auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onCompleted() { while (true) { final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, NOT_REQUESTED_COMPLETED)) { return; } } else if (s == REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(REQUESTED_NOT_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else return; } }

Target:
public void onCompleted() { if (last == ABSENT) { child.onCompleted(); return; } while (true) { final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, NOT_REQUESTED_COMPLETED)) { return; } } else if (s == REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(REQUESTED_NOT_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else return; } }
Source:
public void consumerPrefetch(TestContext context) throws Exception { int count = 3; int amountOfUnAckMessages = count - 1; Async prefetchDone = context.async(); client.basicQos(amountOfUnAckMessages, done -> prefetchDone.countDown()); prefetchDone.await(); Set<String> messages = createMessages(count); String queue = setupQueue(messages); String address = queue + ".address"; Async receivedExpectedNumberOfMessages = context.async(amountOfUnAckMessages); vertx.eventBus().consumer(address, msg -> { if (receivedExpectedNumberOfMessages.isCompleted()) { context.fail(); } else { receivedExpectedNumberOfMessages.countDown(); } }); client.basicConsume(queue, address, false, onSuccess(v -> { })); receivedExpectedNumberOfMessages.await(); Thread.sleep(1000); }

Target:
public void consumerPrefetch(TestContext context) throws Exception { int count = 3; int amountOfUnAckMessages = count - 1; Async prefetchDone = context.async(); client.basicQos(amountOfUnAckMessages, done -> prefetchDone.countDown()); prefetchDone.await(); Set<String> messages = createMessages(count); String queue = setupQueue(messages); String address = queue + ".address"; Async receivedExpectedNumberOfMessages = context.async(amountOfUnAckMessages); vertx.eventBus().consumer(address, msg -> { if (receivedExpectedNumberOfMessages.isCompleted()) { context.fail(); } else { receivedExpectedNumberOfMessages.countDown(); } }); client.basicConsume(queue, address, false, onSuccess(v -> { })); receivedExpectedNumberOfMessages.await(); Async async = context.async(); vertx.setTimer(1000, spent -> async.countDown()); }
Source:
void updateEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }

Target:
void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }
Source:
public void releaseStore(Store<?, ?> resource) { Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.get(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } CacheStore cacheStore = (CacheStore) resource; entry.getKey().releaseCachingTier(cacheStore.cachingTier()); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }

Target:
public void releaseStore(Store<?, ?> resource) { Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.get(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } CacheStore cacheStore = (CacheStore) resource; entry.getKey().releaseCachingTier(cacheStore.realCachingTier); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }
Source:
probeResult processClusters(long nowMs) { synchronized (critSect) { List<Cluster> clusters = new ArrayList<Cluster>(); clusters = computeClusters(clusters); if (clusters.isEmpty()) { if (probes_.size() >= kMaxProbePackets) probes_.get(0); return probeResult.kNoUpdate; } Cluster bestProbe = findBestProbe(clusters); if (bestProbe != null) { int probeBitrateBps = Math.min(bestProbe.getSendBitrateBps(), bestProbe .getRecvBitrateBps()); if (isBitrateImproving(probeBitrateBps)) { logger.warn("Probe successful, sent at " + bestProbe.getSendBitrateBps() + " bps, received at " + bestProbe.getRecvBitrateBps() + " bps. Mean send delta: " + bestProbe.sendMeanMs + " ms, mean recv delta: " + bestProbe.recvMeanMs + " ms, num probes: " + bestProbe.count); remoteRate.setEstimate(probeBitrateBps, nowMs); return probeResult.kBitrateUpdated; } } if (clusters.size() >= kExpectedNumberOfProbes) probes_.clear(); return probeResult.kNoUpdate; } }

Target:
private ProbeResult processClusters(long nowMs) { synchronized (critSect) { List<Cluster> clusters = new ArrayList<Cluster>(); computeClusters(clusters); if (clusters.isEmpty()) { if (probes_.size() >= kMaxProbePackets) probes_.remove(0); return ProbeResult.kNoUpdate; } Cluster bestProbe = findBestProbe(clusters); int probeBitrateBps = Math.min(bestProbe.getSendBitrateBps(), bestProbe .getRecvBitrateBps()); if (isBitrateImproving(probeBitrateBps)) { logger.warn("Probe successful, sent at " + bestProbe.getSendBitrateBps() + " bps, received at " + bestProbe.getRecvBitrateBps() + " bps. Mean send delta: " + bestProbe.sendMeanMs + " ms, mean recv delta: " + bestProbe.recvMeanMs + " ms, num probes: " + bestProbe.count); remoteRate.setEstimate(probeBitrateBps, nowMs); return ProbeResult.kBitrateUpdated; } if (clusters.size() >= kExpectedNumberOfProbes) probes_.clear(); return ProbeResult.kNoUpdate; } }
Source:
public List<UserFromView> getTableFromView() { List<UserFromView> usersList = new LinkedList<>(); int pagination = 0; driver.findElement(SHOW_10_ITEMS.getBy()).click(); do { if (driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()).size() <= 1) { return usersList; } else { List<WebElement> rowsList = driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()); for (int j = 1; j < rowsList.size(); j++) { List<WebElement> cellsList = rowsList.get(j).findElements(AdministrationPageLocators.ROW_CELLS.getBy()); usersList.add(UserFromView.newBuilder() .firstName(cellsList.get(0).getText()) .lastName(cellsList.get(1).getText()) .login(cellsList.get(2).getText()) .role(cellsList.get(3).getText()) .region(cellsList.get(4).getText()) .build()); } } pagination++; clickNextButton(); } while (pagination < getQuantityOfTablePages()); clickFirstButton(); return usersList; }

