auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testMultipleStreamReads() throws Exception { System.out.println("go time"); String myMessage = "{this is my message: héÿ}\n"; byte[] bytes = myMessage.substring(0, myMessage.length()/2).getBytes(Charsets.UTF_8); byte[] bytes2 = myMessage.substring(myMessage.length()/2, myMessage.length()).getBytes(Charsets.UTF_8); InputStream miniStream = new ByteArrayInputStream(bytes); InputStream miniStream2 = new ByteArrayInputStream(bytes2); InputStream stream = new SplitInputStream(Lists.newArrayList(miniStream, miniStream2)); DelimitedStreamReader r = new DelimitedStreamReader(stream, Charsets.UTF_8, myMessage.length() / 3); String msg = r.read(myMessage.length()); assertEquals(msg, myMessage); }

Target:
public void testMultipleStreamReads() throws Exception { String myMessage = "{this is my message: héÿ}\n"; byte[] bytes = myMessage.substring(0, myMessage.length()/2).getBytes(Charsets.UTF_8); byte[] bytes2 = myMessage.substring(myMessage.length()/2, myMessage.length()).getBytes(Charsets.UTF_8); InputStream miniStream = new ByteArrayInputStream(bytes); InputStream miniStream2 = new ByteArrayInputStream(bytes2); InputStream stream = new SplitInputStream(Lists.newArrayList(miniStream, miniStream2)); DelimitedStreamReader r = new DelimitedStreamReader(stream, Charsets.UTF_8, myMessage.length() / 3); String msg = r.read(myMessage.length()); assertEquals(msg, myMessage); }
Source:
public void testBatchBySize() throws Exception { BatchIterator<Integer> batchIterator = InMemoryBatchIterator.of(() -> IntStream.range(0, 5).iterator(), null, true); BatchIterator<List<Integer>> batchedIt = BatchIterators.partition(batchIterator, 2, ArrayList::new, List::add, r -> false); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(0, 1))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(2, 3))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Collections.singletonList(4))); }

Target:
public void testBatchBySize() throws Exception { var batchIterator = InMemoryBatchIterator.of(() -> IntStream.range(0, 5).iterator(), null, false); BatchIterator<List<Integer>> batchedIt = BatchIterators.partition(batchIterator, 2, ArrayList::new, List::add, r -> false); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(0, 1))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(2, 3))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Collections.singletonList(4))); }
Source:
public static SchedulingPolicy map(VDSGroup entity, SchedulingPolicy template) { SchedulingPolicy model = template != null ? template : new SchedulingPolicy(); if (entity.getClusterPolicyName() != null) { model.setPolicy(entity.getClusterPolicyName()); if (entity.getClusterPolicyProperties() != null && !entity.getClusterPolicyProperties().isEmpty()) { model.setThresholds(new SchedulingPolicyThresholds()); String lowUtilization = entity.getClusterPolicyProperties().get(LOW_UTILIZATION); String highUtilization = entity.getClusterPolicyProperties().get(HIGH_UTILIZATION); String cpuOverCommitDurationMinutes = entity.getClusterPolicyProperties().get(CPU_OVER_COMMIT_DURATION_MINUTES); if (lowUtilization != null) { model.getThresholds().setLow(Integer.parseInt(lowUtilization)); } if (highUtilization != null) { model.getThresholds().setHigh(Integer.parseInt(highUtilization)); } if (cpuOverCommitDurationMinutes != null) { int duration = Integer.parseInt(cpuOverCommitDurationMinutes) * 60; model.getThresholds().setDuration(duration); } } } return model; }

Target:
public static SchedulingPolicy map(VDSGroup entity, SchedulingPolicy template) { SchedulingPolicy model = template != null ? template : new SchedulingPolicy(); if (entity.getClusterPolicyName() != null) { model.setPolicy(entity.getClusterPolicyName().toLowerCase()); if (entity.getClusterPolicyProperties() != null && !entity.getClusterPolicyProperties().isEmpty()) { model.setThresholds(new SchedulingPolicyThresholds()); String lowUtilization = entity.getClusterPolicyProperties().get(LOW_UTILIZATION); String highUtilization = entity.getClusterPolicyProperties().get(HIGH_UTILIZATION); String cpuOverCommitDurationMinutes = entity.getClusterPolicyProperties().get(CPU_OVER_COMMIT_DURATION_MINUTES); if (lowUtilization != null) { model.getThresholds().setLow(Integer.parseInt(lowUtilization)); } if (highUtilization != null) { model.getThresholds().setHigh(Integer.parseInt(highUtilization)); } if (cpuOverCommitDurationMinutes != null) { int duration = Integer.parseInt(cpuOverCommitDurationMinutes) * 60; model.getThresholds().setDuration(duration); } } } return model; }
Source:
protected List<Brick> setupDataCategoryList(Context context) { List<Brick> dataBrickList = new ArrayList<>(); dataBrickList.add(new SetVariableBrick(BrickValues.SET_VARIABLE)); dataBrickList.add(new ChangeVariableBrick(BrickValues.CHANGE_VARIABLE)); dataBrickList.add(new ShowTextBrick(BrickValues.X_POSITION, BrickValues.Y_POSITION)); dataBrickList.add(new ShowTextColorSizeAlignmentBrick(BrickValues.X_POSITION, BrickValues.Y_POSITION, BrickValues.RELATIVE_SIZE_IN_PERCENT, BrickValues.SHOW_VARIABLE_COLOR)); dataBrickList.add(new HideTextBrick()); dataBrickList.add(new AddItemToUserListBrick(BrickValues.ADD_ITEM_TO_USERLIST)); dataBrickList.add(new DeleteItemOfUserListBrick(BrickValues.DELETE_ITEM_OF_USERLIST)); dataBrickList.add(new InsertItemIntoUserListBrick(BrickValues.INSERT_ITEM_INTO_USERLIST_VALUE, BrickValues.INSERT_ITEM_INTO_USERLIST_INDEX)); dataBrickList.add(new ReplaceItemInUserListBrick(BrickValues.REPLACE_ITEM_IN_USERLIST_VALUE, BrickValues.REPLACE_ITEM_IN_USERLIST_INDEX)); dataBrickList.add(new AskBrick(context.getString(R.string.brick_ask_default_question))); dataBrickList.add(new AskSpeechBrick(context.getString(R.string.brick_ask_speech_default_question))); if (BuildConfig.DEBUG) { dataBrickList.add(new WebRequestBrick(context.getString(R.string.brick_web_request_default_value))); } return dataBrickList; }

