auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Callable<Integer> getSleepCallable(int durationMillis) { return () -> { Thread.sleep(durationMillis); return durationMillis; }; }

Target:
private static Callable<Integer> getSleepCallable(int durationMillis) { return () -> { Thread.sleep(durationMillis); return durationMillis; }; }
Source:
public void testWriteTimeout() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", port); factory.setSoTimeout(1000); factory.start(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override @SuppressWarnings("unused") public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); Socket s = server.accept(); done.await(10, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); try { TcpConnection connection = factory.getConnection(); connection.send(MessageBuilder.withPayload(new byte[1000000]).build()); } catch (Exception e) { assertTrue("Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + ":" + e.getMessage(), e instanceof SocketTimeoutException); } done.countDown(); }

Target:
public void testWriteTimeout() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", port); factory.setSoTimeout(1000); factory.start(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override @SuppressWarnings("unused") public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); serverSocket.set(server); latch.countDown(); Socket s = server.accept(); done.await(10, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); try { TcpConnection connection = factory.getConnection(); connection.send(MessageBuilder.withPayload(new byte[1000000]).build()); } catch (Exception e) { assertTrue("Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + ":" + e.getMessage(), e instanceof SocketTimeoutException); } done.countDown(); serverSocket.get().close(); }
Source:
private static Map<String, String> mapParams(Map<String, String>fieldsMap, Map<String, String> params) { Map<String, String> mapped = new HashMap<>(); for (String k: params.keySet()) { String fk = fieldsMap.get(k); mapped.put(fk, params.get(k)); } return mapped; }

Target:
private static Map<String, String> mapParams(Map<String, String>fieldsMap, Map<String, String> params) { Map<String, String> mapped = new HashMap<>(); for (String k: params.keySet()) { String fk = fieldsMap.get(k); if (fk == null) { throw new JiraClientException(String.format("Could not map field name '%s'", k)); } mapped.put(fk, params.get(k)); } return mapped; }
Source:
public void project(ICause cause) throws ContradictionException { switch (op) { case ADD: e1.intersect(RealUtils.sub(this, e2), cause); e2.intersect(RealUtils.sub(this, e1), cause); break; case SUB: e1.intersect(RealUtils.add(this, e2), cause); e2.intersect(RealUtils.sub(e1, this), cause); break; case MUL: RealInterval res = RealUtils.odiv_wrt(this, e2, e1); if (res.getLB() > res.getUB()) { throw model.getSolver().getContradictionException().set(cause, null, ""); } e1.intersect(res, cause); res = RealUtils.odiv_wrt(this, e1, e2); if (res.getLB() > res.getUB()) { throw model.getSolver().getContradictionException().set(cause, null, ""); } e2.intersect(res, cause); break; case DIV: e1.intersect(RealUtils.mul(this, e2), cause); e2.intersect(RealUtils.mul(this, e1), cause); break; case POW: case MIN: case MAX: case ATAN2: default: throw new UnsupportedOperationException("Equation does not support " + op.name()); } }

Target:
public void project(ICause cause) throws ContradictionException { switch (op) { case ADD: e1.intersect(RealUtils.sub(this, e2), cause); e2.intersect(RealUtils.sub(this, e1), cause); break; case SUB: e1.intersect(RealUtils.add(this, e2), cause); e2.intersect(RealUtils.sub(e1, this), cause); break; case MUL: e1.intersect(RealUtils.odiv_wrt(this, e2, e1), cause); e2.intersect(RealUtils.odiv_wrt(this, e1, e2), cause); break; case DIV: e1.intersect(RealUtils.mul(this, e2), cause); e2.intersect(RealUtils.odiv_wrt(e1, this, e2), cause); break; case MIN: e1.intersect(this.getLB(), RealUtils.nextFloat(e1.getUB()), cause); e2.intersect(this.getLB(), RealUtils.nextFloat(e2.getUB()), cause); if (e2.getLB() > this.getUB()) { e1.intersect(RealUtils.prevFloat(e1.getLB()), this.getUB(), cause); } if (e1.getLB() > this.getUB()) { e2.intersect(RealUtils.prevFloat(e2.getLB()), this.getUB(), cause); } break; case MAX: e1.intersect(RealUtils.prevFloat(e1.getLB()), this.getUB(), cause); e2.intersect(RealUtils.prevFloat(e2.getLB()), this.getUB(), cause); if (e2.getUB() < this.getLB()) { e1.intersect(this.getLB(), RealUtils.nextFloat(e1.getUB()), cause); } if (e1.getUB() < this.getLB()) { e2.intersect(this.getLB(), RealUtils.nextFloat(e2.getUB()), cause); } break; case POW: case ATAN2: default: throw new UnsupportedOperationException("Equation does not support " + op.name()+". Consider using Ibex instead."); } }
Source:
void shouldUpdateChargeToCaptured_IfEpdqStatusIs9() { final String payload = notificationPayloadForTransaction(payId, EPDQ_PAYMENT_REQUESTED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); final boolean result = notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES); assertTrue(result); verify(mockChargeNotificationProcessor).invoke(payId, charge, CAPTURED, null); }