Target:
public List<UserFromView> getTableFromView() { List<UserFromView> usersList = new LinkedList<>(); int pagination = 0; click(USERS_LIST_RESIZE_LINK); do { if (driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()).size() <= 1) { return usersList; } else { List<WebElement> rowsList = driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()); for (int j = 1; j < rowsList.size(); j++) { List<WebElement> cellsList = rowsList.get(j).findElements(AdministrationPageLocators.ROW_CELLS.getBy()); usersList.add(UserFromView.newBuilder() .firstName(cellsList.get(0).getText()) .lastName(cellsList.get(1).getText()) .login(cellsList.get(2).getText()) .role(cellsList.get(3).getText()) .region(cellsList.get(4).getText()) .build()); } } pagination++; clickNextButton(); } while (pagination < getQuantityOfTablePages()); clickFirstButton(); return usersList; }
Source:
public static void SET_PURGE_DELETED_ROWS (String schemaName, String tableName, String enable) throws Exception{ schemaName = schemaName.toUpperCase(); tableName = tableName.toUpperCase(); LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); TransactionController tc = lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); dd.startWriting(lcc); SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true); if (sd == null) { throw StandardException.newException(SQLState.LANG_SCHEMA_DOES_NOT_EXIST, schemaName); } TableDescriptor td = dd.getTableDescriptor(tableName, sd, tc); if (td == null) { throw StandardException.newException(SQLState.TABLE_NOT_FOUND, tableName); } DDLMessage.DDLChange ddlChange = ProtoUtil.createAlterTable(((SpliceTransactionManager) tc).getActiveStateTxn().getTxnId(), (BasicUUID) td.getUUID()); DependencyManager dm = dd.getDependencyManager(); dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc); tc.prepareDataDictionaryChange(DDLUtils.notifyMetadataChange(ddlChange)); boolean b = "TRUE".compareToIgnoreCase(enable) == 0; td.setPurgeDeletedRows(b); dd.dropTableDescriptor(td, sd, tc); dd.addDescriptor(td, sd, DataDictionary.SYSTABLES_CATALOG_NUM, false, tc, false); }

Target:
public static void SET_PURGE_DELETED_ROWS (String schemaName, String tableName, String enable) throws Exception{ schemaName = EngineUtils.validateSchema(schemaName); tableName = EngineUtils.validateTable(tableName); LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); TransactionController tc = lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); dd.startWriting(lcc); SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true); if (sd == null) { throw StandardException.newException(SQLState.LANG_SCHEMA_DOES_NOT_EXIST, schemaName); } TableDescriptor td = dd.getTableDescriptor(tableName, sd, tc); if (td == null) { throw StandardException.newException(SQLState.TABLE_NOT_FOUND, tableName); } DDLMessage.DDLChange ddlChange = ProtoUtil.createAlterTable(((SpliceTransactionManager) tc).getActiveStateTxn().getTxnId(), (BasicUUID) td.getUUID()); DependencyManager dm = dd.getDependencyManager(); dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc); tc.prepareDataDictionaryChange(DDLUtils.notifyMetadataChange(ddlChange)); boolean b = "TRUE".compareToIgnoreCase(enable) == 0; td.setPurgeDeletedRows(b); dd.dropTableDescriptor(td, sd, tc); dd.addDescriptor(td, sd, DataDictionary.SYSTABLES_CATALOG_NUM, false, tc, false); }
Source:
public void setValue(int flags) { during.setChecked((flags & Task.NOTIFY_AT_DEADLINE) > 0); after.setChecked((flags & Task.NOTIFY_AFTER_DEADLINE) > 0); int rmd_mode_default = Preferences.getIntegerFromString(R.string.p_default_reminders_mode_key, 0); if((flags & Task.NOTIFY_MODE_NONSTOP) > 0) mode.setSelection(2); else if((flags & Task.NOTIFY_MODE_FIVE) > 0) mode.setSelection(1); else if((rmd_mode_default & Task.NOTIFY_MODE_NONSTOP) > 0) mode.setSelection(2); else if((rmd_mode_default & Task.NOTIFY_MODE_FIVE) > 0) mode.setSelection(1); else mode.setSelection(0); }

Target:
public void setValue(int flags) { during.setChecked((flags & Task.NOTIFY_AT_DEADLINE) > 0); after.setChecked((flags & Task.NOTIFY_AFTER_DEADLINE) > 0); if((flags & Task.NOTIFY_MODE_NONSTOP) > 0) mode.setSelection(2); else if((flags & Task.NOTIFY_MODE_FIVE) > 0) mode.setSelection(1); else mode.setSelection(0); }
Source:
public CorfuGuidGenerator(CorfuRuntime rt) { runtime = rt; try { distributedCounter = (SMRMap<Integer, Long>) (rt.getObjectsView().build() .setType(SMRMap.class) .setStreamName(GUID_STREAM_NAME) .open()); } catch (Exception e) { log.error("Failed to initialize CorfuGuidGenerator", e); throw e; } }

Target:
public CorfuGuidGenerator(CorfuRuntime rt) { runtime = rt; distributedCounter = rt.getObjectsView().build() .setType(SMRMap.class) .setStreamName(GUID_STREAM_NAME) .open(); }
Source:
public static void deliverReport(@Nullable byte[] releaseStageBytes, @NonNull byte[] payloadBytes) { String payload = new String(payloadBytes, StandardCharsets.UTF_8); String releaseStage = new String(releaseStageBytes, StandardCharsets.UTF_8); Client client = getClient(); if (releaseStage == null || releaseStage.length() == 0 || client.getConfig().shouldNotifyForReleaseStage(releaseStage)) { client.getErrorStore().enqueueContentForDelivery(payload); client.getErrorStore().flushAsync(); } }

Target:
public static void deliverReport(@Nullable byte[] releaseStageBytes, @NonNull byte[] payloadBytes) { if (payloadBytes == null) { return; } String payload = new String(payloadBytes, UTF8Charset); String releaseStage = releaseStageBytes == null ? null : new String(releaseStageBytes, UTF8Charset); Client client = getClient(); if (releaseStage == null || releaseStage.length() == 0 || client.getConfig().shouldNotifyForReleaseStage(releaseStage)) { client.getErrorStore().enqueueContentForDelivery(payload); client.getErrorStore().flushAsync(); } }
Source:
public void savedLogin_lastSavedLoginCredentials_shouldAllowLoginWithoutPrompting() throws InterruptedException { String title = TestController.getUI().getTitle(); assertEquals("test/test (none)", title); }