Target:
protected List<Brick> setupDataCategoryList(Context context) { List<Brick> dataBrickList = new ArrayList<>(); dataBrickList.add(new SetVariableBrick(BrickValues.SET_VARIABLE)); dataBrickList.add(new ChangeVariableBrick(BrickValues.CHANGE_VARIABLE)); dataBrickList.add(new ShowTextBrick(BrickValues.X_POSITION, BrickValues.Y_POSITION)); dataBrickList.add(new ShowTextColorSizeAlignmentBrick(BrickValues.X_POSITION, BrickValues.Y_POSITION, BrickValues.RELATIVE_SIZE_IN_PERCENT, BrickValues.SHOW_VARIABLE_COLOR)); dataBrickList.add(new HideTextBrick()); dataBrickList.add(new WriteVariableOnDeviceBrick()); dataBrickList.add(new AddItemToUserListBrick(BrickValues.ADD_ITEM_TO_USERLIST)); dataBrickList.add(new DeleteItemOfUserListBrick(BrickValues.DELETE_ITEM_OF_USERLIST)); dataBrickList.add(new InsertItemIntoUserListBrick(BrickValues.INSERT_ITEM_INTO_USERLIST_VALUE, BrickValues.INSERT_ITEM_INTO_USERLIST_INDEX)); dataBrickList.add(new ReplaceItemInUserListBrick(BrickValues.REPLACE_ITEM_IN_USERLIST_VALUE, BrickValues.REPLACE_ITEM_IN_USERLIST_INDEX)); dataBrickList.add(new AskBrick(context.getString(R.string.brick_ask_default_question))); dataBrickList.add(new AskSpeechBrick(context.getString(R.string.brick_ask_speech_default_question))); if (BuildConfig.FEATURE_WEBREQUEST_BRICK_ENABLED) { dataBrickList.add(new WebRequestBrick(context.getString(R.string.brick_web_request_default_value))); } return dataBrickList; }
Source:
public LedgerMetadata(int ensembleSize, int writeQuorumSize, int ackQuorumSize, BookKeeper.DigestType digestType, byte[] password, Map<String, byte[]> customMetadata, LedgerType ledgerType) { this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.ctime = System.currentTimeMillis(); this.length = 0; this.state = LedgerMetadataFormat.State.OPEN; this.lastEntryId = LedgerHandle.INVALID_ENTRY_ID; this.metadataFormatVersion = CURRENT_METADATA_FORMAT_VERSION; this.digestType = digestType.equals(BookKeeper.DigestType.MAC) ? LedgerMetadataFormat.DigestType.HMAC : LedgerMetadataFormat.DigestType.CRC32; this.ledgerType = ledgerType.equals(LedgerType.VD_JOURNAL) ? LedgerMetadataFormat.LedgerType.VD_JOURNAL : LedgerMetadataFormat.LedgerType.PD_JOURNAL; this.password = Arrays.copyOf(password, password.length); this.hasPassword = true; if (customMetadata != null) { this.customMetadata = customMetadata; } }

Target:
public LedgerMetadata(int ensembleSize, int writeQuorumSize, int ackQuorumSize, BookKeeper.DigestType digestType, byte[] password, Map<String, byte[]> customMetadata, LedgerType ledgerType) { this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.ctime = System.currentTimeMillis(); this.length = 0; this.state = LedgerMetadataFormat.State.OPEN; this.lastEntryId = LedgerHandle.INVALID_ENTRY_ID; this.metadataFormatVersion = CURRENT_METADATA_FORMAT_VERSION; this.digestType = digestType.equals(BookKeeper.DigestType.MAC) ? LedgerMetadataFormat.DigestType.HMAC : LedgerMetadataFormat.DigestType.CRC32; this.ledgerType = ledgerType.equals(LedgerType.VD_JOURNAL) ? DataFormats.LedgerType.VD_JOURNAL : DataFormats.LedgerType.PD_JOURNAL; this.password = Arrays.copyOf(password, password.length); this.hasPassword = true; if (customMetadata != null) { this.customMetadata = customMetadata; } }
Source:
private static boolean isEntry(ITmfEvent event) { String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); return "B" == phase || phase == "s"; }

Target:
private static boolean isEntry(ITmfEvent event) { String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); return "B".equals(phase) || "s".equals(phase); }
Source:
public void update_copiesAllEntriesFromSourceDBToDestinationDB_fetchedByWaterMark() throws SQLException { Indexer indexer = new Indexer(sourceDB, destinationDB); ResultSet resultSet = mock(ResultSet.class); int currentWaterMark = 0; when(destinationDB.currentWaterMark()).thenReturn(currentWaterMark); when(sourceDB.read(currentWaterMark)).thenReturn(resultSet); indexer.update(); verify(sourceDB).read(currentWaterMark); verify(destinationDB).write(resultSet); }