Target:
void shouldUpdateChargeToCaptured_IfEpdqStatusIs9() { final String payload = notificationPayloadForTransaction(payId, EPDQ_PAYMENT_REQUESTED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES)); verify(mockChargeNotificationProcessor).invoke(payId, charge, CAPTURED, null); }
Source:
public void suggestReviewNow() { long delay = TimeUnit.SECONDS.toMillis(1) - (System.currentTimeMillis() - lastSuggestedReview); if (delay < 0) { lastSuggestedReview = System.currentTimeMillis(); Computer.threadPoolForRemoting.submit(() -> { LOGGER.fine(() -> "running suggested review for " + label); update(); }); } else if (!queuedReview) { queuedReview = true; LOGGER.fine(() -> "running suggested review in " + delay + " ms for " + label); Timer.get().schedule(() -> { lastSuggestedReview = System.currentTimeMillis(); LOGGER.fine(() -> "running suggested review for " + label + " after " + delay + " ms"); update(); }, delay, TimeUnit.MILLISECONDS); } else { LOGGER.fine(() -> "ignoring suggested review for " + label); } }

Target:
public void suggestReviewNow() { if (!queuedReview) { long delay = TimeUnit.SECONDS.toMillis(1) - (System.currentTimeMillis() - lastSuggestedReview); if (delay < 0) { lastSuggestedReview = System.currentTimeMillis(); Computer.threadPoolForRemoting.submit(() -> { LOGGER.fine(() -> "running suggested review for " + label); update(); }); } else { queuedReview = true; LOGGER.fine(() -> "running suggested review in " + delay + " ms for " + label); Timer.get().schedule(() -> { lastSuggestedReview = System.currentTimeMillis(); LOGGER.fine(() -> "running suggested review for " + label + " after " + delay + " ms"); update(); }, delay, TimeUnit.MILLISECONDS); } } else { LOGGER.fine(() -> "ignoring suggested review for " + label); } }
Source:
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }

Target:
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }
Source:
public List<Observation> searchObservationByPatientAndCode(String patientUuid, List<TokenParam> codings) { Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); List<Observation> obsList = new ArrayList<>(); if (codings.isEmpty()) { return obsList; } else { for (TokenParam tokenParam : codings) { obsList.addAll(getObservations(patient, getConcept(tokenParam))); } } return new ArrayList<Observation>(new HashSet<>(obsList)); }