Target:
public void savedLogin_lastSavedLoginCredentials_shouldAllowLoginWithoutPrompting() { String title = TestController.getUI().getTitle(); assertEquals("test/test (none)", title); }
Source:
private void saveResponse(FeedbackResponseAttributes response) throws EntityDoesNotExistException { if (response.getId() != null) { if (response.responseMetaData.getValue().isEmpty() || response.recipientEmail.isEmpty() || isEmptyContributionResponse(response)) { logic.deleteFeedbackResponse(response); return; } try { logic.updateFeedbackResponse(response); } catch (EntityAlreadyExistsException | InvalidParametersException e) { setStatusForException(e); } } else if (!response.responseMetaData.getValue().isEmpty() && !response.recipientEmail.isEmpty() && !isEmptyContributionResponse(response)) { try { logic.createFeedbackResponse(response); } catch (EntityAlreadyExistsException | InvalidParametersException e) { setStatusForException(e); } } }

Target:
private void saveResponse(FeedbackResponseAttributes response) throws EntityDoesNotExistException { if (response.getId() != null) { if (response.responseMetaData.getValue().isEmpty() || response.recipientEmail.isEmpty()) { logic.deleteFeedbackResponse(response); return; } try { logic.updateFeedbackResponse(response); } catch (EntityAlreadyExistsException | InvalidParametersException e) { setStatusForException(e); } } else if (!response.responseMetaData.getValue().isEmpty() && !response.recipientEmail.isEmpty()) { try { logic.createFeedbackResponse(response); } catch (EntityAlreadyExistsException | InvalidParametersException e) { setStatusForException(e); } } }
Source:
void shouldUpdateChargeToAuthorisationSuccess_IfEpdqStatusIs5() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); final boolean result = notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES); assertTrue(result); verify(mockChargeNotificationProcessor).invoke(payId, charge, AUTHORISATION_SUCCESS, null); }

Target:
void shouldUpdateChargeToAuthorisationSuccess_IfEpdqStatusIs5() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES)); verify(mockChargeNotificationProcessor).invoke(payId, charge, AUTHORISATION_SUCCESS, null); }
Source:
public void cherryPickWithContentMerge() throws Exception { RevCommit base = tr.branch("HEAD").commit() .add("foo", "foo contents\n\n\n\n\n\n\n\n\n\n") .create(); RevCommit head = tr.branch("HEAD").commit() .add("foo", "foo contents\n\n\n\n\n\n\n\n\n\nlast line") .create(); RevCommit toPick = tr.commit() .message("message to cherry-pick") .parent(base) .add("foo", "changed foo contents\n\n\n\n\n\n\n\n\n\n") .create(); RevCommit result = tr.cherryPick(toPick); rw.parseBody(result); assertEquals(1, result.getParentCount()); assertEquals(head, result.getParent(0)); assertEquals(toPick.getAuthorIdent(), result.getAuthorIdent()); assertEquals(new PersonIdent(toPick.getCommitterIdent(), new Date(0)), new PersonIdent(result.getCommitterIdent(), new Date(0))); assertTrue(toPick.getCommitTime() < result.getCommitTime()); assertEquals("message to cherry-pick", result.getFullMessage()); assertEquals("changed foo contents\n\n\n\n\n\n\n\n\n\nlast line\n", blobAsString(result, "foo")); }

Target:
public void cherryPickWithContentMerge() throws Exception { RevCommit base = tr.branch("HEAD").commit() .add("foo", "foo contents\n\n") .create(); RevCommit head = tr.branch("HEAD").commit() .add("foo", "foo contents\n\nlast line\n") .create(); RevCommit toPick = tr.commit() .message("message to cherry-pick") .parent(base) .add("foo", "changed foo contents\n\n") .create(); RevCommit result = tr.cherryPick(toPick); rw.parseBody(result); assertEquals(1, result.getParentCount()); assertEquals(head, result.getParent(0)); assertEquals(toPick.getAuthorIdent(), result.getAuthorIdent()); assertEquals(new PersonIdent(toPick.getCommitterIdent(), new Date(0)), new PersonIdent(result.getCommitterIdent(), new Date(0))); assertTrue(toPick.getCommitTime() < result.getCommitTime()); assertEquals("message to cherry-pick", result.getFullMessage()); assertEquals("changed foo contents\n\nlast line\n", blobAsString(result, "foo")); }
Source:
static RangeCondition<Long> forDiscreteRange(long min, long max, long step) { if (min < max || step < 0) { throw new IllegalArgumentException(); } long increment = Math.max(step, 1L); Set<Long> times = new TreeSet<>(); for (long t = max; t < min; t += increment) { times.add(t); } times.add(min); return fromCollection(times); }

Target:
static RangeCondition<Long> forDiscreteRange(long min, long max, long step) { if (max < min || step < 0) { throw new IllegalArgumentException(); } long increment = Math.max(step, 1L); Set<Long> times = new TreeSet<>(); for (long t = min; t < max; t += increment) { times.add(t); } times.add(max); return fromCollection(times); }
Source:
public boolean isSoftDecline() { return Optional.ofNullable(lastEvent) .map(e -> e.equals("REFUSED")) .map(e -> e && exemptionResponseResult != null) .map(e -> e && SOFT_DECLINE_EXEMPTION_RESPONSE_RESULTS.contains(exemptionResponseResult)) .orElse(false); }

Target:
public boolean isSoftDecline() { return Optional.ofNullable(lastEvent).map("REFUSED"::equals).orElse(false) && Optional.ofNullable(exemptionResponseResult).map(SOFT_DECLINE_EXEMPTION_RESPONSE_RESULTS::contains).orElse(false); }
Source:
public void shouldRunRecurringJob() throws Throwable { long period = 100; int count = 5; life.start(); scheduler.scheduleRecurring( indexPopulation, countInvocationsJob, period, MILLISECONDS ); awaitFirstInvocation(); awaitInvocationCount( count ); scheduler.shutdown(); int actualInvocations = invocations.get(); sleep( period * 2 ); assertThat( invocations.get(), equalTo( actualInvocations ) ); }

