auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); try { ProfileResponse profileResponse = getAvailableProfiles(); setDefaultProfile(getBankId(profileResponse.getBanks())); HttpResponse httpResponse = urlopen.openAsHttpResponse(getResourceUri("engagement/overview"), false); if(httpResponse.getStatusLine().getStatusCode() != 200) { throw new BankException(httpResponse.getStatusLine().toString()); } OverviewResponse overviewResponse = readJsonValue(httpResponse.getEntity().getContent(),OverviewResponse.class); addAccounts(overviewResponse.getTransactionAccounts(),Account.REGULAR); addAccounts(overviewResponse.getSavingAccounts(),Account.REGULAR); addAccounts(overviewResponse.getTransactionDisposalAccounts(),Account.REGULAR); addAccounts(overviewResponse.getSavingDisposalAccounts(),Account.REGULAR); addCardAccounts(overviewResponse.getCardAccounts()); addAccounts(overviewResponse.getLoanAccounts(),Account.LOANS); if (this.accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } } finally { updateComplete(); } }

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); ProfileResponse profileResponse = getAvailableProfiles(); setDefaultProfile(getBankId(profileResponse.getBanks())); HttpResponse httpResponse = urlopen.openAsHttpResponse(getResourceUri("engagement/overview"), false); if(httpResponse.getStatusLine().getStatusCode() != 200) { throw new BankException(httpResponse.getStatusLine().toString()); } OverviewResponse overviewResponse = readJsonValue(httpResponse.getEntity().getContent(),OverviewResponse.class); addAccounts(overviewResponse.getTransactionAccounts(),Account.REGULAR); addAccounts(overviewResponse.getSavingAccounts(),Account.REGULAR); addAccounts(overviewResponse.getTransactionDisposalAccounts(),Account.REGULAR); addAccounts(overviewResponse.getSavingDisposalAccounts(),Account.REGULAR); addCardAccounts(overviewResponse.getCardAccounts()); addAccounts(overviewResponse.getLoanAccounts(),Account.LOANS); if (this.accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } updateComplete(); }
Source:
private JButton getBtnOK() { if (btnOK == null) { btnOK = new JButton(); btnOK.setName("btnOK"); btnOK.setText(Constant.messages.getString("all.button.ok")); btnOK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { validateParam(); saveParam(); exitResult = JOptionPane.OK_OPTION; AbstractParamDialog.this.setVisible(false); } catch (Exception ex) { Constant.messages.getString("options.dialog.save.error", ex.getMessage()); } } }); } return btnOK; }

Target:
private JButton getBtnOK() { if (btnOK == null) { btnOK = new JButton(); btnOK.setName("btnOK"); btnOK.setText(Constant.messages.getString("all.button.ok")); btnOK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { validateParam(); saveParam(); exitResult = JOptionPane.OK_OPTION; AbstractParamDialog.this.setVisible(false); } catch (Exception ex) { View.getSingleton().showWarningDialog( Constant.messages.getString("options.dialog.save.error", ex.getMessage())); } } }); } return btnOK; }
Source:
public static HttpCompilationResponse readDefaultCompilationResponseFromBytes(byte[] bytes) { ObjectInput in = null; ByteArrayOutputStream bos = null; try { in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object newObj = in.readObject(); return (HttpCompilationResponse) newObj; } catch (NotSerializableException nse) { logger.debug("Object is not serializable {}", nse.getMessage()); StringBuilder sb = new StringBuilder("NotSerializableException:").append(nse.getMessage()); logger.error(sb.toString()); } catch (IOException ioe) { StringBuilder sb = new StringBuilder("IOException:").append(ioe.getMessage()); logger.error(sb.toString()); } catch (ClassNotFoundException cnfe) { StringBuilder sb = new StringBuilder("ClassNotFoundException:").append(cnfe.getMessage()); logger.error(sb.toString()); } catch (Exception e) { StringBuilder sb = new StringBuilder("Exception:").append(e.getMessage()); logger.error(sb.toString()); } finally { try { if (bos != null) { bos.close(); } if (in != null) { in.close(); } } catch (IOException ex) { logger.error(ex.getMessage()); } } return new DefaultHttpCompilationResponse(Boolean.FALSE); }

Target:
public static HttpCompilationResponse readDefaultCompilationResponseFromBytes(byte[] bytes) { ObjectInput in = null; ByteArrayOutputStream bos = null; try { in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object newObj = in.readObject(); return (HttpCompilationResponse) newObj; } catch (NotSerializableException nse) { logger.warn("Object is not serializable {}", nse.getMessage()); StringBuilder sb = new StringBuilder("NotSerializableException:").append(nse.getMessage()); logger.error(sb.toString()); } catch (IOException ioe) { StringBuilder sb = new StringBuilder("IOException:").append(ioe.getMessage()); logger.error(sb.toString()); } catch (ClassNotFoundException cnfe) { StringBuilder sb = new StringBuilder("ClassNotFoundException:").append(cnfe.getMessage()); logger.error(sb.toString()); } catch (Exception e) { StringBuilder sb = new StringBuilder("Exception:").append(e.getMessage()); logger.error(sb.toString()); } finally { try { if (bos != null) { bos.close(); } if (in != null) { in.close(); } } catch (IOException ex) { logger.error(ex.getMessage()); } } return new DefaultHttpCompilationResponse(Boolean.FALSE); }
Source:
private static Integer tryParseInt( String s ) { try { if ( !isParsable( s ) ) { return null; } long longValue = Long.parseLong( s ); if ( longValue > Integer.MAX_VALUE ) { return null; } return (int) longValue; } catch ( NumberFormatException e ) { return null; } }