Target:
public List<Observation> searchObservationByPatientAndCode(String patientUuid, List<TokenParam> codings) { Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); List<Observation> obsList = new ArrayList<>(); if (codings.isEmpty()) { return obsList; } else { for (TokenParam tokenParam : codings) { obsList.addAll(getObservations(patient, getConcept(tokenParam))); } } return obsList; }
Source:
private void waitForInitCompleted(Duration duration) { boolean interrupted = false; long deadlineTimeout = System.nanoTime() + duration.toNanos(); try { while (true) { try { long timeRemaining = deadlineTimeout - System.nanoTime(); if (timeRemaining <= 0 || initCompleted) { return; } synchronized (initLock) { if (!initCompleted) { initLock.wait(TimeUnit.NANOSECONDS.toMillis(timeRemaining)); } } } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }

Target:
private void waitForInitCompleted(Duration duration) { boolean interrupted = false; long deadlineTimeout = System.nanoTime() + duration.toNanos(); try { while (true) { try { long timeRemainingInMillis = TimeUnit.NANOSECONDS.toMillis(deadlineTimeout - System.nanoTime()); if (timeRemainingInMillis <= 0 || initCompleted) { return; } synchronized (initLock) { if (!initCompleted) { initLock.wait(timeRemainingInMillis); } } } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
Source:
public List<State> queryKeyValueWithOperator(String key1, Object value1, String key2, DBSQueryOperator operator, Object value2, Set<String> ignored) { Map<String, Object> comparatorAndValue; switch (operator) { case IN: comparatorAndValue = Collections.singletonMap(QueryOperators.IN, value2); break; case NOT_IN: comparatorAndValue = Collections.singletonMap(QueryOperators.NIN, value2); break; default: throw new IllegalArgumentException(String.format("Unknown operator: %s", operator)); } Document filter = new Document(converter.keyToBson(key1), value1); filter.put(converter.keyToBson(key2), comparatorAndValue); addIgnoredIds(filter, ignored); return findAll(filter); }

Target:
public List<State> queryKeyValueWithOperator(String key1, Object value1, String key2, DBSQueryOperator operator, Object value2, Set<String> ignored) { Map<String, Object> comparatorAndValue; switch (operator) { case IN: comparatorAndValue = Map.of(QueryOperators.IN, value2); break; case NOT_IN: comparatorAndValue = Map.of(QueryOperators.NIN, value2); break; default: throw new IllegalArgumentException(String.format("Unknown operator: %s", operator)); } Document filter = new Document(converter.keyToBson(key1), value1); filter.put(converter.keyToBson(key2), comparatorAndValue); addIgnoredIds(filter, ignored); return findAll(filter); }
Source:
public ChangedLines changedLines(Provider<ReviewDb> db, PatchListCache cache) throws OrmException { if (changedLines == null) { Change c = change(db); if (c == null) { return null; } PatchSet ps = currentPatchSet(db); if (ps == null) { return null; } PatchList p; try { p = cache.get(c, ps); } catch (PatchListNotAvailableException e) { return null; } changedLines = new ChangedLines(p.getInsertions(), p.getDeletions()); for (PatchListEntry e : p.getPatches()) { if (Patch.COMMIT_MSG.equals(e.getNewName())) { continue; } } } return changedLines; }

Target:
public ChangedLines changedLines(Provider<ReviewDb> db, PatchListCache cache) throws OrmException { if (changedLines == null) { Change c = change(db); if (c == null) { return null; } PatchSet ps = currentPatchSet(db); if (ps == null) { return null; } PatchList p; try { p = cache.get(c, ps); } catch (PatchListNotAvailableException e) { return null; } changedLines = new ChangedLines(p.getInsertions(), p.getDeletions()); } return changedLines; }
Source:
private static String[] sanitizeNoteProjection(String[] projection) { if (projection == null) { return sDefaultNoteProjectionDBAccess; } List<String> sanitized = new ArrayList<>(); for (String column : projection) { int idx = projSearch(FlashCardsContract.Note.DEFAULT_PROJECTION, column); if (idx >= 0) { sanitized.add(sDefaultNoteProjectionDBAccess[idx]); } else { throw new IllegalArgumentException("Unknown column " + column); } } return sanitized.toArray(new String[sanitized.size()]); }

Target:
private static String[] sanitizeNoteProjection(String[] projection) { if (projection == null || projection.length == 0) { return sDefaultNoteProjectionDBAccess; } List<String> sanitized = new ArrayList<>(); for (String column : projection) { int idx = projSearch(FlashCardsContract.Note.DEFAULT_PROJECTION, column); if (idx >= 0) { sanitized.add(sDefaultNoteProjectionDBAccess[idx]); } else { throw new IllegalArgumentException("Unknown column " + column); } } return sanitized.toArray(new String[sanitized.size()]); }
Source:
private void fillMap(Map<String, ByteIterator> resultMap, Map<String, Object> properties, Set<String> fields) { if (fields == null || fields.size() == 0) { for (Map.Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() instanceof String) { resultMap.put(entry.getKey(), stringToByteIterator((String)(entry.getValue()))); } else { logger.error("Error! Not the format expected! Actually is {}", entry.getValue().getClass().getName()); System.exit(-1); } } } else { for (String field : fields) { if (properties.get(field) instanceof String) { resultMap.put(field, stringToByteIterator((String)(properties.get(field)))); } else { logger.error("Error! Not the format expected! Actually is {}", properties.get(field).getClass().getName()); System.exit(-1); } } } }

Target:
private boolean fillMap(Map<String, ByteIterator> resultMap, Map<String, Object> properties, Set<String> fields) { if (fields == null || fields.size() == 0) { for (Map.Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() instanceof String) { resultMap.put(entry.getKey(), stringToByteIterator((String)(entry.getValue()))); } else { logger.error("Error! Not the format expected! Actually is {}", entry.getValue().getClass().getName()); return false; } } } else { for (String field : fields) { if (properties.get(field) instanceof String) { resultMap.put(field, stringToByteIterator((String)(properties.get(field)))); } else { logger.error("Error! Not the format expected! Actually is {}", properties.get(field).getClass().getName()); return false; } } } return true; }
Source:
public Map<Term, Term> getEntries() { return UnmodifiableMap.decorate(entries); }

Target:
public Map<Term, Term> getEntries() { return UnmodifiableMap.unmodifiableMap(entries); }
Source:
public void onInfoWindowClick(Marker marker) { mCustomInfoWindowAdapter.cancelUpdates(); ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); String focusedStopId = mController.getFocusedStopId(); if (focusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }

Target:
public void onInfoWindowClick(Marker marker) { mCustomInfoWindowAdapter.cancelUpdates(); ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (mController != null && mController.getFocusedStopId() != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), mController.getFocusedStopId()); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }
Source:
public void test_wrong_lines_in_file() { settings.setProperty(JavaScriptPlugin.LCOV_UT_REPORT_PATH, "wrong_line_lcov.info"); DefaultFileSystem fs = newFileSystem(); DefaultInputFile inputFile = newSourceInputFile("sensortests/main/Person.js", "org/sonar/plugins/javascript/unittest/jstestdriver/sensortests/main/Person.js"); fs.add(inputFile.setLines(13)); newSensor(fs, settings).analyse(project, context); ArgumentCaptor<Measure> measures = ArgumentCaptor.forClass(Measure.class); verify(context, times(7)).saveMeasure((Resource) anyObject(), measures.capture()); for (Measure measure : measures.getAllValues()) { if (measure.getMetricKey() == CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY) { assertThat(measure.getData()).isEqualTo("5=1"); } else if (measure.getMetricKey() == CoreMetrics.CONDITIONS_BY_LINE_KEY) { assertThat(measure.getData()).isEqualTo("7=3"); } } }

Target:
public void test_wrong_lines_in_file() { settings.setProperty(JavaScriptPlugin.LCOV_UT_REPORT_PATH, "wrong_line_lcov.info"); DefaultFileSystem fs = newFileSystem(); fs.add(newSourceInputFile("fake_file.js")); newSensor(fs, settings).analyse(project, context); ArgumentCaptor<Measure> measures = ArgumentCaptor.forClass(Measure.class); verify(context, atLeast(2)).saveMeasure((Resource) anyObject(), measures.capture()); boolean lineCoverageMetric = false; boolean conditionCoverageMetric = false; for (Measure measure : measures.getAllValues()) { if (measure.getMetricKey().equals(CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY)) { assertThat(measure.getData()).isEqualTo("5=1"); lineCoverageMetric = true; } else if (measure.getMetricKey().equals(CoreMetrics.CONDITIONS_BY_LINE_KEY)) { assertThat(measure.getData()).isEqualTo("7=3"); conditionCoverageMetric = true; } } assertThat(lineCoverageMetric).isTrue(); assertThat(conditionCoverageMetric).isTrue(); }
Source:
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { User user = ess.getUser(sender.getPlayer()); boolean canDelOthers = (user == null || user.isAuthorized("essentials.delhome.others")); if (args.length == 1) { if (canDelOthers) { return getPlayers(server, sender); } return user != null ? user.getHomes() : Collections.emptyList(); } else if (args.length == 2 && canDelOthers) { try { user = getPlayer(server, args, 0, true, true); return user.getHomes(); } catch (Exception ex) { return Collections.emptyList(); } } else { return Collections.emptyList(); } }

Target:
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { User user = ess.getUser(sender.getPlayer()); boolean canDelOthers = (user == null || user.isAuthorized("essentials.delhome.others")); if (args.length == 1) { return canDelOthers ? getPlayers(server, sender) : user.getHomes(); } else if (args.length == 2 && canDelOthers) { try { user = getPlayer(server, args, 0, true, true); return user.getHomes(); } catch (Exception ex) { return Collections.emptyList(); } } else { return Collections.emptyList(); } }
Source:
private Collection<?> getViewerSelection() { ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { return ((IStructuredSelection) selection).toList(); } return Collections.emptyList(); }

Target:
private Collection<?> getViewerSelection() { return fViewer.getStructuredSelection().toList(); }
Source:
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { if (vm != null && vm.getType().equals(VirtualMachine.Type.User) && !Strings.isNullOrEmpty(rootVolChainInfo)) { String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } } }

Target:
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) { return; } String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } }
Source:
public void prepareRun(BatchSourceContext batchSourceContext) throws Exception { excelInputreaderConfig.validate(batchSourceContext.getFailureCollector()); createDatasets(null, batchSourceContext); Job job = JobUtils.createInstance(); String processFiles = ""; if (!Strings.isNullOrEmpty(excelInputreaderConfig.memoryTableName)) { processFiles = GSON.toJson(getAllProcessedFiles(batchSourceContext), ARRAYLIST_PREPROCESSED_FILES); } ExcelInputFormat.setConfigurations(job, excelInputreaderConfig.filePattern, excelInputreaderConfig.sheet, excelInputreaderConfig.reprocess, excelInputreaderConfig.sheetValue, excelInputreaderConfig.columnList, excelInputreaderConfig.skipFirstRow, excelInputreaderConfig.terminateIfEmptyRow, excelInputreaderConfig.rowsLimit, excelInputreaderConfig.ifErrorRecord, processFiles); ExcelInputFormat.addInputPaths(job, excelInputreaderConfig.filePath); ExcelInputFormat.setInputPathFilter(job, ExcelReaderRegexFilter.class); SourceInputFormatProvider inputFormatProvider = new SourceInputFormatProvider(ExcelInputFormat.class, job.getConfiguration()); batchSourceContext.setInput(Input.of(excelInputreaderConfig.referenceName, inputFormatProvider)); }