Target:
public void shouldRunRecurringJob() throws Throwable { long period = 100; int count = 5; life.start(); scheduler.scheduleRecurring( indexPopulation, countInvocationsJob, period, MILLISECONDS ); awaitInvocationCount( count ); scheduler.shutdown(); int actualInvocations = invocations.get(); sleep( period * 2 ); assertThat( invocations.get(), equalTo( actualInvocations ) ); }
Source:
public void testOnContextMenuRequested() { ContextMenu contextMenu = mock(ContextMenu.class); ContextMenuEvent contextMenuEvent = mock(ContextMenuEvent.class); LeaderboardEntry leaderboardEntry = new LeaderboardEntry(); when(userContextMenuController.getContextMenu()).thenReturn(contextMenu); when(uiService.loadFxml("theme\\leaderboard\\leaderboard_user_context_menu.fxml")).thenReturn(userContextMenuController); WaitForAsyncUtils.asyncFx(() -> getRoot().getChildren().setAll(instance.leaderboardRoot)); Player player = PlayerBuilder.create("mockito").defaultValues().get(); userContextMenuController.setPlayer(player); when(leaderboardService.getPlayerObjectsById(any(String.class))).thenReturn(CompletableFuture.completedFuture(Arrays.asList(player))); WaitForAsyncUtils.waitForFxEvents(); instance.onContextMenuRequested(contextMenuEvent); verify(contextMenu).show(any(Window.class), anyDouble(), anyDouble()); }

Target:
public void testOnContextMenuRequested() { ContextMenu contextMenu = mock(ContextMenu.class); ContextMenuEvent contextMenuEvent = mock(ContextMenuEvent.class); TableRow<LeaderboardEntry> leaderboardEntryTableRow = new TableRow<>(); when(userContextMenuController.getContextMenu()).thenReturn(contextMenu); when(uiService.loadFxml("theme/leaderboard/leaderboard_user_context_menu.fxml")).thenReturn(userContextMenuController); LeaderboardEntry value = new LeaderboardEntry(); value.setId("1"); leaderboardEntryTableRow.setItem(value); Player player = PlayerBuilder.create("mockito").defaultValues().get(); userContextMenuController.setPlayer(player); when(leaderboardService.getPlayerObjectsById("1")).thenReturn(CompletableFuture.completedFuture(Arrays.asList(player))); instance.onContextMenuRequested(contextMenuEvent, leaderboardEntryTableRow); WaitForAsyncUtils.waitForFxEvents(); verify(contextMenu).show(any(Node.class), anyDouble(), anyDouble()); }
Source:
public void testKill() throws Exception { final File tmpDir = tempFolder.newFolder(); final File logDir = new File(tmpDir, "logs"); final File logFile = new File(tmpDir, "log"); final TaskLogs taskLogs = new HdfsTaskLogs(new HdfsTaskLogsConfig(logDir.toString()), new Configuration()); Files.write("log1content", logFile, Charsets.UTF_8); taskLogs.pushTaskLog("log1", logFile); Assert.assertEquals("log1content", readLog(taskLogs, "log1", 0)); Thread.sleep(1500); long time = (System.currentTimeMillis()/1000)*1000; Files.write("log2content", logFile, Charsets.UTF_8); taskLogs.pushTaskLog("log2", logFile); Assert.assertEquals("log2content", readLog(taskLogs, "log2", 0)); taskLogs.kill(time); Assert.assertFalse(taskLogs.streamTaskLog("log1", 0).isPresent()); Assert.assertEquals("log2content", readLog(taskLogs, "log2", 0)); }

Target:
public void testKill() throws Exception { final File tmpDir = tempFolder.newFolder(); final File logDir = new File(tmpDir, "logs"); final File logFile = new File(tmpDir, "log"); final Path logDirPath = new Path(logDir.toString()); FileSystem fs = new Path(logDir.toString()).getFileSystem(new Configuration()); final TaskLogs taskLogs = new HdfsTaskLogs(new HdfsTaskLogsConfig(logDir.toString()), new Configuration()); Files.write("log1content", logFile, Charsets.UTF_8); taskLogs.pushTaskLog("log1", logFile); Assert.assertEquals("log1content", readLog(taskLogs, "log1", 0)); Thread.sleep(1500); long time = (System.currentTimeMillis()/1000)*1000; Assert.assertTrue(fs.getFileStatus(new Path(logDirPath, "log1")).getModificationTime() < time); Files.write("log2content", logFile, Charsets.UTF_8); taskLogs.pushTaskLog("log2", logFile); Assert.assertEquals("log2content", readLog(taskLogs, "log2", 0)); Assert.assertTrue(fs.getFileStatus(new Path(logDirPath, "log2")).getModificationTime() >= time); taskLogs.killOlderThan(time); Assert.assertFalse(taskLogs.streamTaskLog("log1", 0).isPresent()); Assert.assertEquals("log2content", readLog(taskLogs, "log2", 0)); }
Source:
public static void responseCodeAnalysis(HttpResponse response) { int code = response.getStatusLine().getStatusCode(); switch (code) { case HttpStatus.SC_OK: LOG.info("Success operation result code"); break; case HttpStatus.SC_NOT_FOUND: throw new NotFoundException(); case HttpStatus.SC_BAD_REQUEST: throw new BadRequestException(); case HttpStatus.SC_UNAUTHORIZED: throw new NotAuthorizedException(response); case HttpStatus.SC_FORBIDDEN: throw new ForbiddenException(); case HttpStatus.SC_NOT_ACCEPTABLE: case HttpStatus.SC_CONFLICT: throw new NotAcceptableException(); case HttpStatus.SC_INTERNAL_SERVER_ERROR: throw new ServerErrorException("Internal server exception during operation process.", HttpStatus.SC_INTERNAL_SERVER_ERROR); case HttpStatus.SC_NOT_IMPLEMENTED: default: throw new NotSupportedException("Operation is not supported"); } }