Target:
public void update_copiesAllEntriesFromSourceDBToDestinationDB_fetchedByWaterMark() throws SQLException { Indexer indexer = new Indexer(sourceDB, destinationDB); ResultSet resultSet = mock(ResultSet.class); int currentWaterMark = 0; when(destinationDB.currentWaterMark()).thenReturn(currentWaterMark); when(sourceDB.read(currentWaterMark)).thenReturn(resultSet); indexer.update(); verify(destinationDB).write(resultSet); }
Source:
private void onReplicaResponse(ReplicaId replicaId) { boolean isReplicaFound = false; for (String dataCenter : replicasInFlightPerDatacenter.keySet()) { List<ReplicaId> replicasInFlight = replicasInFlightPerDatacenter.get(dataCenter); if (replicasInFlight.contains(replicaId)) { replicasInFlight.remove(replicaId); isReplicaFound = true; replicasInFlightPerDatacenter.get(dataCenter).clear(); replicasInFlightPerDatacenter.get(dataCenter).addAll(replicasInFlight); if (dataCenter.equalsIgnoreCase(localDataCenterName)) { if (replicaListPerDatacenter.get(localDataCenterName) == null && replicasInFlightPerDatacenter.get(localDataCenterName).size() == 0) { isLocalDone = true; requestParallelism = requestParallelism * remoteDataCenterCount; } } break; } } if (!isReplicaFound) { logger.error("Found response for which no request was sent ", new CoordinatorException("Found response from " + replicaId + "replica for which no request was sent ", CoordinatorError.UnexpectedInternalError)); } }

Target:
private void onReplicaResponse(ReplicaId replicaId) { String dataCenter = replicaId.getDataNodeId().getDatacenterName(); List<ReplicaId> replicasInFlight = replicasInFlightPerDatacenter.get(dataCenter); if (replicasInFlight.contains(replicaId)) { replicasInFlight.remove(replicaId); if (dataCenter.equals(localDataCenterName)) { if (replicaListPerDatacenter.get(localDataCenterName).size() == 0 && replicasInFlight.size() == 0) { isLocalDone = true; requestParallelism = requestParallelism * remoteDataCenterCount; } } } else { logger.error("Found response for which no request was sent " + replicaId); coordinatorMetrics.unknownReplicaResponseError.inc(); } }
Source:
public boolean tryReserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); if (getFreeBytes() - bytes < 0) { return false; } synchronized (this) { reservedBytes += bytes; } if (bytes != 0) { while (true) { if (queryMemoryReservations.computeIfPresent(queryId, (ignored, value) -> value + bytes) != null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, false); break; } synchronized (this) { if (queryMemoryReservations.putIfAbsent(queryId, bytes) == null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, true); break; } } } } onMemoryReserved(); return true; }

Target:
public boolean tryReserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); synchronized (this) { if (getFreeBytes() - bytes < 0) { return false; } reservedBytes += bytes; } if (bytes != 0) { while (true) { if (queryMemoryReservations.computeIfPresent(queryId, (ignored, value) -> value + bytes) != null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, false); break; } synchronized (this) { if (queryMemoryReservations.putIfAbsent(queryId, bytes) == null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, true); break; } } } } onMemoryReserved(); return true; }
Source:
protected void executeCommand() { VdsActionParameters parameters = new VdsActionParameters(getVdsId()); parameters.setLockProperties(LockProperties.create(LockProperties.Scope.Execution).withWait(true)); VdcReturnValueBase returnValue = runInternalAction(VdcActionType.RefreshHostCapabilities, parameters); if (!returnValue.getSucceeded()) { return; } returnValue = runInternalAction(VdcActionType.RefreshHostDevices, parameters); if (!returnValue.getSucceeded()) { return; } setSucceeded(true); }

Target:
protected void executeCommand() { VdsActionParameters parameters = new VdsActionParameters(getVdsId()); parameters.setLockProperties( LockProperties.create(LockProperties.Scope.Execution).withWait(isInternalExecution())); VdcReturnValueBase returnValue = runInternalAction(VdcActionType.RefreshHostCapabilities, parameters); if (!returnValue.getSucceeded()) { return; } returnValue = runInternalAction(VdcActionType.RefreshHostDevices, parameters); if (!returnValue.getSucceeded()) { return; } setSucceeded(true); }
Source:
private void uploadMissing(Map<Digest, Path> files, Map<Digest, ByteString> blobs) throws IOException, InterruptedException { List<ListenableFuture<Void>> uploads = new ArrayList<>(); for (Map.Entry<Digest, Path> entry : files.entrySet()) { uploads.add(cacheProtocol.uploadFile(entry.getKey(), entry.getValue())); } for (Map.Entry<Digest, ByteString> entry : blobs.entrySet()) { uploads.add(cacheProtocol.uploadBlob(entry.getKey(), entry.getValue())); } InterruptedException interruptedException = null; BulkTransferException bulkTransferException = null; boolean interrupted = Thread.currentThread().isInterrupted(); for (ListenableFuture<Void> upload : uploads) { try { upload.get(); } catch (ExecutionException e) { if (bulkTransferException != null) { bulkTransferException = new BulkTransferException(); } Throwable cause = e.getCause(); IOException ioEx; if (cause instanceof IOException) { ioEx = new IOException(cause); } else { ioEx = (IOException) cause; } bulkTransferException.add(ioEx); } catch (InterruptedException e) { interrupted = Thread.interrupted() || interrupted; interruptedException = e; } } if (interruptedException != null) { if (bulkTransferException != null) { interruptedException.addSuppressed(bulkTransferException); } throw interruptedException; } if (bulkTransferException != null) { throw bulkTransferException; } }

Target:
private void uploadMissing(Map<Digest, Path> files, Map<Digest, ByteString> blobs) throws IOException, InterruptedException { List<ListenableFuture<Void>> uploads = new ArrayList<>(); for (Map.Entry<Digest, Path> entry : files.entrySet()) { uploads.add(cacheProtocol.uploadFile(entry.getKey(), entry.getValue())); } for (Map.Entry<Digest, ByteString> entry : blobs.entrySet()) { uploads.add(cacheProtocol.uploadBlob(entry.getKey(), entry.getValue())); } waitForBulkTransfer(uploads, false); }
Source:
protected <T> T getValue(Class<T> type, String key) { Object rawProp = getRawProperty(key); if (rawProp == null) { return notFound(key); } if (rawProp instanceof String) { try { String value = interpolator.create(lookup).resolve(rawProp.toString()); if (type.equals(boolean.class) || type.equals(Boolean.class)) { if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { return (T) Boolean.TRUE; } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { return (T) Boolean.FALSE; } return parseError(key, value, new Exception("Expected one of [true, yes, on, false, no, off]")); } return decoder.decode(type, value); } catch (NumberFormatException e) { return parseError(key, rawProp.toString(), e); } } else if (type.isInstance(rawProp)) { return (T)rawProp; } else { return parseError(key, rawProp.toString(), new NumberFormatException("Property " + rawProp.toString() + " is of wrong format " + type.getCanonicalName())); } }