Target:
private static Integer tryParseInt( String s ) { try { if ( !isDigits( s ) ) { return null; } long longValue = Long.parseLong( s ); if ( longValue > Integer.MAX_VALUE ) { return null; } return (int) longValue; } catch ( NumberFormatException e ) { return null; } }
Source:
public FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }

Target:
FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }
Source:
public <C> void addFilteredListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) { ListenerHolder listenerHolder = new ListenerHolder(listener, encoder, wrapper); Cache unwrapped = super.unwrapCache(this.cache); if(unwrapped instanceof CacheImpl) { ((CacheImpl)unwrapped).addFilteredListener(listenerHolder, filter, converter, filterAnnotations); } else { super.addFilteredListener(listener, filter, converter, filterAnnotations); } }

Target:
public <C> void addFilteredListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) { ListenerHolder listenerHolder = new ListenerHolder(listener, keyEncoderClass, valueEncoderClass, keyWrapperClass, valueWrapperClass); Cache unwrapped = super.unwrapCache(this.cache); if (unwrapped instanceof CacheImpl) { ((CacheImpl) unwrapped).addFilteredListener(listenerHolder, filter, converter, filterAnnotations); } else { super.addFilteredListener(listener, filter, converter, filterAnnotations); } }
Source:
public void clickOnFilterBoxTitle() { waitForElementVisibleByElement(mapFrame); scrollToElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementByElement(filterBoxTitle); Actions actions = new Actions(driver); actions.moveToElement(filterBoxTitle).click().perform(); driver.switchTo().defaultContent(); }

Target:
public void clickOnFilterBoxTitle() { waitForElementVisibleByElement(mapFrame); scrollToElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementByElement(filterBoxTitle); Actions actions = new Actions(driver); actions.moveToElement(filterBoxTitle).click().perform(); driver.switchTo().defaultContent(); PageObjectLogging.log("clickOnFilterBoxTitle", "Filter box title was clicked", true); }
Source:
Mono<Response<DocumentResultCollection<RecognizeLinkedEntitiesResult>>> recognizeBatchLinkedEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(convertToMultiLanguageInput(textInputs)); return service.entitiesLinkingWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", ignoredValue)) .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }

Target:
Mono<Response<DocumentResultCollection<RecognizeLinkedEntitiesResult>>> recognizeBatchLinkedEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(convertToMultiLanguageInput(textInputs)); return service.entitiesLinkingWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }
Source:
private ModuleInfoWriter nameAccessAndVersion(Entry<String, Attrs> instruction, Parameters requireCapability, Analyzer analyzer) { Attrs attrs = instruction.getValue(); String name = instruction.getKey(); String access = attrs.computeIfAbsent("access", k -> String.valueOf(access(requireCapability))); String version = attrs.computeIfAbsent("version", k -> analyzer.getVersion()); return new ModuleInfoWriter(Clazz.JAVA.OpenJDK9.getMajor(), name, version, Integer.valueOf(access) == ModuleAttribute.ACC_OPEN); }

Target:
private ModuleInfoWriter nameAccessAndVersion(Entry<String, Attrs> instruction, Parameters requireCapability, Analyzer analyzer) { Attrs attrs = instruction.getValue(); String name = instruction.getKey(); String access = attrs.computeIfAbsent("access", k -> String.valueOf(access(requireCapability))); String version = attrs.computeIfAbsent("version", k -> analyzer.getVersion()); return new ModuleInfoWriter(Clazz.JAVA.OpenJDK9.getMajor(), name, version, Integer.parseInt(access) == ModuleAttribute.ACC_OPEN); }
Source:
@Test public void testGeoServerEnvParametrization() throws Exception { GeoServerSecurityManager secMgr = getSecurityManager(); SecurityManagerConfig config = secMgr.loadSecurityConfig(); String oldRoleServiceName = config.getRoleServiceName(); try { if (GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) { System.setProperty("TEST_SYS_PROPERTY", oldRoleServiceName); config.setRoleServiceName("${TEST_SYS_PROPERTY}"); secMgr.saveSecurityConfig(config); SecurityManagerConfig config1 = secMgr.loadSecurityConfig(); assertEquals(config1.getRoleServiceName(), oldRoleServiceName); } } finally { config.setRoleServiceName(oldRoleServiceName); secMgr.saveSecurityConfig(config); } }