Target:
public void prepareRun(BatchSourceContext batchSourceContext) throws Exception { FailureCollector collector = batchSourceContext.getFailureCollector(); excelInputreaderConfig.validate(collector); collector.getOrThrowException(); createDatasets(batchSourceContext); collector.getOrThrowException(); Job job = JobUtils.createInstance(); String processFiles = ""; if (!Strings.isNullOrEmpty(excelInputreaderConfig.memoryTableName)) { processFiles = GSON.toJson(getAllProcessedFiles(batchSourceContext), ARRAYLIST_PREPROCESSED_FILES); } ExcelInputFormat.setConfigurations(job, excelInputreaderConfig.filePattern, excelInputreaderConfig.sheet, excelInputreaderConfig.reprocess, excelInputreaderConfig.sheetValue, excelInputreaderConfig.columnList, excelInputreaderConfig.skipFirstRow, excelInputreaderConfig.terminateIfEmptyRow, excelInputreaderConfig.rowsLimit, excelInputreaderConfig.ifErrorRecord, processFiles); ExcelInputFormat.addInputPaths(job, excelInputreaderConfig.filePath); ExcelInputFormat.setInputPathFilter(job, ExcelReaderRegexFilter.class); SourceInputFormatProvider inputFormatProvider = new SourceInputFormatProvider(ExcelInputFormat.class, job.getConfiguration()); batchSourceContext.setInput(Input.of(excelInputreaderConfig.referenceName, inputFormatProvider)); }
Source:
public JSONObject getSnapshot() { return new JSONObject(); }