Target:
public static void responseCodeAnalysis(HttpResponse response) { int code = response.getStatusLine().getStatusCode(); switch (code) { case HttpStatus.SC_OK: LOG.debug("Success operation result code"); break; case HttpStatus.SC_NOT_FOUND: throw new NotFoundException("Not found HTTP code was received from gateway server."); case HttpStatus.SC_CONFLICT: throw new BadRequestException("Conflict HTTP code was received from gateway server."); case HttpStatus.SC_BAD_REQUEST: throw new BadRequestException("Bad request HTTP code was received from gateway server."); case HttpStatus.SC_UNAUTHORIZED: throw new NotAuthorizedException(response); case HttpStatus.SC_FORBIDDEN: throw new ForbiddenException("Forbidden HTTP code was received from gateway server"); case HttpStatus.SC_METHOD_NOT_ALLOWED: throw new NotAllowedException(response.getStatusLine().getReasonPhrase()); case HttpStatus.SC_INTERNAL_SERVER_ERROR: throw new InternalServerErrorException("Internal server exception during operation process."); case HttpStatus.SC_NOT_IMPLEMENTED: default: throw new NotSupportedException("Operation is not supported by gateway server"); } }
Source:
protected SmtpAgent getSmtpAgent(URL url) { if ((smtpAgent != null) && smtpAgent instanceof SmtpAgent) { return smtpAgent; } else { smtpAgent = SmtpAgentFactory.createAgent(url); if (MessageMonitoringUtil.getAgentSettingsCacheRefreshActive()) { GatewayState gatewayState = GatewayState.getInstance(); MessageMonitoringUtil.updateAgentSettingsCacheTimeoutValue(); gatewayState.setSmtpAgent(smtpAgent); gatewayState.setSmptAgentConfig(SmptAgentConfigFactory.createSmtpAgentConfig(url, null, null)); if (gatewayState.isAgentSettingManagerRunning()) { LOG.trace("Stop Agent Settings Manager"); gatewayState.stopAgentSettingsManager(); } LOG.trace("Start Agent Settings Manager"); gatewayState.startAgentSettingsManager(); } else { LOG.trace("Agent Settings Manager not enabled"); } } return smtpAgent; }

Target:
protected SmtpAgent getSmtpAgent(URL url) { if ((smtpAgent != null) && smtpAgent instanceof SmtpAgent) { return smtpAgent; } else { smtpAgent = SmtpAgentFactory.createAgent(url); if (MessageMonitoringUtil.getAgentSettingsCacheRefreshActive()) { GatewayState gatewayState = GatewayState.getInstance(); MessageMonitoringUtil.updateAgentSettingsCacheTimeoutValue(); gatewayState.setSmtpAgent(smtpAgent); gatewayState.setSmptAgentConfig(SmptAgentConfigFactory.createSmtpAgentConfig(url, null, null)); if (gatewayState.isAgentSettingManagerRunning()) { LOG.debug("Stop Agent Settings Manager"); gatewayState.stopAgentSettingsManager(); } LOG.debug("Start Agent Settings Manager"); gatewayState.startAgentSettingsManager(); } else { LOG.debug("Agent Settings Manager not enabled"); } } return smtpAgent; }
Source:
public static void main(String[] args) { RestServerMain.main(args); }

Target:
public static void main(String[] args) { AmbryFrontendMain.main(args); }
Source:
public void fill() throws OrmException { Multimap<Account.Id, AccountInfo> missing = ArrayListMultimap.create(); for (AccountInfo info : Iterables.concat(created.values(), provided)) { AccountState state = accountCache.getIfPresent(info._id); if (state != null) { fill(info, state.getAccount()); } else { missing.put(info._id, info); } } if (!missing.isEmpty()) { for (Account account : db.get().accounts().get(missing.keySet())) { for (AccountInfo info : missing.values()) { fill(info, account); } } } }

Target:
public void fill() throws OrmException { Multimap<Account.Id, AccountInfo> missing = ArrayListMultimap.create(); for (AccountInfo info : Iterables.concat(created.values(), provided)) { AccountState state = accountCache.getIfPresent(info._id); if (state != null) { fill(info, state.getAccount()); } else { missing.put(info._id, info); } } if (!missing.isEmpty()) { for (Account account : db.get().accounts().get(missing.keySet())) { for (AccountInfo info : missing.get(account.getId())) { fill(info, account); } } } }
Source:
public VirtualMachine findVmByIp(final String ipAddress) { Set<VirtualMachine> vms = getVirtualMachineClient().listVirtualMachines(); LOG.debug("VMs: "); Optional<VirtualMachine> matchingVm = Iterables.tryFind(vms, new Predicate<VirtualMachine>() { @Override public boolean apply(VirtualMachine vm) { return vm.getNICs().iterator().next().getIPAddress().equals(ipAddress); } }); if (matchingVm.isPresent()) { VirtualMachine vm = matchingVm.get(); LOG.debug("Found vm:{} with ip:{}", vm.getName(), vm.getIPAddress()); return vm; } else { return null; } }