Target:
@Test public void testGeoServerEnvParametrization() throws Exception { GeoServerSecurityManager secMgr = getSecurityManager(); SecurityManagerConfig config = secMgr.loadSecurityConfig(); String oldRoleServiceName = config.getRoleServiceName(); try { if (GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) { System.setProperty("TEST_SYS_PROPERTY", oldRoleServiceName); config.setRoleServiceName("${TEST_SYS_PROPERTY}"); secMgr.saveSecurityConfig(config); SecurityManagerConfig config1 = secMgr.loadSecurityConfig(); assertEquals(config1.getRoleServiceName(), oldRoleServiceName); } } finally { config.setRoleServiceName(oldRoleServiceName); secMgr.saveSecurityConfig(config); System.setProperty("TEST_SYS_PROPERTY", ""); } }
Source:
public CurrencyAmount presentValue( ResolvedCdsIndex cdsIndex, CreditRatesProvider ratesProvider, LocalDate referenceDate, PriceType priceType, ReferenceData refData) { if (isExpired(cdsIndex, ratesProvider)) { return CurrencyAmount.of(cdsIndex.getCurrency(), 0d); } ResolvedCds cds = cdsIndex.toSingleNameCds(); LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = underlyingPricer.recoveryRate(cds, ratesProvider); Triple<CreditDiscountFactors, LegalEntitySurvivalProbabilities, Double> rates = reduceDiscountFactors(cds, ratesProvider); double protectionLeg = (1d - recoveryRate) * underlyingPricer.protectionFull(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate); double rpv01 = underlyingPricer.riskyAnnuity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate, priceType); return CurrencyAmount.of(cds.getCurrency(), cds.getBuySell().normalize(cds.getNotional()) * rates.getThird() * (protectionLeg - rpv01 * cds.getFixedRate())); }

Target:
public CurrencyAmount presentValue( ResolvedCdsIndex cdsIndex, CreditRatesProvider ratesProvider, LocalDate referenceDate, PriceType priceType, ReferenceData refData) { if (isExpired(cdsIndex, ratesProvider)) { return CurrencyAmount.of(cdsIndex.getCurrency(), 0d); } ResolvedCds cds = cdsIndex.toSingleNameCds(); LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = underlyingPricer.recoveryRate(cds, ratesProvider); Triple<CreditDiscountFactors, LegalEntitySurvivalProbabilities, Double> rates = reduceDiscountFactors(cds, ratesProvider); double protectionLeg = (1d - recoveryRate) * underlyingPricer.protectionFull(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate); double rpv01 = underlyingPricer.riskyAnnuity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate, priceType); double amount = cds.getBuySell().normalize(cds.getNotional()) * rates.getThird() * (protectionLeg - rpv01 * cds.getFixedRate()); return CurrencyAmount.of(cds.getCurrency(), amount); }
Source:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - 5, ptInDisplay.y - 5, 10, 10); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display.getDefault().addFilter(SWT.MouseExit, fListener); } }); }

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display.getDefault().addFilter(SWT.MouseMove, fListener); } }); }
Source:
synchronized void destroy() { if (shutdownHook != null) { Runtime.getRuntime().removeShutdownHook(shutdownHook); } if (workerMultiplexer.isAlive()) { workerMultiplexer.interrupt(); } workerMultiplexer.destroyMultiplexer(); }

Target:
synchronized void destroy() throws IOException { super.destroy(); try { WorkerMultiplexerManager.removeInstance(workerKey.hashCode()); } catch (InterruptedException e) { logger.warning("InterruptedException was caught while destroying multiplexer. " + "It could because the multiplexer was interrupted."); } catch (UserExecException e) { logger.warning(e.toString()); } }
Source:
static boolean targetEqualsSource(Object target, Object srcObject) { if (target == null) { return false; } if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { return true; } } } if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { return true; } } } return target.equals(srcObject); }

Target:
private static boolean targetEqualsSource(Object target, Object srcObject) { if (target == null) { return false; } if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { return true; } } } if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { return true; } } } return target.equals(srcObject); }
Source:
public void beginTask(String name, int totalWork) { final long timestamp = System.currentTimeMillis(); fStartTime = timestamp; final boolean animated = (totalWork == UNKNOWN || totalWork == 0); Runnable timer = () -> StatusLine.this.startTask(timestamp, animated); if (fProgressBar == null) { return; } fProgressBar.getDisplay().timerExec(DELAY_PROGRESS, timer); inUIThread(() -> { if (!animated) { fProgressBar.beginTask(totalWork); } if (name == null) { fTaskName = Util.ZERO_LENGTH_STRING; } else { fTaskName = name; } setMessage(fTaskName); }); }