Target:
public JSONObject getSnapshot() { return null; }
Source:
public void destroy() { super.destroy(); producer.close(); }

Target:
public void destroy() { try { super.destroy(); } finally { if (producer != null) { producer.close(); } } }
Source:
private static Map<CfgBlock, LiveVariables> compute(ControlFlowGraph cfg, SymbolTable symbols) { Map<CfgBlock, LiveVariables> liveVariablesPerBlock = new HashMap<>(); cfg.blocks().forEach(block -> liveVariablesPerBlock.put(block, LiveVariables.init(block, symbols))); Deque<CfgBlock> workList = new ArrayDeque<>(cfg.blocks()); while (!workList.isEmpty()) { CfgBlock currentBlock = workList.pop(); LiveVariables liveVariables = liveVariablesPerBlock.get(currentBlock); boolean liveInHasChanged = liveVariables.propagateBackwards(liveVariablesPerBlock); if (liveInHasChanged) { currentBlock.predecessors().forEach(workList::push); } } return liveVariablesPerBlock; }

Target:
private void compute(ControlFlowGraph cfg, SymbolTable symbols) { cfg.blocks().forEach(block -> liveVariablesPerBlock.put(block, LiveVariables.build(block, symbols))); Deque<CfgBlock> workList = new ArrayDeque<>(cfg.blocks()); while (!workList.isEmpty()) { CfgBlock currentBlock = workList.pop(); LiveVariables liveVariables = liveVariablesPerBlock.get(currentBlock); boolean liveInHasChanged = liveVariables.propagate(liveVariablesPerBlock); if (liveInHasChanged) { currentBlock.predecessors().forEach(workList::push); } } }
Source:
public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { LOG.debug("Sending pacemaker message to {}: {}", host, m.toString()); int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } LOG.error("error attempting to write to a channel {}.", e.getMessage()); } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.error("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }

Target:
public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { LOG.debug("Sending pacemaker message to {}: {}", host, m); int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } LOG.error("error attempting to write to a channel {}.", e.getMessage()); } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.error("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }
Source:
public DistributionSnapshot getSnapshot(String key, CoreSession session) { if (key == null || RuntimeSnapshot.LIVE_ALIASES.contains(key)) { return getRuntimeSnapshot(); } DistributionSnapshot snap = getPersistentSnapshots(session).get(key); if (snap == null && !isSiteMode()) { DistributionSnapshot rtsnap = getRuntimeSnapshot(); if (rtsnap.getKey().equals(key)) { return rtsnap; } } return snap; }

Target:
public DistributionSnapshot getSnapshot(String key, CoreSession session) { if (RuntimeSnapshot.LIVE_ALIASES.contains(key)) { if (!canSeeRuntimeSnapshot(session)) { throw new RuntimeServiceException("Live runtime cannot be snapshotted."); } return getRuntimeSnapshot(); } DistributionSnapshot snap = getPersistentSnapshots(session).get(key); if (snap == null && canSeeRuntimeSnapshot(session)) { DistributionSnapshot rtsnap = getRuntimeSnapshot(); if (rtsnap.getKey().equals(key)) { return rtsnap; } } return snap; }
Source:
public void analyzeMember(final AbstractJavaAccessNode node, final List<NameOccurrence> occurrences, final ClassScope classScope, final Object data) { if (!node.isPrivate()) { return; } for (final ASTVariableDeclarator varDecl: node.findChildrenOfType(ASTVariableDeclarator.class)) { if (varDecl.hasInitializer()) { ASTVariableInitializer varInit = varDecl.getInitializer(); List<ASTPrimaryPrefix> initPrefix = varInit.findDescendantsOfType(ASTPrimaryPrefix.class); boolean allLiterals = true; for (ASTPrimaryPrefix prefix: initPrefix) { if (!prefix.getType().isPrimitive() && !TypeHelper.isA(prefix, "java.lang.String")) { allLiterals = false; break; } } if (allLiterals) { return; } } } for (final NameOccurrence no : occurrences) { ClassScope usedAtScope = no.getLocation().getScope().getEnclosingScope(ClassScope.class); if (!classScope.equals(usedAtScope)) { addViolation(data, no.getLocation()); } } }

Target:
public void analyzeMember(final AbstractJavaAccessNode node, final List<NameOccurrence> occurrences, final ClassScope classScope, final Object data) { if (!node.isPrivate()) { return; } if (node.isFinal()) { for (final ASTVariableDeclarator varDecl: node.findChildrenOfType(ASTVariableDeclarator.class)) { if (varDecl.hasInitializer()) { ASTVariableInitializer varInit = varDecl.getInitializer(); List<ASTExpression> initExpression = varInit.findDescendantsOfType(ASTExpression.class); boolean isConstantExpression = true; constantCheck: for (ASTExpression exp: initExpression) { List<ASTPrimaryExpression> primaryExpressions = exp.findDescendantsOfType(ASTPrimaryExpression.class); for (ASTPrimaryExpression expression: primaryExpressions) { if (!isCompileTimeConstant(expression)) { isConstantExpression = false; break constantCheck; } } } if (isConstantExpression) { cache.add(varDecl.getName()); return; } } } } for (final NameOccurrence no : occurrences) { ClassScope usedAtScope = no.getLocation().getScope().getEnclosingScope(ClassScope.class); if (!classScope.equals(usedAtScope)) { addViolation(data, no.getLocation()); } } }
Source:
private <Q, R> QueryResponseMessage<R> interceptAndInvoke(UnitOfWork<QueryMessage<Q, R>> uow, MessageHandler<? super QueryMessage<?, R>> handler) throws Exception { return uow.executeWithResult(() -> { ResponseType<R> responseType = uow.getMessage().getResponseType(); Object queryResponse = new DefaultInterceptorChain<>(uow, handlerInterceptors, handler).proceed(); if (queryResponse instanceof Future) { queryResponse = ((Future) queryResponse).get(); } return GenericQueryResponseMessage.asNullableResponseMessage( responseType.responseMessagePayloadType(), responseType.convert(queryResponse)); }); }

Target:
private <Q, R> CompletableFuture<QueryResponseMessage<R>> interceptAndInvoke(UnitOfWork<QueryMessage<Q, R>> uow, MessageHandler<? super QueryMessage<?, R>> handler) throws Exception { return uow.executeWithResult(() -> { ResponseType<R> responseType = uow.getMessage().getResponseType(); Object queryResponse = new DefaultInterceptorChain<>(uow, handlerInterceptors, handler).proceed(); if (queryResponse instanceof CompletableFuture) { return ((CompletableFuture) queryResponse).thenCompose( result -> buildCompletableFuture(responseType, result)); } else if (queryResponse instanceof Future) { return CompletableFuture.supplyAsync(() -> { try { return ((Future) queryResponse).get(); } catch (InterruptedException | ExecutionException e) { throw new QueryExecutionException("Error happened while trying to execute query handler", e); } }); } return buildCompletableFuture(responseType, queryResponse); }); }
Source:
private String parseSwing(String value) { if (value.equals("UD")) return "Ud"; if (value.equals("OFF")) return "Off"; return "None"; }

Target:
private DaikinSwing parseSwing(String value) { if (value.equals("UD")) return DaikinSwing.UpDown; if (value.equals("OFF")) return DaikinSwing.Off; return DaikinSwing.None; }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionSubjects = hosts.stream() .map(host -> new PermissionSubject(host.getId(), VdcObjectType.VDS, ActionGroup.CONFIGURE_HOST_NETWORK)) .collect(Collectors.toList()); return permissionSubjects; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionSubjects = hosts.stream() .map(host -> new PermissionSubject(host.getId(), VdcObjectType.VDS, getActionType().getActionGroup())) .collect(Collectors.toList()); return permissionSubjects; }
Source:
public void testLocateParameterizedQuery1() throws Exception { ResultSet rs = null; String sqlText = format("select id, '-' || a2 || '-', locate(?, a5) from t1 --splice-properties useSpark=%s\n order by id", useSpark); try { PreparedStatement ps = methodWatcher.prepareStatement(sqlText); ps.setBytes(1, "ac".getBytes()); rs = ps.executeQuery(); String expected = "ID | 2 | 3 |\n" + "---------------------\n" + " 1 |-abac bc- | 3 |\n" + " 2 |-abac bc- | 3 |\n" + " 3 |-abac bc- | 3 |\n" + " 4 | -ab- | 0 |\n" + " 5 | -- | 0 |\n" + " 6 | -ab- | 0 |\n" + " 7 | NULL |NULL |"; Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } finally { if (rs != null) rs.close(); } }