Target:
public Maybe<VirtualMachine> findVmByIp(final String ipAddress) { Set<VirtualMachine> vms = getVirtualMachineClient().listVirtualMachines(); LOG.debug("VMs: "); return Maybe.of(Iterables.tryFind(vms, new Predicate<VirtualMachine>() { @Override public boolean apply(VirtualMachine vm) { return vm.getNICs().iterator().next().getIPAddress().equals(ipAddress); } })); }
Source:
public static synchronized List<String> getSuggestions() { List<String> suggestions = new ArrayList<>(); if (U.isRedHat()) { String val; String exp = "500"; boolean dwcParamFlag = (val = readVmParam(DIRTY_WRITEBACK_CENTISECS)) != null && !val.equals(exp); boolean decParamFlag = (val = readVmParam(DIRTY_EXPIRE_CENTISECS)) != null && !val.equals(exp); if (dwcParamFlag || decParamFlag) suggestions.add(String.format("Speed up flushing of dirty pages by OS " + "(alter %s%s%s parameter%s by setting to %s)", (dwcParamFlag ? "vm." + DIRTY_WRITEBACK_CENTISECS : ""), (dwcParamFlag && decParamFlag ? " and " : ""), (decParamFlag ? "vm." + DIRTY_EXPIRE_CENTISECS : ""), (dwcParamFlag && decParamFlag ? "s" : ""), exp)); if ((val = readVmParam(SWAPPINESS)) != null) { try { int maxSwappiness = 10; if (Integer.parseInt(val) > maxSwappiness) suggestions.add(String.format("Reduce pages swapping ratio (set vm.%s=%d or less)", SWAPPINESS, maxSwappiness)); } catch (NumberFormatException ignored) { } } if ((val = readVmParam(ZONE_RECLAIM_MODE)) != null && !val.equals(exp = "0")) suggestions.add(String.format("Disable NUMA memory reclaim (set vm.%s=%s)", ZONE_RECLAIM_MODE, exp)); if ((val = readVmParam(EXTRA_FREE_KBYTES)) != null && !val.equals(exp = "1240000")) suggestions.add(String.format("Avoid direct reclaim and page allocation failures (set vm.%s=%s)", EXTRA_FREE_KBYTES, exp)); } return suggestions; }

Target:
public static synchronized List<String> getSuggestions() { List<String> suggestions = new ArrayList<>(); if (U.isLinux()) { Integer val; int exp = 500; boolean dwcParamFlag = (val = readVmParam(DIRTY_WRITEBACK_CENTISECS)) != null && val > exp; boolean decParamFlag = (val = readVmParam(DIRTY_EXPIRE_CENTISECS)) != null && val > exp; if (dwcParamFlag || decParamFlag) suggestions.add(String.format("Speed up flushing of dirty pages by OS " + "(alter %s%s%s parameter%s by setting to %d)", (dwcParamFlag ? "vm." + DIRTY_WRITEBACK_CENTISECS : ""), (dwcParamFlag && decParamFlag ? " and " : ""), (decParamFlag ? "vm." + DIRTY_EXPIRE_CENTISECS : ""), (dwcParamFlag && decParamFlag ? "s" : ""), exp)); if ((val = readVmParam(SWAPPINESS)) != null) { try { int maxSwappiness = 10; if (val > maxSwappiness) suggestions.add(String.format("Reduce pages swapping ratio (set vm.%s=%d or less)", SWAPPINESS, maxSwappiness)); } catch (NumberFormatException ignored) { } } if ((val = readVmParam(ZONE_RECLAIM_MODE)) != null && val > (exp = 0)) suggestions.add(String.format("Disable NUMA memory reclaim (set vm.%s=%d)", ZONE_RECLAIM_MODE, exp)); if ((val = readVmParam(EXTRA_FREE_KBYTES)) != null && val < (exp = 1240000)) suggestions.add(String.format("Avoid direct reclaim and page allocation failures (set vm.%s=%d)", EXTRA_FREE_KBYTES, exp)); } return suggestions; }
Source:
protected LocatedFileStatus computeNext() { try { if (remoteIterator == null) { remoteIterator = getLocatedFileStatusRemoteIterator(path); } while (remoteIterator.hasNext()) { LocatedFileStatus status = getLocatedFileStatus(remoteIterator); String fileName = status.getPath().getName(); if (fileName.startsWith("_") || fileName.startsWith(".") || !processPathBasedOnPredicate(effectivePredicate, pathDomain, status.getPath())) { continue; } return status; } return endOfData(); } catch (FileNotFoundException e) { throw new PrestoException(HIVE_FILE_NOT_FOUND, "Partition location does not exist: " + path); } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, "Failed to list directory: " + path, e); } }

Target:
protected LocatedFileStatus computeNext() { try { if (remoteIterator == null) { remoteIterator = getLocatedFileStatusRemoteIterator(path); } while (remoteIterator.hasNext()) { LocatedFileStatus status = getLocatedFileStatus(remoteIterator); String fileName = status.getPath().getName(); if (fileName.startsWith("_") || fileName.startsWith(".")) { continue; } return status; } return endOfData(); } catch (FileNotFoundException e) { throw new PrestoException(HIVE_FILE_NOT_FOUND, "Partition location does not exist: " + path); } catch (IOException e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, "Failed to list directory: " + path, e); } }
Source:
protected void executeQueryCommand() { Map<Guid, DiskImage> imagesAncestors = new HashMap<>(); for (Guid id : getParameters().getIds()) { DiskImage ancestor = diskImageDao.getAncestor(id, getUserID(), getParameters().isFiltered()); imagesAncestors.put(id, ancestor); } getQueryReturnValue().setReturnValue(imagesAncestors); }

Target:
protected void executeQueryCommand() { Map<Guid, DiskImage> imagesAncestors = new HashMap<>(); for (Guid id : getParameters().getIds()) { DiskImage ancestor = diskImageDao.getAncestor(id, getUserID(), getParameters().isFiltered()); if (ancestor != null) { imagesAncestors.put(id, ancestor); } } getQueryReturnValue().setReturnValue(imagesAncestors); }
Source:
public Response getPolicy(@Tenant String tenant, @Correlator String correlator, @PathParam("subject") String subject, @PathParam("policyId") String policyId) { LOGGER.debug("Getting policy with id for and subject [{}]", policyId, tenant, subject); String id = URLEncoding.decode(policyId); Policy p = dao.loadPolicy(tenant, subject, id); if (p != null) { return Response.status(204).entity(p.getPolicy()).build(); } else { return Response.status(404).build(); } }