Target:
protected <T> T getValue(Class<T> type, String key) { Object rawProp = getRawProperty(key); if (rawProp == null) { return notFound(key); } if (rawProp instanceof String) { try { String value = interpolator.create(lookup).resolve(rawProp.toString()); return decoder.decode(type, value); } catch (NumberFormatException e) { return parseError(key, rawProp.toString(), e); } } else if (type.isInstance(rawProp)) { return (T)rawProp; } else { return parseError(key, rawProp.toString(), new NumberFormatException("Property " + rawProp.toString() + " is of wrong format " + type.getCanonicalName())); } }
Source:
public void testCreateDirectoriesWithTrailingSlash() throws IOException { Path testBaseDirectoryPath = Paths.get(ConfigCore.getParameter(ParameterCore.DIR_XML_CONFIG)); Path firstDirectoryOfTestPath = testBaseDirectoryPath.resolve("several"); if (Files.isDirectory(firstDirectoryOfTestPath)) { TreeDeleter.deltree(firstDirectoryOfTestPath); } String testBaseDirectoryURI = testBaseDirectoryPath.toUri().toString(); String createDirectories = "several/directories/can/be/created/with/trailing/"; new FileService().createDirectories(URI.create(testBaseDirectoryURI + createDirectories)); assertTrue(Files.isDirectory(firstDirectoryOfTestPath.resolve("directories/can/be/created/with/trailing"))); TreeDeleter.deltree(firstDirectoryOfTestPath); }

Target:
public void testCreateDirectoriesWithTrailingSlash() throws IOException { ServiceManager.getFileService() .createDirectories(URI.create("several/directories/can/be/created/with/trailing/")); assertTrue(ServiceManager.getFileService().isDirectory(URI.create(SEVERAL))); cleanUp(); }
Source:
public void makeHttpRequest(String jobId, Logger logger, List<HttpRequestBase> httpRequestList) { if (httpRequestList == null || httpRequestList.isEmpty()) { logger.info("No HTTP requests to make"); return; } for (HttpRequestBase httpRequest : httpRequestList) { logger.info("Job callback http request: " + httpRequest.toString()); logger.info("headers ["); for (Header header : httpRequest.getAllHeaders()) { logger.info(String.format(" %s : %s", header.getName(), header.getValue())); } logger.info("]"); HttpRequestFutureTask<Integer> task = futureRequestExecutionService.execute(httpRequest, HttpClientContext.create(), new LoggingResonseHandler(logger)); try { Integer statusCode = task.get(responseWaitTimeoutMS, TimeUnit.MILLISECONDS); logger.info("http callback status code: " + statusCode); } catch (TimeoutException timeOutEx) { logger .warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", timeOutEx); } catch (ExecutionException ee) { if (ee.getCause() instanceof SocketTimeoutException) { logger.warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", ee); } else { logger.warn( "Encountered error while waiting for job callback to complete", ee); } } catch (Throwable e) { logger.warn( "Encountered error while waiting for job callback to complete", e); } } }

Target:
public void makeHttpRequest(String jobId, Logger logger, List<HttpRequestBase> httpRequestList) { if (httpRequestList == null || httpRequestList.isEmpty()) { logger.info("No HTTP requests to make"); return; } for (HttpRequestBase httpRequest : httpRequestList) { logger.info("Job callback http request: " + httpRequest.toString()); logger.info("headers ["); for (Header header : httpRequest.getAllHeaders()) { logger.info(String.format(" %s : %s", header.getName(), header.getValue())); } logger.info("]"); HttpRequestFutureTask<Integer> task = futureRequestExecutionService.execute(httpRequest, HttpClientContext.create(), new LoggingResponseHandler(logger)); try { Integer statusCode = task.get(responseWaitTimeoutMS, TimeUnit.MILLISECONDS); logger.info("http callback status code: " + statusCode); } catch (TimeoutException timeOutEx) { logger .warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", timeOutEx); } catch (ExecutionException ee) { if (ee.getCause() instanceof SocketTimeoutException) { logger.warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", ee); } else { logger.warn( "Encountered error while waiting for job callback to complete", ee); } } catch (Throwable e) { logger.warn( "Encountered error while waiting for job callback to complete", e); } } }
Source:
private void injectPortSelectorPropertySource(ConfigurableEnvironment environment) { environment.getPropertySources() .remove(PORT_SELECTOR_PROPERTY_SOURCE); environment.getPropertySources() .addLast(new PropertySource<Integer>(PORT_SELECTOR_PROPERTY_SOURCE) { @Override public Integer getProperty(@NonNull String s) { boolean isK8s = (!"IS_KUBERNETES".equalsIgnoreCase(s)) && "true".equalsIgnoreCase(environment.getProperty("IS_KUBERNETES", "false")); if (SERVER_PORT.equalsIgnoreCase(s)) { return Integer.parseInt(environment.getProperty("PORT_HTTP", environment.getProperty("PORT0", "0"))); } if (HTTPSERVER_CONNECTOR_DEFAULT_HTTP_PORT.equalsIgnoreCase(s)) { return Integer.parseInt(environment.getProperty("PORT_HTTP", environment.getProperty("PORT0", "-1"))); } if (isK8s && s.matches("ot\\.httpserver\\.connector\\..*-.*\\.port")) { final String name = s.split("\\.")[3].split("-")[0].toUpperCase(Locale.US); return Integer.parseInt(environment.getProperty("PORT_" + name, "-1")); } if (JMX_PORT.equalsIgnoreCase(s)) { return Integer.parseInt(environment.getProperty("PORT_JMX", environment.getProperty("PORT1", "0"))); } if (MANAGEMENT_SERVER_PORT.equalsIgnoreCase(s)) { return Integer.parseInt(environment.getProperty("PORT_ACTUATOR", environment.getProperty("PORT2", "0"))); } return null; } }); }