Target:
public void testLocateParameterizedQuery1() throws Exception { String sqlText = format("select id, '-' || a2 || '-', locate(?, a5) from t1 --splice-properties useSpark=%s\n order by id", useSpark); try (PreparedStatement ps = methodWatcher.prepareStatement(sqlText)) { ps.setBytes(1, "ac".getBytes()); try (ResultSet rs = ps.executeQuery()) { String expected = "ID | 2 | 3 |\n" + "---------------------\n" + " 1 |-abac bc- | 3 |\n" + " 2 |-abac bc- | 3 |\n" + " 3 |-abac bc- | 3 |\n" + " 4 | -ab- | 0 |\n" + " 5 | -- | 0 |\n" + " 6 | -ab- | 0 |\n" + " 7 | NULL |NULL |"; Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } } }
Source:
private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); return (int) Math.max(1, Math.ceil(availableProcessors * 2.5d)); }

Target:
private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); return (int) Math.min(250, Math.max(1, Math.ceil(availableProcessors * 2.5d))); }
Source:
public void setColorspace(String colorspace) { if(!colorspace.equals(null)) { this.colorspace = colorspace; } else { throw new IllegalArgumentException("Invalid colorspace value"); } }

Target:
public void setColorspace(String colorspace) { if(!colorspace.equals(null)) { this.colorspace = colorspace; } else { throw new IllegalArgumentException("Colorspace value cannot be null."); } }
Source:
public ValidationResult allDomainsHaveSpaceForNewDisks(final List<DiskImage> disksList) { setDomainsDisksMap(disksList); return validOrFirstFailure(new ValidatorPredicate() { @Override public ValidationResult evaluate(StorageDomainValidator validator) { List disksForDomain = getDomainsDisksMap().get(validator.getDomainId()); return validator.hasSpaceForNewDisks(disksForDomain); } }); }