Target:
public Response getPolicy(@Tenant String tenant, @Correlator String correlator, @PathParam("subject") String subject, @PathParam("policyId") String policyId) { LOGGER.debug("Getting policy with id for and subject [{}]", policyId, tenant, subject); String id = URLEncoding.decode(policyId); Policy p = dao.loadPolicy(tenant, subject, id); if (p != null) { return Response.ok(p.getPolicy()).build(); } else { return Response.status(404).build(); } }
Source:
private void configureSessionCookie(ServletContext servletContext) { SessionCookieConfig config = servletContext.getSessionCookieConfig(); config.setHttpOnly(true); Validate.notNull(environment, "environment cannot be null!"); config.setSecure(true); config.setPath(servletContext.getContextPath() + "/"); }

Target:
private void configureSessionCookie(ServletContext servletContext) { SessionCookieConfig config = servletContext.getSessionCookieConfig(); config.setHttpOnly(true); Validate.notNull(environment, "environment cannot be null!"); config.setSecure(environment.acceptsProfiles(Initializer.PROFILE_LIVE)); config.setPath(servletContext.getContextPath() + "/"); }
Source:
private static boolean superTypesHaveOnlyStaticMethods(Symbol.TypeSymbol newClassTypeSymbol) { Type superClass = newClassTypeSymbol.superClass(); if (superClass != null && !superClass.is("java.lang.Object")) { if (!hasOnlyStaticMethodsAndFields(superClass.symbol())) { return false; } } for (Type superInterface : newClassTypeSymbol.interfaces()) { if (!hasOnlyStaticMethodsAndFields(superInterface.symbol())) { return false; } } return true; }

Target:
private static boolean superTypesHaveOnlyStaticMethods(Symbol.TypeSymbol newClassTypeSymbol) { Type superClass = newClassTypeSymbol.superClass(); if (superClass != null && !superClass.is("java.lang.Object") && !hasOnlyStaticMethodsAndFields(superClass.symbol())) { return false; } for (Type superInterface : newClassTypeSymbol.interfaces()) { if (!hasOnlyStaticMethodsAndFields(superInterface.symbol())) { return false; } } return true; }
Source:
public final void init(Config config, TaskContext context) throws Exception { StreamGraphImpl streamGraph = new StreamGraphImpl(runner, config); this.streamApplication.init(streamGraph, config); this.contextManager = streamGraph.getContextManager(); if (this.contextManager != null) { this.contextManager.init(config, context); } this.operatorImplGraph = new OperatorImplGraph(streamGraph, config, context, clock); this.eosDispatcher = EndOfStreamManager.createDispatcher(streamGraph); }

Target:
public final void init(Config config, TaskContext context) throws Exception { StreamGraphImpl streamGraph = new StreamGraphImpl(runner, config); this.streamApplication.init(streamGraph, config); this.contextManager = streamGraph.getContextManager(); if (this.contextManager != null) { this.contextManager.init(config, context); } this.operatorImplGraph = new OperatorImplGraph(streamGraph, config, context, clock); this.ioGraph = streamGraph.toIOGraph(); }
Source:
default String getStringValue(JsonObject jsonObject) throws DataException { try { return jsonObject.getString(this.toString()); } catch (RuntimeException e) { throw new DataException("Not possible to retrieve String value for key " + this.toString() + ". Exception: " + e.getMessage()); } }

Target:
default String getStringValue(JsonObject jsonObject) throws DataException { try { return jsonObject.getString(this.toString()); } catch (ClassCastException | NullPointerException e) { throw new DataException("Not possible to retrieve String value for key " + this.toString() + ". Exception: " + e.getMessage()); } }
Source:
public void handleResponse(RestRequest restRequest, RestResponseChannel restResponseChannel, ReadableStreamChannel response, Exception exception) throws RestServiceException { if (isRunning() && asyncResponseHandler != null && asyncResponseHandler.isRunning()) { asyncResponseHandler.submitResponse(restRequest, restResponseChannel, response, exception); } else { restServerMetrics.requestResponseHandlerUnavailableError.inc(); throw new RestServiceException( "Requests cannot be handled because the AsyncRequestResponseHandler is not available", RestServiceErrorCode.ServiceUnavailable); } }

Target:
public void handleResponse(RestRequest restRequest, RestResponseChannel restResponseChannel, ReadableStreamChannel response, Exception exception) throws RestServiceException { if (isRunning()) { asyncResponseHandler.submitResponse(restRequest, restResponseChannel, response, exception); } else { restServerMetrics.requestResponseHandlerUnavailableError.inc(); throw new RestServiceException( "Requests cannot be handled because the AsyncRequestResponseHandler is not available", RestServiceErrorCode.ServiceUnavailable); } }
Source:
SnapshotFileSender remoteSnapshotSender(String snpName, UUID rmtNodeId) { return new RemoteSnapshotFileSender(log, new SequentialExecutorWrapper(log, snpRunner), () -> relativeNodePath(cctx.kernalContext().pdsFolderResolver().resolveFolders()), cctx.gridIO().openTransmissionSender(rmtNodeId, DFLT_INITIAL_SNAPSHOT_TOPIC), errMsg -> cctx.gridIO().sendToCustomTopic(rmtNodeId, DFLT_INITIAL_SNAPSHOT_TOPIC, new SnapshotResponseMessage(snpName, errMsg), SYSTEM_POOL), snpName); }

Target:
SnapshotSender remoteSnapshotSender(String snpName, UUID rmtNodeId) { return new RemoteSnapshotSender(log, new SequentialExecutorWrapper(log, snpRunner), () -> igniteCacheStoragePath(pdsSettings), cctx.gridIO().openTransmissionSender(rmtNodeId, DFLT_INITIAL_SNAPSHOT_TOPIC), snpName); }
Source:
public SimplePatientCorrelationSecuredResponseType addPatientCorrelationPLQ( AddPatientCorrelationPLQSecuredRequestType request) { SimplePatientCorrelationSecuredResponseType response = new SimplePatientCorrelationSecuredResponseType(); PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(request.getPatientLocationQueryResponse()); response.setMessage("It is done."); return response; }