Target:
private void injectPortSelectorPropertySource(ConfigurableEnvironment environment) { environment.getPropertySources() .remove(OtPortSelectorPropertySource.class.getName()); environment.getPropertySources() .remove(OtPortSelectorInfoPropertySource.class.getName()); environment.getPropertySources() .remove(JMX_PROPERTY_SOURCE); ImmutableMap<String, PortSelector.PortSelection> portSelectionMap = ImmutableMap.copyOf(new PortSelector(environment).getPortSelectionMap()); environment.getPropertySources() .addFirst(getPortPropertySource(portSelectionMap)); environment.getPropertySources() .addLast(getPortDebugPropertySource(portSelectionMap)); environment.getPropertySources() .addFirst(getHostPropertySource(environment)); }
Source:
public void setup() throws Exception { mySqlServer = setupMySql(); jdbi = getJdbi(mySqlServer); handle = jdbi.open(); config = new BenchmarkSuiteConfig() .setSuitesTableName(BENCHMARK_SUITES_TABLE) .setQueriesTableName(BENCHMARK_QUERIES_TABLE); }

Target:
public void setup() throws Exception { mySqlServer = setupMySql(); jdbi = getJdbi(mySqlServer); handle = jdbi.open(); }
Source:
public float getFraction() { return mFraction; }

Target:
public @FloatRange(from = 0, to = 1) float getFraction() { return mFraction; }
Source:
HiveMetaStoreClient getHive() throws IOException { if (mHive != null) { try { mHive.getAllDatabases(); } catch (TException e) { LOG.info("Hive metastore client disconnected, attempting to reconnect"); mHive = newHiveClient(); } return mHive; } mHive = newHiveClient(); return mHive; }

Target:
MetaStoreClient getHive() { return mHive; }
Source:
public CompletionServiceResponse doMultiGetRequest(List<String> serverURLs, String tableNameWithType, int timeoutMs) { CompletionServiceResponse completionServiceResponse = new CompletionServiceResponse(); CompletionService<GetMethod> completionService = new MultiGetRequest(_executor, _httpConnectionManager).execute(serverURLs, timeoutMs); for (int i = 0; i < serverURLs.size(); i++) { GetMethod getMethod = null; try { getMethod = completionService.take().get(); URI uri = getMethod.getURI(); String instance = _endpointsToServers.get(uri.getHost() + ":" + uri.getPort()); if (getMethod.getStatusCode() >= 300) { LOGGER.error("Server: returned error: {}", instance, getMethod.getStatusCode()); completionServiceResponse._failedResponseCount++; continue; } completionServiceResponse._httpResponses.put(instance, getMethod.getResponseBodyAsString()); } catch (Exception e) { } finally { if (getMethod != null) { getMethod.releaseConnection(); } } } int numServersResponded = completionServiceResponse._httpResponses.size(); if (numServersResponded != serverURLs.size()) { LOGGER.warn("Finish reading information for table: with {}/{} server responses", tableNameWithType, numServersResponded, serverURLs); } else { LOGGER.info("Finish reading information for table: {}", tableNameWithType); } return completionServiceResponse; }

Target:
public CompletionServiceResponse doMultiGetRequest(List<String> serverURLs, String tableNameWithType, int timeoutMs) { CompletionServiceResponse completionServiceResponse = new CompletionServiceResponse(); CompletionService<GetMethod> completionService = new MultiGetRequest(_executor, _httpConnectionManager).execute(serverURLs, timeoutMs); for (int i = 0; i < serverURLs.size(); i++) { GetMethod getMethod = null; try { getMethod = completionService.take().get(); URI uri = getMethod.getURI(); String instance = _endpointsToServers.get(uri.getHost() + ":" + uri.getPort()); if (getMethod.getStatusCode() >= 300) { LOGGER.error("Server: returned error: {}", instance, getMethod.getStatusCode()); completionServiceResponse._failedResponseCount++; continue; } completionServiceResponse._httpResponses.put(instance, getMethod.getResponseBodyAsString()); } catch (Exception e) { } finally { if (getMethod != null) { getMethod.releaseConnection(); } } } int numServersResponded = completionServiceResponse._httpResponses.size(); if (numServersResponded != serverURLs.size()) { LOGGER.warn("Finished reading information for table: with {}/{} server responses", tableNameWithType, numServersResponded, serverURLs.size()); } else { LOGGER.info("Finished reading information for table: {}", tableNameWithType); } return completionServiceResponse; }
Source:
public OAuthServiceClient(String backendServerURL, String username, String password, ConfigurationContext configCtx) throws Exception { String serviceURL = backendServerURL + "OAuth2TokenValidationService"; try { stub = new OAuth2TokenValidationServiceStub(configCtx, serviceURL); CarbonUtils.setBasicAccessSecurityHeaders(username, password, true, stub._getServiceClient()); } catch (AxisFault e) { log.error("Error initializing OAuth2 Client"); throw new Exception("Error initializing OAuth Client", e); } }