Target:
public ValidationResult allDomainsHaveSpaceForNewDisks(final List<DiskImage> disksList) { final Map<Guid, List<DiskImage>> domainsDisksMap = getDomainsDisksMap(disksList); return validOrFirstFailure(new ValidatorPredicate() { @Override public ValidationResult evaluate(Map.Entry<Guid, StorageDomainValidator> entry) { Guid sdId = entry.getKey(); List disksForDomain = domainsDisksMap.get(sdId); return getStorageDomainValidator(entry).hasSpaceForNewDisks(disksForDomain); } }); }
Source:
public void testPackageWithMainlineNetworkStackPermission() throws Exception { final PackageManager packageManager = mContext.getPackageManager(); assertNotNull("Network stack permission is not defined.", packageManager); final PermissionInfo permissioninfo = packageManager.getPermissionInfo(PERMISSION_MAINLINE_NETWORK_STACK, 0); assertNotNull("Package defining the network stack permission is not a system package.", permissioninfo); PackageInfo packageInfo = packageManager.getPackageInfo(permissioninfo.packageName, PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_PERMISSIONS); assertNotNull(packageInfo.permissions); for (PermissionInfo permission : packageInfo.permissions) { if (PERMISSION_MAINLINE_NETWORK_STACK.equals(permission.name)) { return; } } fail("Expect a system package defining " + PERMISSION_MAINLINE_NETWORK_STACK + " is installed."); }

Target:
public void testPackageWithMainlineNetworkStackPermission() throws Exception { final PackageManager packageManager = mContext.getPackageManager(); assertNotNull("Unable to find PackageManager.", packageManager); final PermissionInfo permissioninfo = packageManager.getPermissionInfo(PERMISSION_MAINLINE_NETWORK_STACK, 0); assertNotNull("Network stack permission is not defined.", permissioninfo); PackageInfo packageInfo = packageManager.getPackageInfo(permissioninfo.packageName, PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_PERMISSIONS); assertNotNull("Package defining the network stack permission is not a system package.", packageInfo.permissions); for (PermissionInfo permission : packageInfo.permissions) { if (PERMISSION_MAINLINE_NETWORK_STACK.equals(permission.name)) { return; } } fail("Expect a system package defining " + PERMISSION_MAINLINE_NETWORK_STACK + " is installed."); }
Source:
public void initializeAgentLogDir() { if (getPropertyImpl("go.agent.log.dir") == null) { String logDir = getEnvironmentVariable("LOG_DIR") == null ? "logs" : getEnvironmentVariable("LOG_DIR"); setProperty("go.agent.log.dir", logDir); } }

Target:
public void initializeAgentLogDir() { String logDir; logDir = getEnvironmentVariable("GO_AGENT_LOG_DIR") == null ? getEnvironmentVariable("LOG_DIR") : getEnvironmentVariable("GO_AGENT_LOG_DIR"); if (logDir == null) { logDir = "logs"; } setProperty("go.agent.log.dir", logDir); }
Source:
public Rule[] blockPluginRules() { return new Rule[]{ toc(), note(), cols(), }; }

Target:
public Rule[] blockPluginRules() { return new Rule[] { cols(), note(), toc(), }; }
Source:
public void testPrivateBitstream() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .build(); Group internalGroup = GroupBuilder.createGroup(context) .withName("Internal Group") .build(); String bitstreamContent = "Private!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Bitstream bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withReaderGroup(internalGroup) .build(); getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isForbidden()); checkNumberOfStatsRecords(bitstream, 0); } }