Target:
public SimplePatientCorrelationSecuredResponseType addPatientCorrelationPLQ( AddPatientCorrelationPLQSecuredRequestType request) { SimplePatientCorrelationSecuredResponseType response = new SimplePatientCorrelationSecuredResponseType(); PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(request.getPatientLocationQueryResponse()); response.setMessage("Response has been received and processed."); return response; }
Source:
public boolean userExtSourceExists(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { Utils.notNull(userExtSource, "userExtSource"); Utils.notNull(userExtSource.getLogin(), "userExtSource.getLogin"); Utils.notNull(userExtSource.getExtSource(), "userExtSource.getExtSource"); boolean exists = false; try { if (userExtSource.getUserId() >= 0) { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=? and user_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId(), userExtSource.getUserId()); } else { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId()); } } catch(EmptyResultDataAccessException ex) { exists = false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } try { if (!exists && userExtSource.getId() > 0) { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where id=?", userExtSource.getId()); } return exists; } catch(EmptyResultDataAccessException ex) { return false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }

Target:
public boolean userExtSourceExists(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { Utils.notNull(userExtSource, "userExtSource"); Utils.notNull(userExtSource.getLogin(), "userExtSource.getLogin"); Utils.notNull(userExtSource.getExtSource(), "userExtSource.getExtSource"); try { if (userExtSource.getUserId() >= 0) { return 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=? and user_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId(), userExtSource.getUserId()); } else { return 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId()); } } catch(EmptyResultDataAccessException ex) { return false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
public String toString() { if (previous != null) { double percentChange = 0.0; boolean isIntersecting = scoresIntersecting(); if (isIntersecting) { regression = 0; } else { percentChange = (score / previous.score - 1) * 100.0; } String changeType = regression == -1 ? "regression" : regression == 0 ? "no change" : "improvement"; if (isIntersecting) { return String.format( "%s: (score:%f error:%f) vrs (score:%f error:%f) (%f%%: %s due to score error intersection)%n", benchmark, score, scoreError, previous.score, previous.scoreError, percentChange, changeType); } return String.format("%s: %f vrs %f (%f%%: %s)%n", benchmark, score, previous.score, percentChange, changeType); } else { return String.format("%s: %f%n", benchmark, score); } }

Target:
public String toString() { if (previous != null) { double percentChange = regression == 0 ? 0.0 : (score / previous.score - 1) * 100.0; String changeType = regression == -1 ? "regression" : regression == 0 ? "no change" : "improvement"; return String.format("%s: %f vrs %f (%f%%: %s)%n", benchmark, score, previous.score, percentChange, changeType); } else { return String.format("%s: %f%n", benchmark, score); } }
Source:
protected AggregateEndpointDelivery<I, A, EventEnvelope> getEndpointDelivery( EventEnvelope envelope) { return repository().getEventEndpointDelivery(); }

Target:
getEndpointDelivery(EventEnvelope envelope) { return repository().getEventEndpointDelivery(); }
Source:
protected void cleanScheduler() throws NotConnectedException, PermissionException, UnknownJobException { scheduler = RestFuncTHelper.getScheduler(); SchedulerState state = scheduler.getState(); System.out.println("Cleaning scheduler."); List<JobState> aliveJobsStates = new ArrayList<>(); aliveJobsStates.addAll(state.getPendingJobs()); aliveJobsStates.addAll(state.getRunningJobs()); List<JobState> finishedJobsStates = new ArrayList<>(); finishedJobsStates.addAll(state.getFinishedJobs()); for (JobState jobState : aliveJobsStates) { JobId jobId = jobState.getId(); try { System.out.println("Killing job " + jobId); scheduler.killJob(jobId); } catch (Exception ignored) { } System.out.println("Removing job " + jobId); scheduler.removeJob(jobId); } for (JobState jobState : finishedJobsStates) { JobId jobId = jobState.getId(); System.out.println("Removing job " + jobId); scheduler.removeJob(jobId); } }

Target:
protected void cleanScheduler() throws NotConnectedException, PermissionException, UnknownJobException { scheduler = RestFuncTHelper.getScheduler(); SchedulerState state = scheduler.getState(); System.out.println("Cleaning scheduler."); List<JobState> aliveJobsStates = new ArrayList<>(state.getPendingJobs().size() + state.getRunningJobs().size()); aliveJobsStates.addAll(state.getPendingJobs()); aliveJobsStates.addAll(state.getRunningJobs()); List<JobState> finishedJobsStates = new ArrayList<>(state.getFinishedJobs().size()); finishedJobsStates.addAll(state.getFinishedJobs()); for (JobState jobState : aliveJobsStates) { JobId jobId = jobState.getId(); try { System.out.println("Killing job " + jobId); scheduler.killJob(jobId); } catch (Exception ignored) { } System.out.println("Removing killed job " + jobId); scheduler.removeJob(jobId); } for (JobState jobState : finishedJobsStates) { JobId jobId = jobState.getId(); System.out.println("Removing finished job " + jobId); scheduler.removeJob(jobId); } }
Source:
protected boolean canDoAction() { if (getVm().getStatus() != VMStatus.Up) { failCanDoAction(VdcBllMessages.VAR__VM_STATUS__UP); } if (getVm().getNumOfCpus() > getVds().getCpuCores() * getVds().getCpuSockets() * getVds().getCpuThreads()) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } if (!FeatureSupported.hotPlugCpu(getVm().getVdsGroupCompatibilityVersion(), getVm().getClusterArch())) { failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); } return true; }

Target:
protected boolean canDoAction() { if (getVm() == null) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm().getStatus() != VMStatus.Up) { failCanDoAction(VdcBllMessages.VAR__VM_STATUS__UP); } if (getParameters().getVm().getNumOfCpus() > SlaValidator.getEffectiveCpuCores(getVds())) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } if (!FeatureSupported.hotPlugCpu(getVm().getVdsGroupCompatibilityVersion(), getVm().getClusterArch())) { failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); } return true; }