Target:
public OAuthServiceClient(String backendServerURL, String username, String password, ConfigurationContext configCtx) throws AxisFault { String serviceURL = backendServerURL + "OAuth2TokenValidationService"; try { stub = new OAuth2TokenValidationServiceStub(configCtx, serviceURL); CarbonUtils.setBasicAccessSecurityHeaders(username, password, true, stub._getServiceClient()); } catch (AxisFault e) { throw new AxisFault("Error initializing OAuth Client", e); } }
Source:
public void testProgressBar() { EventBus<Event> events = new EventBus<>(); List<Object[]> testContents = Arrays.asList( new Object[]{"Progress bar testing generic String message"}, new Object[]{"Progress bar testing class message", ProgressBarTest.class}, new Object[]{ProgressBarTest.class, "Progress bar testing class message"}, new Object[]{ProgressBarTest.class}, new Object[]{"Progress bar testing mod message", TestMod.class}, new Object[]{TestMod.class, "Progress bar testing mod message"}, new Object[]{TestMod.class}, new Object[]{"Progress bar testing null message", null}, new Object[]{null, "Progress bar testing class message"}, new Object[]{(String) null}, new Object[]{(Class) null}, new Object[]{ProgressBarTest.class, null}, new Object[]{null, ProgressBarTest.class}); List<String> testResults = new LinkedList<>(); events.on(TestProgressBarEvent.class).bind(evt -> testResults.add(evt.message)); ProgressBar progressBar = new AbstractProgressBar() { @Override protected void stepImpl(String message) { events.publish(new TestProgressBarEvent(message)); } }; for (Object[] testArg : testContents) { step(progressBar, testArg); } progressBar.finish(); List<String> expectedResults = testContents.stream().map(ProgressBarTest::convert).collect(Collectors.toList()); assertThat(testResults.size()).isEqualTo(testContents.size()); assertThat(testResults.size()).isEqualTo(expectedResults.size()); for (int i = 0; i < testContents.size(); i++) assertThat(testResults.get(i)).isEqualTo(expectedResults.get(i)); }

Target:
public void testProgressBar() { List<String> testResults = new LinkedList<>(); finishedCounter = 0; ProgressBar progressBar = new AbstractProgressBar() { @Override protected void stepImpl(String message) { testResults.add(message); } @Override protected void finishImpl() { finishedCounter++; } }; progressBar.step("Progress bar testing generic String message"); progressBar.step("Progress bar testing class message", ProgressBarTest.class); progressBar.step(ProgressBarTest.class, "Progress bar testing class message"); progressBar.step(ProgressBarTest.class); progressBar.step("Progress bar testing mod message", TestMod.class); progressBar.step(TestMod.class, "Progress bar testing mod message"); progressBar.step(TestMod.class); progressBar.step("Progress bar testing null message", null); progressBar.step(null, "Progress bar testing null message"); progressBar.step((String)null); progressBar.step((Class)null); progressBar.step(ProgressBarTest.class, null); progressBar.step(null, ProgressBarTest.class); progressBar.finish(); progressBar.finish(); assertThat(testResults).containsExactly(new String[] { "Progress bar testing generic String message", "Progress bar testing class message: ProgressBarTest", "ProgressBarTest: Progress bar testing class message", "ProgressBarTest", "Progress bar testing mod message: Test Mod", "Test Mod: Progress bar testing mod message", "Test Mod", "Progress bar testing null message: null", "null: Progress bar testing null message", null, null, "ProgressBarTest", "ProgressBarTest" }); assertThat(progressBar.isFinished()).isTrue(); assertThat(finishedCounter).isEqualTo(1); }
Source:
protected List<PreviousCommit> findPreviousCommits() throws IOException { List<PreviousCommit> result = new ArrayList<PreviousCommit>(); Repository repository = getRepository(); IResource resource = getSelectedResources()[0]; String path = RepositoryMapping.getMapping(resource.getProject()) .getRepoRelativePath(resource); RevWalk rw = new RevWalk(repository); rw.sort(RevSort.COMMIT_TIME_DESC); try { if (path.length() > 0) { DiffConfig diffConfig = repository.getConfig().get( DiffConfig.KEY); FollowFilter filter = FollowFilter.create(path, diffConfig); rw.setTreeFilter(filter); } RevCommit headCommit = rw.parseCommit(repository.getRef( Constants.HEAD).getObjectId()); rw.markStart(headCommit); headCommit = rw.next(); if (headCommit == null) return result; List<RevCommit> directParents = Arrays.asList(headCommit .getParents()); RevCommit previousCommit = rw.next(); while (previousCommit != null && result.size() < directParents.size()) { if (directParents.contains(previousCommit)) { String previousPath = getPreviousPath(repository, rw.getObjectReader(), headCommit, previousCommit, path); result.add(new PreviousCommit(previousCommit, previousPath)); } previousCommit = rw.next(); } } finally { rw.dispose(); } return result; }

Target:
protected List<PreviousCommit> findPreviousCommits() throws IOException { List<PreviousCommit> result = new ArrayList<PreviousCommit>(); Repository repository = getRepository(); IResource resource = getSelectedResources()[0]; String path = RepositoryMapping.getMapping(resource.getProject()) .getRepoRelativePath(resource); RevWalk rw = new RevWalk(repository); rw.sort(RevSort.COMMIT_TIME_DESC, true); rw.sort(RevSort.BOUNDARY, true); try { if (path.length() > 0) { DiffConfig diffConfig = repository.getConfig().get( DiffConfig.KEY); FollowFilter filter = FollowFilter.create(path, diffConfig); rw.setTreeFilter(filter); } RevCommit headCommit = rw.parseCommit(repository.getRef( Constants.HEAD).getObjectId()); rw.markStart(headCommit); headCommit = rw.next(); if (headCommit == null) return result; List<RevCommit> directParents = Arrays.asList(headCommit .getParents()); RevCommit previousCommit = rw.next(); while (previousCommit != null && result.size() < directParents.size()) { if (directParents.contains(previousCommit)) { String previousPath = getPreviousPath(repository, rw.getObjectReader(), headCommit, previousCommit, path); result.add(new PreviousCommit(previousCommit, previousPath)); } previousCommit = rw.next(); } } finally { rw.dispose(); } return result; }
Source:
protected void initDetailModels() { super.initDetailModels(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmInterfaceListModel()); VmDiskListModel diskListModel = new VmDiskListModel(); diskListModel.setSystemTreeContext(this); list.add(diskListModel); list.add(new VmSnapshotListModel()); list.add(new VmEventListModel()); list.add(new VmAppListModel()); list.add(new PermissionListModel()); list.add(new VmAffinityGroupListModel(VdcQueryType.GetAffinityGroupsByVmId)); list.add(new VmSessionsModel()); setDetailModels(list); }