Target:
public void testPrivateBitstream() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .build(); Group internalGroup = GroupBuilder.createGroup(context) .withName("Internal Group") .build(); String bitstreamContent = "Private!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Bitstream bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withReaderGroup(internalGroup) .build(); getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isUnauthorized()); checkNumberOfStatsRecords(bitstream, 0); } }
Source:
protected void removeProvider(Provider<E> provider) { final Collection<E> removedElements = new LinkedList<>(); elementWriteLock.lock(); try { final Collection<E> providerElements = providerToElements.remove(provider); if (providerElements == null) { logger.warn("Cannot remove provider because it is unknown."); return; } for (final E element : providerElements) { try { onRemoveElement(element); } catch (final RuntimeException ex) { logger.warn( "Removal should be prevented but we need to remove the element as the provider is gone: {}", ex.getMessage(), ex); } removedElements.add(element); elements.remove(element); elementToProvider.remove(element); identifierToElement.remove(element.getUID()); } } finally { elementWriteLock.unlock(); } removedElements.forEach(this::notifyListenersAboutRemovedElement); provider.removeProviderChangeListener(this); logger.debug("Provider '{}' has been removed.", provider.getClass().getSimpleName()); }

Target:
protected void removeProvider(Provider<E> provider) { final Collection<E> removedElements = new LinkedList<>(); elementWriteLock.lock(); try { final Collection<E> providerElements = providerToElements.remove(provider); if (providerElements == null) { logger.warn("Cannot remove provider \"{}\" because it is unknown.", provider.getClass().getSimpleName()); return; } for (final E element : providerElements) { try { onRemoveElement(element); } catch (final RuntimeException ex) { logger.warn( "Removal of \"{}\" with key \"{}\" should be prevented but we need to remove the element as the provider \"{}\" is gone: {}", element.getClass().getSimpleName(), element.getUID(), provider.getClass().getSimpleName(), ex.getMessage(), ex); } removedElements.add(element); elements.remove(element); elementToProvider.remove(element); identifierToElement.remove(element.getUID()); } } finally { elementWriteLock.unlock(); } removedElements.forEach(this::notifyListenersAboutRemovedElement); provider.removeProviderChangeListener(this); logger.debug("Provider \"{}\" has been removed.", provider.getClass().getSimpleName()); }
Source:
private Optional<VM> chooseNextVmToMigrateFromVMsToHostsAffinity(Cluster cluster, List<AffinityGroup> allAffinityGroups) { VM vm = null; List<AffinityGroup> allVMtoHostsAffinityGroups = getAllAffinityGroupsForVMsToHostsAffinity(allAffinityGroups); if (allVMtoHostsAffinityGroups.isEmpty()) { return Optional.ofNullable(vm); } Map<Guid, VM> vmsMap = getVMsMap(allVMtoHostsAffinityGroups); List<Guid> candidateVMsPositiveEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, true); List<Guid> candidateVMsNegativeEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, true); List<Guid> candidateVMsPositiveNonEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, false); List<Guid> candidateVMsNegativeNonEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, false); List<Guid> canidatesVMs = new ArrayList<>(); canidatesVMs.addAll(candidateVMsPositiveEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsNegativeEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsPositiveNonEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsNegativeNonEnforcingAffinitiy); if (!canidatesVMs.isEmpty()) { log.info("vm to hosts affinity group violation detected"); } for (Guid id : canidatesVMs) { VM canidateVM = vmsMap.get(id); if (isVMmigrationValid(cluster, canidateVM)) { return Optional.of(canidateVM); } } return Optional.ofNullable(vm); }

Target:
private Optional<VM> chooseNextVmToMigrateFromVMsToHostsAffinity(Cluster cluster, List<AffinityGroup> allAffinityGroups) { List<AffinityGroup> allVMtoHostsAffinityGroups = getAllAffinityGroupsForVMsToHostsAffinity(allAffinityGroups); if (allVMtoHostsAffinityGroups.isEmpty()) { return Optional.empty(); } Map<Guid, VM> vmsMap = getVMsMap(allVMtoHostsAffinityGroups); List<Guid> candidateVMsPositiveEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, true); List<Guid> candidateVMsNegativeEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, true); List<Guid> candidateVMsPositiveNonEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, false); List<Guid> candidateVMsNegativeNonEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, false); List<Guid> candidatesVMs = new ArrayList<>(); candidatesVMs.addAll(candidateVMsPositiveEnforcingAffinity); candidatesVMs.addAll(candidateVMsNegativeEnforcingAffinity); candidatesVMs.addAll(candidateVMsPositiveNonEnforcingAffinity); candidatesVMs.addAll(candidateVMsNegativeNonEnforcingAffinity); if (!candidatesVMs.isEmpty()) { log.info("vm to hosts affinity group violation detected"); } for (Guid id : candidatesVMs) { VM canidateVM = vmsMap.get(id); if (isVmMigrationValid(cluster, canidateVM)) { return Optional.of(canidateVM); } } return Optional.empty(); }