Target:
public void beginTask(String name, int totalWork) { final long timestamp = System.currentTimeMillis(); fStartTime = timestamp; if (fProgressBar == null) { return; } final boolean animated = (totalWork == UNKNOWN || totalWork == 0); Runnable timer = () -> StatusLine.this.startTask(timestamp, animated); inUIThread(() -> { fProgressBar.getDisplay().timerExec(DELAY_PROGRESS, timer); if (!animated) { fProgressBar.beginTask(totalWork); } if (name == null) { fTaskName = Util.ZERO_LENGTH_STRING; } else { fTaskName = name; } setMessage(fTaskName); }); }
Source:
public void complete() { cleanup(getId()); finalizeStats(); setFinishTime(); eventHandler.handle(new SubQueryCompletedEvent(getId(), SubQueryState.SUCCEEDED)); }

Target:
public void complete() { cleanup(); finalizeStats(); setFinishTime(); eventHandler.handle(new SubQueryCompletedEvent(getId(), SubQueryState.SUCCEEDED)); }
Source:
public void testIndirectIAMAndNotificationOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); sessionManager.onInAppMessageReceived(IAM_ID); sessionManager.onNotificationReceived(NOTIFICATION_ID); sessionManager.restartSessionIfNeeded(OneSignal.AppEntryAction.APP_OPEN); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); new Thread(new Runnable() { @Override public void run() { handler.setOutcomes(repository.getSavedOutcomeEvents()); } }, "OS_GET_SAVED_OUTCOMES_SUCCESS").start(); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{\"indirect\":{\"notification_ids\":[\"notification_id\"],\"in_app_message_ids\":[\"iam_id\"]}},\"device_type\":1}", service.getLastJsonObjectSent()); }

Target:
public void testIndirectIAMAndNotificationOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); sessionManager.onInAppMessageReceived(IAM_ID); sessionManager.onNotificationReceived(NOTIFICATION_ID); sessionManager.restartSessionIfNeeded(OneSignal.AppEntryAction.APP_OPEN); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); handler.setOutcomes(repository.getSavedOutcomeEvents()); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{\"indirect\":{\"notification_ids\":[\"notification_id\"],\"in_app_message_ids\":[\"iam_id\"]}},\"device_type\":1}", service.getLastJsonObjectSent()); }
Source:
public static <T extends IndexedRecord> T decodeAvroGenericRecord(Schema schema, byte[] bytes, T reuse) throws IOException { BinaryDecoder binDecoder = DecoderFactory.defaultFactory().createBinaryDecoder(bytes, null); GenericDatumReader<T> reader = new GenericDatumReader<>(schema); return reader.read(reuse, binDecoder); }

Target:
public static <T> T decodeAvroGenericRecord(Schema schema, byte[] bytes, T reuse) throws IOException { BinaryDecoder binDecoder = DecoderFactory.defaultFactory().createBinaryDecoder(bytes, null); GenericDatumReader<T> reader = new GenericDatumReader<>(schema); return reader.read(reuse, binDecoder); }
Source:
public static ClassFilter of(Predicate<String> namePredicate, Predicate<Class<?>> classPredicate) { Preconditions.notNull(namePredicate, "name predicate must not be null"); Preconditions.notNull(classPredicate, "class predicate must not be null"); return new ClassFilter(namePredicate, classPredicate); }