Target:
protected void initDetailModels() { super.initDetailModels(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmInterfaceListModel()); VmDiskListModel diskListModel = new VmDiskListModel(); diskListModel.setSystemTreeContext(this); list.add(diskListModel); list.add(new VmSnapshotListModel()); list.add(new VmEventListModel()); list.add(new VmAppListModel()); list.add(new PermissionListModel()); list.add(new VmAffinityGroupListModel()); list.add(new VmSessionsModel()); setDetailModels(list); }
Source:
public void applyProjection(int[][] projectedFields) { this.projectedFields = new int[projectedFields.length]; FieldsDataType dataType = (FieldsDataType) physicalRowDataType; RowType rowType = ((RowType) physicalRowDataType.getLogicalType()); DataTypes.Field[] fields = new DataTypes.Field[projectedFields.length]; for (int i = 0; i < projectedFields.length; ++i) { int[] projection = projectedFields[i]; Preconditions.checkArgument(projection.length == 1); int index = projection[0]; this.projectedFields[i] = index; String fieldName = rowType.getFieldNames().get(index); fields[i] = DataTypes.FIELD(fieldName, dataType.getFieldDataTypes().get(fieldName)); } this.physicalRowDataType = DataTypes.ROW(fields); }

Target:
public void applyProjection(int[][] projectedFields) { this.projectedFields = new int[projectedFields.length]; FieldsDataType dataType = (FieldsDataType) physicalRowDataType; RowType rowType = ((RowType) physicalRowDataType.getLogicalType()); DataTypes.Field[] fields = new DataTypes.Field[projectedFields.length]; for (int i = 0; i < projectedFields.length; ++i) { int[] projection = projectedFields[i]; Preconditions.checkArgument(projection.length == 1); int index = projection[0]; this.projectedFields[i] = index; fields[i] = DataTypes.FIELD(rowType.getFieldNames().get(index), dataType.getChildren().get(index)); } this.physicalRowDataType = DataTypes.ROW(fields); }
Source:
public boolean process(final Exchange exchange, final AsyncCallback callback) { Operation operation = getOperation(exchange); LOG.debug("Executing operation", operation); switch (operation) { case PUBLISH: { doPublish(exchange, callback); break; } case FIRE: { doFire(exchange, callback); break; } case GETHISTORY: { doGetHistory(exchange, callback); break; } case GETSTATE: { doGetState(exchange, callback); break; } case HERENOW: { doHereNow(exchange, callback); break; } case SETSTATE: { doSetState(exchange, callback); break; } case WHERENOW: { doWhereNow(exchange, callback); break; } default: throw new UnsupportedOperationException(operation.toString()); } if (exchange.getException() != null) { if (exchange.getException() instanceof PubNubException) { LOG.error("Exception from PubNub : {}", exchange.getException(PubNubException.class).getPubnubError().getMessage()); } callback.done(true); return true; } return false; }

Target:
public boolean process(final Exchange exchange, final AsyncCallback callback) { Operation operation = getOperation(exchange); LOG.debug("Executing operation", operation); try { switch (operation) { case PUBLISH: { doPublish(exchange, callback); break; } case FIRE: { doFire(exchange, callback); break; } case GETHISTORY: { doGetHistory(exchange, callback); break; } case GETSTATE: { doGetState(exchange, callback); break; } case HERENOW: { doHereNow(exchange, callback); break; } case SETSTATE: { doSetState(exchange, callback); break; } case WHERENOW: { doWhereNow(exchange, callback); break; } default: throw new UnsupportedOperationException(operation.toString()); } } catch (Exception e) { exchange.setException(e); callback.done(true); return true; } return false; }
Source:
public void populateDAG(DAG dag, Configuration configuration) { testInput.length(); }

Target:
public void populateDAG(DAG dag, Configuration configuration) { if (testInput == null) { throw new NullPointerException(); } TestModuleOperator testModuleOperator = dag.addOperator("testModuleOperator", TestModuleOperator.class); testModuleOperator.setTestInput(this.getTestInput()); }
Source:
protected void run() throws Exception { try (Git git = new Git(db)) { PushCommand push = git.push(); push.setDryRun(dryRun); push.setForce(force); push.setProgressMonitor(new TextProgressMonitor(errw)); push.setReceivePack(receivePack); push.setRefSpecs(refSpecs); if (all) push.setPushAll(); if (tags) push.setPushTags(); push.setRemote(remote); push.setThin(thin); push.setAtomic(atomic); push.setTimeout(timeout); if (pushOptions.isEmpty()) { push.setPushOptions(null); } else { push.setPushOptions(pushOptions); } Iterable<PushResult> results = push.call(); for (PushResult result : results) { try (ObjectReader reader = db.newObjectReader()) { printPushResult(reader, result.getURI(), result); } } } }

Target:
protected void run() throws Exception { try (Git git = new Git(db)) { PushCommand push = git.push(); push.setDryRun(dryRun); push.setForce(force); push.setProgressMonitor(new TextProgressMonitor(errw)); push.setReceivePack(receivePack); push.setRefSpecs(refSpecs); if (all) push.setPushAll(); if (tags) push.setPushTags(); push.setRemote(remote); push.setThin(thin); push.setAtomic(atomic); push.setTimeout(timeout); if (!pushOptions.isEmpty()) { push.setPushOptions(pushOptions); } Iterable<PushResult> results = push.call(); for (PushResult result : results) { try (ObjectReader reader = db.newObjectReader()) { printPushResult(reader, result.getURI(), result); } } } }
Source:
private void processElementWithoutRowNumber(RowData input, Collector<RowData> out) throws Exception { if (buffer.getCurrentTopNum() > rankEnd) { Map.Entry<RowData, Collection<RowData>> lastEntry = buffer.lastEntry(); RowData lastKey = lastEntry.getKey(); List<RowData> lastList = (List<RowData>) lastEntry.getValue(); int size = lastList.size(); RowData lastElement = null; if (size > 0) { lastElement = lastList.get(size - 1); } if (size <= 1) { buffer.removeAll(lastKey); dataState.remove(lastKey); } else { buffer.remove(lastKey, lastElement); dataState.put(lastKey, lastList); } if (size == 0 || input.equals(lastElement)) { return; } else { collectDelete(out, lastElement); } } collectInsert(out, input); }