Target:
public static ClassFilter of(Predicate<String> namePredicate, Predicate<Class<?>> classPredicate) { return new ClassFilter(namePredicate, classPredicate); }
Source:
private void scheduleExplictLacFlush() { int explicitLacIntervalInSec = lh.bk.getExplicitLacInterval(); final SafeRunnable updateLacTask = new SafeRunnable() { @Override public void safeRun() { if (getExplicitLac() < getPiggyBackedLac()) { LOG.debug("ledgerid: {}", lh.getId()); LOG.debug("explicitLac:{} piggybackLac:{}", getExplicitLac(), getPiggyBackedLac()); setExplicitLac(getPiggyBackedLac()); return; } if (lh.getLastAddConfirmed() > getExplicitLac()) { LOG.debug("ledgerid: {}", lh.getId()); asyncExplicitLacFlush(lh.getLastAddConfirmed()); setExplicitLac(lh.getLastAddConfirmed()); LOG.debug("After sending explict LAC lac: explicitLac:{}", lh.getLastAddConfirmed(), getExplicitLac()); } } @Override public String toString() { return String.format("UpdateLacTask ledgerId - (%d)", lh.getId()); } }; try { scheduledFuture = lh.bk.mainWorkerPool.scheduleAtFixedRateOrdered(lh.getId(), updateLacTask, explicitLacIntervalInSec, explicitLacIntervalInSec, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException re) { LOG.error("Scheduling of ExplictLastAddConfirmedFlush for ledger: has failed because of {}", lh.getId(), re); } }

Target:
private void scheduleExplictLacFlush() { int explicitLacIntervalInMs = lh.bk.getExplicitLacInterval(); final SafeRunnable updateLacTask = new SafeRunnable() { @Override public void safeRun() { if (getExplicitLac() < getPiggyBackedLac()) { LOG.debug("ledgerid: {}", lh.getId()); LOG.debug("explicitLac:{} piggybackLac:{}", getExplicitLac(), getPiggyBackedLac()); setExplicitLac(getPiggyBackedLac()); return; } if (lh.getLastAddConfirmed() > getExplicitLac()) { LOG.debug("ledgerid: {}", lh.getId()); asyncExplicitLacFlush(lh.getLastAddConfirmed()); setExplicitLac(lh.getLastAddConfirmed()); LOG.debug("After sending explict LAC lac: explicitLac:{}", lh.getLastAddConfirmed(), getExplicitLac()); } } @Override public String toString() { return String.format("UpdateLacTask ledgerId - (%d)", lh.getId()); } }; try { scheduledFuture = lh.bk.mainWorkerPool.scheduleAtFixedRateOrdered(lh.getId(), updateLacTask, explicitLacIntervalInMs, explicitLacIntervalInMs, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException re) { LOG.error("Scheduling of ExplictLastAddConfirmedFlush for ledger: has failed because of {}", lh.getId(), re); } }
Source:
public AboutInfo[] getFeatureInfos() { List infos = new ArrayList(); IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { IBundleGroup[] bundleGroups = provider.getBundleGroups(); for (IBundleGroup bundleGroup : bundleGroups) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }

Target:
public AboutInfo[] getFeatureInfos() { List infos = new ArrayList(); IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { for (IBundleGroup bundleGroup : provider.getBundleGroups()) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }
Source:
public void add(Parse daughter, HeadRules rules) { if (daughter.prevPunctSet != null) { parts.addAll(daughter.prevPunctSet); } parts.add(daughter); this.span = new Span(span.getStart(),daughter.getSpan().getEnd()); this.head = rules.getHead(getChildren(),type); if (head == null) { System.err.println(parts); throw new IllegalArgumentException("Rule returned null head!"); } this.headIndex = head.headIndex; }

Target:
public void add(Parse daughter, HeadRules rules) { if (daughter.prevPunctSet != null) { parts.addAll(daughter.prevPunctSet); } parts.add(daughter); this.span = new Span(span.getStart(),daughter.getSpan().getEnd()); this.head = rules.getHead(getChildren(),type); this.headIndex = head.headIndex; }
Source:
private static AECableType from( AECableVariant variant, AECableSize size ) { switch( variant ) { case GLASS: switch( size ) { case THIN: return GLASS; default: break; } break; case COVERED: switch( size ) { case NORMAL: return COVERED; case DENSE: return DENSE_COVERED; default: break; } break; case SMART: switch( size ) { case NORMAL: return SMART; case DENSE: return DENSE_SMART; default: break; } break; default: break; } return NONE; }

Target:
private static AECableType from( AECableVariant variant, AECableSize size ) { switch( variant ) { case GLASS: switch( size ) { case NORMAL: return GLASS; default: break; } break; case COVERED: switch( size ) { case NORMAL: return COVERED; case DENSE: return DENSE_COVERED; default: break; } break; case SMART: switch( size ) { case NORMAL: return SMART; case DENSE: return DENSE_SMART; default: break; } break; default: break; } return NONE; }
Source:
public static void export(BriefcaseFormDefinition formDefinition, ExportConfiguration configuration, TerminationFuture terminationFuture) { if (formDefinition.isFileEncryptedForm() || formDefinition.isFieldEncryptedForm()) { formDefinition.setPrivateKey(readPemFile(configuration.getPemFile() .orElseThrow(() -> new RuntimeException("PEM file not present")) ).get()); } boolean overwriteExistingFiles = configuration.getOverwriteExistingFiles().isPresent() ? configuration.getOverwriteExistingFiles().get() : false; ExportToCsv action = new ExportToCsv( terminationFuture, configuration.getExportDir().orElseThrow(() -> new RuntimeException("Export dir not present")).toFile(), formDefinition, formDefinition.getFormName(), true, overwriteExistingFiles, configuration.mapStartDate((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null), configuration.mapEndDate((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null) ); try { boolean allSuccessful = action.doAction(); if (!allSuccessful) EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); if (allSuccessful && action.noneSkipped()) EventBus.publish(new ExportSucceededEvent(action.getFormDefinition())); if (allSuccessful && action.someSkipped()) EventBus.publish(new ExportSucceededWithErrorsEvent(action.getFormDefinition())); if (allSuccessful && action.allSkipped()) EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); } catch (Exception e) { log.error("export action failed", e); EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); } }

Target:
public static void export(BriefcaseFormDefinition formDefinition, ExportConfiguration configuration, TerminationFuture terminationFuture) { if (formDefinition.isFileEncryptedForm() || formDefinition.isFieldEncryptedForm()) { formDefinition.setPrivateKey(readPemFile(configuration.getPemFile() .orElseThrow(() -> new RuntimeException("PEM file not present")) ).get()); } ExportToCsv action = new ExportToCsv( terminationFuture, configuration.getExportDir().orElseThrow(() -> new RuntimeException("Export dir not present")).toFile(), formDefinition, formDefinition.getFormName(), true, configuration.getOverwriteExistingFiles().orElse(false), configuration.mapStartDate((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null), configuration.mapEndDate((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null) ); try { boolean allSuccessful = action.doAction(); if (!allSuccessful) EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); if (allSuccessful && action.noneSkipped()) EventBus.publish(new ExportSucceededEvent(action.getFormDefinition())); if (allSuccessful && action.someSkipped()) EventBus.publish(new ExportSucceededWithErrorsEvent(action.getFormDefinition())); if (allSuccessful && action.allSkipped()) EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); } catch (Exception e) { log.error("export action failed", e); EventBus.publish(new ExportFailedEvent(action.getFormDefinition())); } }
Source:
public static float STATS_NULL_FRACTION(ColumnStatisticsImpl itemStatistics){ if(itemStatistics==null) return 0; if (itemStatistics.notNullCount() == 0) return 0; return ((float) itemStatistics.nullCount()/ (float) itemStatistics.notNullCount()); }

Target:
public static float STATS_NULL_FRACTION(ColumnStatisticsImpl itemStatistics){ if(itemStatistics==null) return 0; if (itemStatistics.notNullCount() + itemStatistics.nullCount() == 0) return 0; return ((float) itemStatistics.nullCount()/ (float) (itemStatistics.notNullCount()+itemStatistics.nullCount())); }
Source:
private synchronized void resetLogUnit(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { if (msg.getPayload() <= serverContext.getLogUnitEpochWaterMark() || msg.getPayload() != serverContext.getServerEpoch()) { log.info("LogUnit Server Reset request received but reset already done."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); return; } serverContext.setLogUnitEpochWaterMark(msg.getPayload()); Lock lock = resetLock.writeLock(); lock.lock(); try { CompletableFuture<Void> cf = batchWriter .addTask(RESET, msg) .thenRun(() -> { dataCache.invalidateAll(); log.info("LogUnit Server Reset."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); cf.join(); } finally { lock.unlock(); } }

Target:
private synchronized void resetLogUnit(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { if (msg.getPayload() <= serverContext.getLogUnitEpochWaterMark() || msg.getPayload() != serverContext.getServerEpoch()) { log.info("LogUnit Server Reset request received but reset already done."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); return; } serverContext.setLogUnitEpochWaterMark(msg.getPayload()); CompletableFuture<Void> cf = batchWriter .addTask(RESET, msg) .thenRun(() -> { dataCache.invalidateAll(); log.info("LogUnit Server Reset."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
public QuorumServer(long id, String hostname, Integer port, Integer electionPort, LearnerType type) { this.id = id; this.hostname=hostname; if (port!=null){ this.port=port; } if (electionPort!=null){ this.electionPort=electionPort; } if (type!=null){ this.type = type; } String checkIPReachableValue = System.getProperty("zookeeper.checkIPTimeout"); if(checkIPReachableValue != null){ this.checkIPReachableTO = Integer.parseInt(checkIPReachableValue); } this.recreateSocketAddresses(); }

Target:
public QuorumServer(long id, String hostname, Integer port, Integer electionPort, LearnerType type) { this.id = id; this.hostname=hostname; if (port!=null){ this.port=port; } if (electionPort!=null){ this.electionPort=electionPort; } if (type!=null){ this.type = type; } this.recreateSocketAddresses(); }
Source:
public boolean explodeWithEvent() { if (power < 0.1f) { return true; } Set<BlockVector> droppedBlocks = calculateBlocks(); List<Block> blocks = toBlockList(droppedBlocks); if (source != null) { EntityExplodeEvent event = EventFactory.getInstance().callEvent( new EntityExplodeEvent(source, location, blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } else { BlockExplodeEvent event = EventFactory.getInstance().callEvent( new BlockExplodeEvent(location.getBlock(), blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } playOutSoundAndParticles(); for (Block block : blocks) { handleBlockExplosion((GlowBlock) block); } if (incendiary) { for (Block block : blocks) { setBlockOnFire((GlowBlock) block); } } damageEntities(); Collection<GlowPlayer> affectedPlayers = collectPlayersInRadius(EXPLOSION_VISIBILITY_RADIUS * (int)this.power); for (GlowPlayer player : affectedPlayers) { if (player.getGameMode() != GameMode.CREATIVE & player.getGameMode() != GameMode.SPECTATOR) { playOutExplosion(player, blocks); } } return true; }

Target:
public boolean explodeWithEvent() { if (power < 0.1f) { return true; } Set<BlockVector> droppedBlocks = calculateBlocks(); List<Block> blocks = toBlockList(droppedBlocks); if (source != null) { EntityExplodeEvent event = EventFactory.getInstance().callEvent( new EntityExplodeEvent(source, location, blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } else { BlockExplodeEvent event = EventFactory.getInstance().callEvent( new BlockExplodeEvent(location.getBlock(), blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } playOutSoundAndParticles(); for (Block block : blocks) { handleBlockExplosion((GlowBlock) block); } if (incendiary) { for (Block block : blocks) { setBlockOnFire((GlowBlock) block); } } damageEntities(); Collection<GlowPlayer> affectedPlayers = collectPlayersInRadius(EXPLOSION_VISIBILITY_RADIUS * (int)this.power); for (GlowPlayer player : affectedPlayers) { switch(player.getGameMode()){ case GameMode.CREATIVE: case GameMode.SPECTATOR: break; default: playOutExplosion(player, blocks); } } return true; }
Source:
public void writeModelsToDisk(String dir, String modelName){ chunker.write(dir + modelName + ".lc", dir + modelName + ".lex"); System.out.println("Done training, models are in " + dir+modelName+".lc (.lex)"); }

Target:
public void writeModelsToDisk(String dir, String modelName){ IOUtils.mkdir(dir); chunker.write(dir + File.separator + modelName + ".lc", dir + File.separator + modelName + ".lex"); System.out.println("Done training, models are in " + dir+File.separator+modelName+".lc (.lex)"); }
Source:
public void start(final Environment env) throws IOException { try { parseCommandLine(); if (Strings.isNullOrEmpty(commandName)) { StringWriter msg = new StringWriter(); msg.write(usage()); throw new UnloggedFailure(1, msg.toString()); } final CommandProvider p = commands.get(commandName); if (p == null) { String msg = (getName().isEmpty() ? "Gerrit Code Review" : getName()) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.getProvider().get(); checkRequiresCapability(getName(), cmd); if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (getName().isEmpty()) bc.setName(commandName); else bc.setName(getName() + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); atomicCmd.set(cmd); cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }

Target:
public void start(final Environment env) throws IOException { try { parseCommandLine(); if (Strings.isNullOrEmpty(commandName)) { StringWriter msg = new StringWriter(); msg.write(usage()); throw new UnloggedFailure(1, msg.toString()); } final CommandProvider p = commands.get(commandName); if (p == null) { String msg = (getName().isEmpty() ? "Gerrit Code Review" : getName()) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.getProvider().get(); checkRequiresCapability(cmd); if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (getName().isEmpty()) bc.setName(commandName); else bc.setName(getName() + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); atomicCmd.set(cmd); cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }
Source:
public void execute() { for (NetworkHealthBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String hostname = provider.getHostname(itemName); int port = provider.getPort(itemName); if (provider.getTimeout(itemName) > 0) { timeout = provider.getTimeout(itemName); } boolean success = false; try { success = Ping.checkVitality(hostname, port, timeout); if(success) logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); else logger.debug("couldn't established connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } catch (SocketTimeoutException se) { logger.debug("timed out while connecting [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } if (eventPublisher != null) { if (shouldPostUpdate(hostname, port, success)) { eventPublisher.postUpdate(itemName, success ? OnOffType.ON : OnOffType.OFF); } } } } }

Target:
public void execute() { for (NetworkHealthBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String hostname = provider.getHostname(itemName); int port = provider.getPort(itemName); if (provider.getTimeout(itemName) > 0) { timeout = provider.getTimeout(itemName); } boolean success = false; try { success = Ping.checkVitality(hostname, port, timeout); if(success) { logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } else { logger.debug("couldn't establish connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } } catch (SocketTimeoutException se) { logger.debug("timed out while connecting [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } if (eventPublisher != null) { if (shouldPostUpdate(hostname, port, success)) { eventPublisher.postUpdate(itemName, success ? OnOffType.ON : OnOffType.OFF); } } } } }
Source:
protected void putManagedState(Object tuple) { ((ManagedTimeUnifiedStateImpl)managedState).put(getTime(tuple), getKey(tuple), new Slice(null)); }

Target:
protected void putManagedState(Object tuple) { ((ManagedTimeUnifiedStateImpl)managedState).put(getTime(tuple), getKey(tuple), new Slice(null, 0, 0)); }
Source:
beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeReceiptsOptions recognizeReceiptsOptions, Context context) { try { Objects.requireNonNull(receipt, "'receipt' is required and cannot be null."); recognizeReceiptsOptions = getRecognizeReceiptOptions(recognizeReceiptsOptions); final boolean isFieldElementsIncluded = recognizeReceiptsOptions.isFieldElementsIncluded(); final String localeInfo = recognizeReceiptsOptions.getLocale() == null ? "" : recognizeReceiptsOptions.getLocale(); return new PollerFlux<>( recognizeReceiptsOptions.getPollInterval(), streamActivationOperation( (contentType -> service.analyzeReceiptAsyncWithResponseAsync( contentType, receipt, length, isFieldElementsIncluded, localeInfo, context) .map(response -> new FormRecognizerOperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))), receipt, recognizeReceiptsOptions.getContentType()), pollingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)) .andThen(after -> after.map(modelSimpleResponse -> toRecognizedForm(modelSimpleResponse.getValue().getAnalyzeResult(), isFieldElementsIncluded)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist))); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }

Target:
beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeReceiptsOptions recognizeReceiptsOptions, Context context) { try { Objects.requireNonNull(receipt, "'receipt' is required and cannot be null."); recognizeReceiptsOptions = getRecognizeReceiptOptions(recognizeReceiptsOptions); final boolean isFieldElementsIncluded = recognizeReceiptsOptions.isFieldElementsIncluded(); final String localeInfo = recognizeReceiptsOptions.getLocale(); return new PollerFlux<>( recognizeReceiptsOptions.getPollInterval(), streamActivationOperation( (contentType -> service.analyzeReceiptAsyncWithResponseAsync( contentType, receipt, length, isFieldElementsIncluded, localeInfo, context) .map(response -> new FormRecognizerOperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))), receipt, recognizeReceiptsOptions.getContentType()), pollingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)) .andThen(after -> after.map(modelSimpleResponse -> toRecognizedForm(modelSimpleResponse.getValue().getAnalyzeResult(), isFieldElementsIncluded, null)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist))); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }
Source:
public Iterable<Channel> allChannels(ChannelQuery query) { MongoQueryBuilder mongoQuery = new MongoQueryBuilder(); if (query.getBroadcaster().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.BROADCASTER, query.getBroadcaster().get().key()); } if (query.getMediaType().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.MEDIA_TYPE, query.getMediaType().get().name()); } if (query.getAvailableFrom().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.AVAILABLE_ON, query.getAvailableFrom().get().key()); } if (query.getChannelGroups().isPresent()) { mongoQuery.longFieldIn(JOIN_ON_DOT.join(ChannelTranslator.NUMBERINGS, ChannelNumberingTranslator.CHANNEL_GROUP_KEY, MongoConstants.ID), query.getChannelGroups().get()); } return Iterables.transform(collection.find(mongoQuery.build()), DB_TO_CHANNEL_TRANSLATOR); }

Target:
public Iterable<Channel> allChannels(ChannelQuery query) { MongoQueryBuilder mongoQuery = new MongoQueryBuilder(); if (query.getBroadcaster().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.BROADCASTER, query.getBroadcaster().get().key()); } if (query.getMediaType().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.MEDIA_TYPE, query.getMediaType().get().name()); } if (query.getAvailableFrom().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.AVAILABLE_ON, query.getAvailableFrom().get().key()); } if (query.getChannelGroups().isPresent()) { mongoQuery.longFieldIn(NUMBERING_CHANNEL_GROUP_ID, query.getChannelGroups().get()); } return Iterables.transform(getOrderedCursor(mongoQuery.build()), DB_TO_CHANNEL_TRANSLATOR); }
Source:
private boolean CanFindVdsToRun(List<String> messages, boolean isMigrate, Iterable<VDS> vdss) { VdcBllMessages messageToReturn = VdcBllMessages.Unassigned; RpmVersion vdsVersion = null; boolean noVDSs = true; StringBuffer sb = new StringBuffer(); for (VDS curVds : vdss) { if (isMigrate && getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) { continue; } noVDSs = false; ValidationResult result = validateHostIsReadyToRun(curVds, sb); if (result.isValid()) { return true; } else { if (messageToReturn.getValue() < result.getMessage().getValue()) { messageToReturn = result.getMessage(); vdsVersion = curVds.getVersion(); } } } if (noVDSs) { if (messages != null) { messageToReturn = VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_AVAILABLE_IN_CLUSTER; } } if (messages != null) { messages.add(messageToReturn.toString()); if (messageToReturn == VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_VERSION && vdsVersion != null) { VmHandler.UpdateVmGuestAgentVersion(getVm()); messages.add("$toolsVersion " + getVm().getPartialVersion()); messages.add("$serverVersion " + vdsVersion.getRpmName()); } } log.info(sb.toString()); return false; }

Target:
private boolean CanFindVdsToRun(List<String> messages, boolean isMigrate, Iterable<VDS> vdss) { VdcBllMessages messageToReturn = VdcBllMessages.Unassigned; RpmVersion vdsVersion = null; boolean noVDSs = true; StringBuilder sb = new StringBuilder(); for (VDS curVds : vdss) { if (isMigrate && getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) { continue; } noVDSs = false; ValidationResult result = validateHostIsReadyToRun(curVds, sb); if (result.isValid()) { return true; } else { if (messageToReturn.getValue() < result.getMessage().getValue()) { messageToReturn = result.getMessage(); vdsVersion = curVds.getVersion(); } } } if (noVDSs) { if (messages != null) { messageToReturn = VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_AVAILABLE_IN_CLUSTER; } } if (messages != null) { messages.add(messageToReturn.toString()); if (messageToReturn == VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_VERSION && vdsVersion != null) { VmHandler.UpdateVmGuestAgentVersion(getVm()); messages.add("$toolsVersion " + getVm().getPartialVersion()); messages.add("$serverVersion " + vdsVersion.getRpmName()); } } log.info(sb.toString()); return false; }