Target:
private void processElementWithoutRowNumber(RowData input, Collector<RowData> out) throws Exception { if (buffer.getCurrentTopNum() > rankEnd) { Map.Entry<RowData, Collection<RowData>> lastEntry = buffer.lastEntry(); RowData lastKey = lastEntry.getKey(); Collection<RowData> lastList = lastEntry.getValue(); RowData lastElement = buffer.lastElement(); int size = lastList.size(); if (size <= 1) { buffer.removeAll(lastKey); dataState.remove(lastKey); } else { buffer.removeLast(); dataState.put(lastKey, new ArrayList<>(lastList)); } if (size == 0 || input.equals(lastElement)) { return; } else { collectDelete(out, lastElement); } } collectInsert(out, input); }
Source:
void account_credentials_are_valid_for_a_gateway_account(String type) { var gatewayAccount = aGatewayAccountEntity().withType(GatewayAccountEntity.Type.fromString(type)).build(); when(gatewayAccountService.getGatewayAccount(gatewayAccount.getId())).thenReturn(Optional.of(gatewayAccount)); when(response.getStatus()).thenReturn(HttpStatus.SC_OK); var flexCredentials = new Worldpay3dsFlexCredentials("53f0917f101a4428b69d5fb0", "57992a087a0c4849895ab8a2", "4cabd5d2-0133-4e82-b0e5-2024dbeddaa9"); assertTrue(service.validateCredentials(gatewayAccount.getId(), flexCredentials)); verify(client).target(threeDsFlexDdcUrls.get(type)); verify(worldpay3dsFlexJwtService).generateDdcToken(eq(GatewayAccount.valueOf(gatewayAccount)), eq(flexCredentials), any(ZonedDateTime.class)); verify(invocationBuilder).post(entityArgumentCaptor.capture()); assertEquals(((Form) entityArgumentCaptor.getValue().getEntity()).asMap(), new MultivaluedHashMap<String, String>() {{ add("JWT", DDC_TOKEN); }}); assertEquals(entityArgumentCaptor.getValue().getMediaType(), MediaType.APPLICATION_FORM_URLENCODED_TYPE); }

Target:
void account_credentials_are_valid_for_a_gateway_account(String type) { var gatewayAccount = aGatewayAccountEntity().withType(GatewayAccountEntity.Type.fromString(type)).build(); var flexCredentials = new Worldpay3dsFlexCredentials("53f0917f101a4428b69d5fb0", "57992a087a0c4849895ab8a2", "4cabd5d2-0133-4e82-b0e5-2024dbeddaa9"); when(response.getStatus()).thenReturn(HttpStatus.SC_OK); when(client.target(threeDsFlexDdcUrls.get(type))).thenReturn(webTarget); when(worldpay3dsFlexJwtService.generateDdcToken(eq(GatewayAccount.valueOf(gatewayAccount)), eq(flexCredentials), any(ZonedDateTime.class))).thenReturn(DDC_TOKEN); var expectedFormData = new MultivaluedHashMap<String, String>(){{add("JWT", DDC_TOKEN);}}; when(invocationBuilder.post(argThat(new EntityMatcher(Entity.form(expectedFormData))))).thenReturn(response); assertTrue(service.validateCredentials(gatewayAccount, flexCredentials)); }
Source:
protected void setMultipleColumnItems(List<String> names, List<String> timestamps) { this.items.clearAll(); int i = 0; String[] columns = new String[2]; if (timestamps.size() == 0) { setItems(names); } else { for (String name : names) { TableItem item = new TableItem(this.items, SWT.NONE); columns[0] = name; columns[1] = timestamps.get(i); item.setText(columns); i++; } } }

Target:
protected void setMultipleColumnItems(List<String> names, List<String> timestamps) { this.items.clearAll(); int i = 0; String[] columns = new String[2]; if (timestamps.size() != names.size()) { LOG.error("Got mismatched timestamps and names"); setItems(names); } else { for (String name : names) { TableItem item = new TableItem(this.items, SWT.NONE); columns[0] = name; columns[1] = timestamps.get(i); item.setText(columns); i++; } } }
Source:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } int offset = 0; CompletableFuture[] futures = new CompletableFuture[5]; long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (e) { value = e.getValue(); lifespan = e.getLifespan(); maxIdle = e.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, e.getLastUsed(), currentTimeMillis); } if (expiredMortal) { offset = addAndWaitIfFull(handleLifespanExpireEntry(e.getKey(), value, lifespan), futures, offset); } else if (expiredTransient) { offset = addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(e.getKey(), value, maxIdle), futures, offset); } } } if (offset != 0) { CompletableFuture.allOf(Arrays.copyOf(futures, offset)).join(); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }

Target:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } int offset = 0; CompletableFuture[] futures = new CompletableFuture[MAX_ASYNC_EXPIRATIONS]; long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (e) { value = e.getValue(); lifespan = e.getLifespan(); maxIdle = e.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, e.getLastUsed(), currentTimeMillis); } if (expiredMortal) { offset = addAndWaitIfFull(handleLifespanExpireEntry(e.getKey(), value, lifespan), futures, offset); } else if (expiredTransient) { offset = addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(e.getKey(), value, maxIdle), futures, offset); } } } if (offset != 0) { CompletableFuture.allOf(Arrays.copyOf(futures, offset)).join(); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }