auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isMine() { IRepository repos = getReview() != null ? getReview().getRepository() : null; return getAuthor() != null && repos != null && (repos.getAccount() == getAuthor() || (repos.getAccount() != null && (repos.getAccount().getEmail().equals(getAuthor().getEmail())))); }

Target:
public boolean isMine() { IRepository repos = getReview() != null ? getReview().getRepository() : null; return getAuthor() != null && repos != null && (repos.getAccount() == getAuthor() || (repos.getAccount() != null && repos.getAccount().getEmail().equals(getAuthor().getEmail()))); }
Source:
public void setPageLayout(Artifact artifact, String footerMl) throws OseeCoreException { String pageTypeValue = null; if (artifact.isAttributeTypeValid(CoreAttributeTypes.PageType)) { pageTypeValue = artifact.getSoleAttributeValue(CoreAttributeTypes.PageType, "Portrait"); } boolean landscape = pageTypeValue != null && pageTypeValue.equals("Landscape"); if (landscape) { append("<w:p>"); append("<w:pPr>"); append("<w:sectPr>"); append(footerMl); append("<w:pgSz w:w=\"15840\" w:h=\"12240\" w:orient=\"landscape\" w:code=\"1\" />"); append("</w:sectPr>"); append("</w:pPr>"); append("</w:p>"); } }

Target:
public void setPageLayout(Artifact artifact, String footerMl) throws OseeCoreException { String pageTypeValue = null; if (artifact.isAttributeTypeValid(CoreAttributeTypes.PageType)) { pageTypeValue = artifact.getSoleAttributeValue(CoreAttributeTypes.PageType, "Portrait"); } boolean landscape = pageTypeValue != null && pageTypeValue.equals("Landscape"); if (landscape) { append("<w:p>"); append("<w:pPr>"); append("<w:sectPr>"); if (Strings.isValid(footerMl)) { append(footerMl); } append("<w:pgSz w:w=\"15840\" w:h=\"12240\" w:orient=\"landscape\" w:code=\"1\" />"); append("</w:sectPr>"); append("</w:pPr>"); append("</w:p>"); } }
Source:
public void migrateExternalIdentifierFromSingularToSubstudyAssociation() throws Exception { when(substudyService.getSubstudy(TestConstants.TEST_STUDY, ID, true)) .thenReturn(Substudy.create()); ExternalIdentifier extId = ExternalIdentifier.create(TestConstants.TEST_STUDY, ID); when(externalIdDao.getExternalId(TestConstants.TEST_STUDY, ID)) .thenReturn(extId); Account account = Account.create(); account.setId(USER_ID); account.setExternalId(ID); AccountId accountId = AccountId.forExternalId(TestConstants.TEST_STUDY_IDENTIFIER, ID); when(accountDao.getAccount(accountId)).thenReturn(account); externalIdService.migrateExternalIdentifier(study, ID, SUBSTUDY_ID); assertEquals(SUBSTUDY_ID, extId.getSubstudyId()); assertEquals(1, account.getAccountSubstudies().size()); assertEquals(ID, account.getExternalId()); AccountSubstudy acctSubstudy = Iterables.getFirst(account.getAccountSubstudies(), null); assertEquals(TestConstants.TEST_STUDY_IDENTIFIER, acctSubstudy.getStudyId()); assertEquals(ID, acctSubstudy.getExternalId()); assertEquals(SUBSTUDY_ID, acctSubstudy.getSubstudyId()); verify(externalIdDao).createExternalId(extId); verify(accountDao).updateAccount(account, null); }

Target:
public void migrateExternalIdentifierFromSingularToSubstudyAssociation() throws Exception { when(substudyService.getSubstudy(TestConstants.TEST_STUDY, ID, true)) .thenReturn(Substudy.create()); ExternalIdentifier extId = ExternalIdentifier.create(TestConstants.TEST_STUDY, ID); when(externalIdDao.getExternalId(TestConstants.TEST_STUDY, ID)) .thenReturn(extId); Account account = Account.create(); account.setId(USER_ID); account.setExternalId("differentExternalId"); AccountId accountId = AccountId.forExternalId(TestConstants.TEST_STUDY_IDENTIFIER, ID); when(accountDao.getAccount(accountId)).thenReturn(account); externalIdService.migrateExternalIdentifier(study, ID, SUBSTUDY_ID); assertEquals(SUBSTUDY_ID, extId.getSubstudyId()); assertEquals(1, account.getAccountSubstudies().size()); assertEquals(ID, account.getExternalId()); AccountSubstudy acctSubstudy = Iterables.getFirst(account.getAccountSubstudies(), null); assertEquals(TestConstants.TEST_STUDY_IDENTIFIER, acctSubstudy.getStudyId()); assertEquals(ID, acctSubstudy.getExternalId()); assertEquals(SUBSTUDY_ID, acctSubstudy.getSubstudyId()); verify(externalIdDao).createExternalId(extId); verify(accountDao).updateAccount(account, null); }
Source:
public static double kgToLb(double kg) { return kg * 2.20462; }

Target:
public static double kgToLb(double kg) { return kg * KG_TO_LB_CONSTANT; }
Source:
void checkRamResourcesAvailability( String accountId, String namespace, String workspaceId, WorkspaceConfig config, @Nullable String envName) throws NotFoundException, ServerException, ConflictException { if (config.getEnvironments().isEmpty()) { return; } if (SidecarToolingWorkspaceUtil.isSidecarBasedWorkspace(config.getAttributes())) { LOG.warn( "Sidecar memory of plugins of workspace `{}` is not taken in account. " + "Set memory resources limits may work incorrectly", workspaceId); } final Environment environment = config.getEnvironments().get(firstNonNull(envName, config.getDefaultEnv())); final ResourceImpl ramToUse = new ResourceImpl( RamResourceType.ID, environmentRamCalculator.calculate(environment), RamResourceType.UNIT); try { resourceManager.checkResourcesAvailability(accountId, singletonList(ramToUse)); } catch (NoEnoughResourcesException e) { final Resource requiredRam = e.getRequiredResources().get(0); final Resource availableRam = getResourceOrDefault( e.getAvailableResources(), RamResourceType.ID, 0, RamResourceType.UNIT); final Resource usedRam = getResourceOrDefault( resourceManager.getUsedResources(accountId), RamResourceType.ID, 0, RamResourceType.UNIT); throw new LimitExceededException( format( "Workspace %s/%s needs %s to start. Your account has %s available and %s in use. " + "The workspace can't be start. Stop other workspaces or grant more resources.", namespace, config.getName(), printResourceInfo(requiredRam), printResourceInfo(availableRam), printResourceInfo(usedRam))); } }

Target:
void checkRamResourcesAvailability( String accountId, String namespace, String workspaceId, WorkspaceConfig config, @Nullable String envName) throws NotFoundException, ServerException, ConflictException { if (config.getEnvironments().isEmpty()) { return; } if (SidecarToolingWorkspaceUtil.isSidecarBasedWorkspace(config.getAttributes())) { LOG.warn( "The memory requirements for the plugin sidecars of workspace `{}` are not taken" + " into account. The memory limits may not be applied correctly.", workspaceId); } final Environment environment = config.getEnvironments().get(firstNonNull(envName, config.getDefaultEnv())); final ResourceImpl ramToUse = new ResourceImpl( RamResourceType.ID, environmentRamCalculator.calculate(environment), RamResourceType.UNIT); try { resourceManager.checkResourcesAvailability(accountId, singletonList(ramToUse)); } catch (NoEnoughResourcesException e) { final Resource requiredRam = e.getRequiredResources().get(0); final Resource availableRam = getResourceOrDefault( e.getAvailableResources(), RamResourceType.ID, 0, RamResourceType.UNIT); final Resource usedRam = getResourceOrDefault( resourceManager.getUsedResources(accountId), RamResourceType.ID, 0, RamResourceType.UNIT); throw new LimitExceededException( format( "Workspace %s/%s needs %s to start. Your account has %s available and %s in use. " + "The workspace can't be start. Stop other workspaces or grant more resources.", namespace, config.getName(), printResourceInfo(requiredRam), printResourceInfo(availableRam), printResourceInfo(usedRam))); } }
Source:
private static boolean isShutdownHookNeeded() { String property = AccessController.doPrivileged(new GetSystemPropertyAction(Weld.SHUTDOWN_HOOK_SYSTEM_PROPERTY)); return property == null || Boolean.FALSE.equals(Boolean.valueOf(property)); }

Target:
private static boolean isShutdownHookNeeded() { String property = AccessController.doPrivileged(new GetSystemPropertyAction(Weld.SHUTDOWN_HOOK_SYSTEM_PROPERTY)); return property == null || Boolean.TRUE.equals(Boolean.valueOf(property)); }
Source:
public void updateEntity() { super.updateEntity(); if (mjStored > 0) { ForgeDirection dir = getOpenOrientation(); if (dir != ForgeDirection.UNKNOWN) { Position loc = getPosition().shift(dir); Block block = loc.getBlock(getWorld()); float h = block.getBlockHardness(getWorld(), (int) loc.x, (int) loc.y, (int) loc.z); if (loc.blockExists(getWorld()) && h > 0.0F && h < 100.0F) { IStripesHandler handler = new DefaultHandler(); Item blockItem = Item.getItemFromBlock(block); if (PipeManager.stripesHandlers.containsKey(blockItem)) { handler = PipeManager.stripesHandlers.get(blockItem); } else if (blockItem instanceof IStripesHandler) { handler = (IStripesHandler) blockItem; } else if (block instanceof IStripesHandler) { handler = (IStripesHandler) block; } if (handler.behave(this, StripesAction.DESTROY, new ItemStack(block, 0, loc.getMeta(getWorld()))) == StripesBehavior.DEFAULT) { List<ItemStack> drops = block.getDrops(getWorld(), (int) loc.x, (int) loc.y, (int) loc.z, loc.getMeta(getWorld()), 0); loc.destroyBlock(getWorld(), false); for (ItemStack drop : drops) { if (drop != null) { sendItem(drop, dir.getOpposite()); } } } } } } mjStored = 0; }

Target:
public void updateEntity() { super.updateEntity(); if (!getWorld().isRemote && mjStored > 0) { ForgeDirection dir = getOpenOrientation(); if (dir != ForgeDirection.UNKNOWN) { Position loc = getPosition().shift(dir); Block block = loc.getBlock(getWorld()); float h = block.getBlockHardness(getWorld(), (int) loc.x, (int) loc.y, (int) loc.z); if (loc.blockExists(getWorld()) && h > 0.0F && h < 100.0F) { IStripesHandler handler = new DefaultHandler(); Item blockItem = Item.getItemFromBlock(block); if (PipeManager.stripesHandlers.containsKey(blockItem)) { handler = PipeManager.stripesHandlers.get(blockItem); } else if (blockItem instanceof IStripesHandler) { handler = (IStripesHandler) blockItem; } else if (block instanceof IStripesHandler) { handler = (IStripesHandler) block; } if (handler.behave(this, StripesAction.DESTROY, new ItemStack(block, 0, loc.getMeta(getWorld()))) == StripesBehavior.DEFAULT) { List<ItemStack> drops = block.getDrops(getWorld(), (int) loc.x, (int) loc.y, (int) loc.z, loc.getMeta(getWorld()), 0); loc.destroyBlock(getWorld(), false); for (ItemStack drop : drops) { if (drop != null) { sendItem(drop, dir.getOpposite()); } } } } } mjStored = 0; } }
Source:
protected void updateNotPropagatedHeaders(String[] headers, boolean merge) { Set<String> headerPatterns = new HashSet<>(); if (merge && this.notPropagatedHeaders != null) { headerPatterns.addAll(Arrays.asList(this.notPropagatedHeaders)); } if (!ObjectUtils.isEmpty(headers)) { Assert.noNullElements(headers, "null elements are not allowed in 'headers'"); headerPatterns.addAll(Arrays.asList(headers)); this.notPropagatedHeaders = headerPatterns.toArray(new String[0]); } boolean hasAsterisk = headerPatterns.contains("*"); if (hasAsterisk) { this.notPropagatedHeaders = new String[] { "*" }; this.noHeadersPropagation = true; } this.selectiveHeaderPropagation = !ObjectUtils.isEmpty(this.notPropagatedHeaders); }

Target:
protected final void updateNotPropagatedHeaders(String[] headers, boolean merge) { Set<String> headerPatterns = new HashSet<>(); if (merge && this.notPropagatedHeaders != null) { headerPatterns.addAll(Arrays.asList(this.notPropagatedHeaders)); } if (!ObjectUtils.isEmpty(headers)) { Assert.noNullElements(headers, "null elements are not allowed in 'headers'"); headerPatterns.addAll(Arrays.asList(headers)); this.notPropagatedHeaders = headerPatterns.toArray(new String[0]); } boolean hasAsterisk = headerPatterns.contains("*"); if (hasAsterisk) { this.notPropagatedHeaders = new String[] { "*" }; this.noHeadersPropagation = true; } this.selectiveHeaderPropagation = !ObjectUtils.isEmpty(this.notPropagatedHeaders); }
Source:
void addContent() { final List<Customer> customers = new ArrayList<Customer>(); customers.add(Customer.builder().name("Artem").surname("Zinnatullin").city("SF").build()); customers.add(Customer.builder().name("Elon").surname("Musk").city("Boring").build()); customers.add(Customer.builder().name("Jake").surname("Wharton").city("Pittsburgh").build()); List<ContentValues> contentValues = new ArrayList<ContentValues>(customers.size()); for (Customer customer : customers) { contentValues.add(Customer.FACTORY.marshal(customer).asContentValues()); } storIOSQLite .put() .contentValues(contentValues) .withPutResolver(Customer.CV_PUT_RESOLVER) .prepare() .asRxCompletable() .observeOn(mainThread()) .subscribe( new Action0() { @Override public void call() { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { safeShowShortToast(SqlDelightActivity.this, R.string.common_error); } }); }

Target:
void addContent() { final List<Customer> customers = new ArrayList<Customer>(); customers.add(Customer.builder().name("Elon").surname("Musk").city("Boring").build()); customers.add(Customer.builder().name("Jake").surname("Wharton").city("Pittsburgh").build()); List<ContentValues> contentValues = new ArrayList<ContentValues>(customers.size()); for (Customer customer : customers) { contentValues.add(Customer.FACTORY.marshal(customer).asContentValues()); } storIOSQLite .put() .contentValues(contentValues) .withPutResolver(Customer.CV_PUT_RESOLVER) .prepare() .asRxCompletable() .observeOn(mainThread()) .subscribe( new Action0() { @Override public void call() { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { safeShowShortToast(SqlDelightActivity.this, R.string.common_error); } }); }
Source:
public void open() throws Exception { super.open(); bais = new ByteArrayInputStreamWithPos(); baisWrapper = new DataInputViewStreamWrapper(bais); baos = new ByteArrayOutputStreamWithPos(); baosWrapper = new DataOutputViewStreamWrapper(baos); keyTypeSerializer = PythonTypeUtils.TypeInfoToSerializerConverter.typeInfoSerializerConverter(keyTypeInfo); runnerInputSerializer = PythonTypeUtils.TypeInfoToSerializerConverter .typeInfoSerializerConverter(runnerInputTypeInfo); runnerOutputSerializer = PythonTypeUtils.TypeInfoToSerializerConverter .typeInfoSerializerConverter(runnerOutputTypeInfo); InternalTimerService<VoidNamespace> internalTimerService = getInternalTimerService("user-timers", VoidNamespaceSerializer.INSTANCE, this); this.streamRecordCollector = new StreamRecordCollector(output); timerservice = new SimpleTimerService(internalTimerService); reusableInput = new Row(5); reusableTimerData = new Row(5); }

Target:
public void open() throws Exception { super.open(); bais = new ByteArrayInputStreamWithPos(); baisWrapper = new DataInputViewStreamWrapper(bais); baos = new ByteArrayOutputStreamWithPos(); baosWrapper = new DataOutputViewStreamWrapper(baos); keyTypeSerializer = PythonTypeUtils.TypeInfoToSerializerConverter.typeInfoSerializerConverter(keyTypeInfo); runnerInputSerializer = PythonTypeUtils.TypeInfoToSerializerConverter .typeInfoSerializerConverter(runnerInputTypeInfo); runnerOutputSerializer = PythonTypeUtils.TypeInfoToSerializerConverter .typeInfoSerializerConverter(runnerOutputTypeInfo); InternalTimerService<VoidNamespace> internalTimerService = getInternalTimerService("user-timers", VoidNamespaceSerializer.INSTANCE, this); streamRecordCollector = new StreamRecordCollector(output); timerservice = new SimpleTimerService(internalTimerService); reusableInput = new Row(5); reusableTimerData = new Row(5); }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_auth_method_picker_layout); FlowParameters params = getFlowParams(); mHandler = ViewModelProviders.of(this).get(SocialProviderResponseHandler.class); mHandler.init(params); populateIdpList(params.providerInfo, mHandler); int logoId = params.logoId; if (logoId == AuthUI.NO_LOGO) { findViewById(R.id.logo).setVisibility(View.GONE); ConstraintLayout layout = findViewById(R.id.root); ConstraintSet constraints = new ConstraintSet(); constraints.clone(layout); constraints.setHorizontalBias(R.id.container, 0.5f); constraints.setVerticalBias(R.id.container, 0.5f); constraints.applyTo(layout); } else { ImageView logo = findViewById(R.id.logo); logo.setImageResource(logoId); } mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_in) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials(mHandler.getCurrentUser(), response, null); } @Override protected void onFailure(@NonNull Exception e) { if (!(e instanceof UserCancellationException)) { Toast.makeText(AuthMethodPickerActivity.this, R.string.fui_error_unknown, Toast.LENGTH_SHORT).show(); } } }); TextView termsText = findViewById(R.id.main_tos_and_pp); PrivacyDisclosureUtils.setupTermsOfServiceAndPrivacyPolicyText(AuthMethodPickerActivity.this, getFlowParams(), termsText); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_auth_method_picker_layout); FlowParameters params = getFlowParams(); mHandler = ViewModelProviders.of(this).get(SocialProviderResponseHandler.class); mHandler.init(params); populateIdpList(params.providerInfo, mHandler); int logoId = params.logoId; if (logoId == AuthUI.NO_LOGO) { findViewById(R.id.logo).setVisibility(View.GONE); ConstraintLayout layout = findViewById(R.id.root); ConstraintSet constraints = new ConstraintSet(); constraints.clone(layout); constraints.setHorizontalBias(R.id.container, 0.5f); constraints.setVerticalBias(R.id.container, 0.5f); constraints.applyTo(layout); } else { ImageView logo = findViewById(R.id.logo); logo.setImageResource(logoId); } mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_in) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials(mHandler.getCurrentUser(), response, null); } @Override protected void onFailure(@NonNull Exception e) { if (!(e instanceof UserCancellationException)) { Toast.makeText(AuthMethodPickerActivity.this, R.string.fui_error_unknown, Toast.LENGTH_SHORT).show(); } } }); TextView termsText = findViewById(R.id.main_tos_and_pp); PrivacyDisclosureUtils.setupTermsOfServiceAndPrivacyPolicyText(this, getFlowParams(), termsText); }
Source:
public Double getMinRowCount(Union rel, RelMetadataQuery mq) { if (rel.all) { double rowCount = 0.0; for (RelNode input : rel.getInputs()) { Double partialRowCount = mq.getMinRowCount(input); if (partialRowCount != null) { rowCount += partialRowCount; } } return rowCount; } else { boolean valid = false; double rowCount = Double.POSITIVE_INFINITY; for (RelNode input : rel.getInputs()) { Double partialRowCount = mq.getMinRowCount(input); if (partialRowCount != null && rowCount > partialRowCount) { rowCount = partialRowCount; valid = true; } } if (!valid) { rowCount = 0.0; } return rowCount; } }

Target:
public Double getMinRowCount(Union rel, RelMetadataQuery mq) { double rowCount = 0.0; for (RelNode input : rel.getInputs()) { Double partialRowCount = mq.getMinRowCount(input); if (partialRowCount != null) { rowCount += partialRowCount; } } if (rel.all) { return rowCount; } else { return Math.min(rowCount, 1d); } }
Source:
public String getScript(String inMoovServiceName) { return String.format((Locale)null,"%s.moveHead(%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, neck.getPos(), rothead.getPos(), eyeX.getPos(), eyeY.getPos(), jaw.getPos(), rollNeck.getPos()); }

Target:
public String getScript(String inMoovServiceName) { return String.format(Locale.ENGLISH,"%s.moveHead(%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, neck.getPos(), rothead.getPos(), eyeX.getPos(), eyeY.getPos(), jaw.getPos(), rollNeck.getPos()); }
Source:
public JSReference getProxy(String endpointName, String moduleId) { Endpoint e = this; String proxyModuleId = new String(moduleId); Proxy proxy = null; if(!endpointName.equals(this.getName())){ e = EndpointFactory.getEndpointUnchecked(endpointName); } try { proxy = ProxyFactory.getProxyConfig(e.getProxyConfig()); if(proxy != null && proxy.getProxyModule() != null){ proxyModuleId = proxy.getProxyModule(); } } catch (ProxyConfigException ex) { String thisClass = AbstractEndpoint.class.getName(); Logger logger = Logger.getLogger(thisClass); if (logger.isLoggable(Level.SEVERE)) { logger.entering(thisClass, "createProxyRef failed", ex.getMessage()); } } return new JSReference(proxyModuleId); }

Target:
public JSReference getProxy(String endpointName, String moduleId) { String proxyModuleId = moduleId; Proxy proxy = null; if(this.getProxyConfig() != null){ try { proxy = ProxyFactory.getProxyConfig(this.getProxyConfig()); if(proxy != null && proxy.getProxyModule() != null){ proxyModuleId = proxy.getProxyModule(); } } catch (ProxyConfigException ex) { Logger logger = Logger.getLogger(AbstractEndpoint.class.getName()); if (logger.isLoggable(Level.SEVERE)) { logger.severe(ex.getMessage()); } } } return new JSReference(proxyModuleId); }
Source:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { sco = null; } }

Target:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; columnsRead.clear(); } }
Source:
public static URL getOpenInOseeLink(final Artifact artifact, String cmd, PresentationType presentationType) { Map<String, String> parameters = new HashMap<>(); parameters.put("sessionId", ClientSessionManager.getSessionId()); parameters.put("context", "osee/loopback"); parameters.put("id", artifact.getIdString()); parameters.put("branchUuid", artifact.getBranch().getIdString()); parameters.put("isDeleted", String.valueOf(artifact.isDeleted())); if (artifact.isHistorical() && presentationType != PresentationType.DIFF && presentationType != PresentationType.F5_DIFF) { parameters.put("transactionId", String.valueOf(artifact.getTransaction())); } parameters.put("cmd", cmd); String urlString = getPermanentLinkBaseUrl(OseeServerContext.CLIENT_LOOPBACK_CONTEXT, parameters); URL url = null; try { url = new URL(urlString); } catch (Exception ex) { OseeCoreException.wrapAndThrow(ex); } return url; }

Target:
public static URL getOpenInOseeLink(final Artifact artifact, String cmd, PresentationType presentationType) { Map<String, String> parameters = new HashMap<>(); parameters.put("sessionId", ClientSessionManager.getSessionId()); parameters.put("context", "osee/loopback"); parameters.put("id", artifact.getIdString()); parameters.put("guid", artifact.getGuid()); parameters.put("branchUuid", artifact.getBranch().getIdString()); parameters.put("isDeleted", String.valueOf(artifact.isDeleted())); if (artifact.isHistorical() && presentationType != PresentationType.DIFF && presentationType != PresentationType.F5_DIFF) { parameters.put("transactionId", String.valueOf(artifact.getTransaction())); } parameters.put("cmd", cmd); String urlString = getPermanentLinkBaseUrl(OseeServerContext.CLIENT_LOOPBACK_CONTEXT, parameters); URL url = null; try { url = new URL(urlString); } catch (Exception ex) { OseeCoreException.wrapAndThrow(ex); } return url; }
Source:
public void restart() throws IOException, InterruptedException { Jenkins jenkins = Jenkins.getInstanceOrNull(); try { if (jenkins != null) { jenkins.cleanUp(); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failed to clean up. Restart will continue.", e); } int sz = LIBC.getdtablesize(); for(int i=3; i<sz; i++) { int flags = LIBC.fcntl(i, F_GETFD); if(flags<0) continue; LIBC.fcntl(i, F_SETFD,flags| FD_CLOEXEC); } if (EXIT_ON_RESTART == null) { String exe = args.get(0); LIBC.execvp(exe, new StringArray(args.toArray(new String[args.size()]))); throw new IOException("Failed to exec '"+exe+"' "+LIBC.strerror(Native.getLastError())); } else { System.exit(Integer.parseInt(EXIT_ON_RESTART)); } }

Target:
public void restart() throws IOException, InterruptedException { Jenkins jenkins = Jenkins.getInstanceOrNull(); try { if (jenkins != null) { jenkins.cleanUp(); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failed to clean up. Restart will continue.", e); } int sz = LIBC.getdtablesize(); for(int i=3; i<sz; i++) { int flags = LIBC.fcntl(i, F_GETFD); if(flags<0) continue; LIBC.fcntl(i, F_SETFD,flags| FD_CLOEXEC); } String exe = args.get(0); LIBC.execvp(exe, new StringArray(args.toArray(new String[args.size()]))); throw new IOException("Failed to exec '"+exe+"' "+LIBC.strerror(Native.getLastError())); }
Source:
public static JobValidationData validateJob(String jobFilePath, Map<String, String> jobVariables, Scheduler scheduler, SchedulerSpaceInterface space) { JobValidationData data = new JobValidationData(); Job job = null; try { JobFactory factory = JobFactory.getFactory(); job = factory.createJob(jobFilePath, jobVariables, null, scheduler, space); if (job instanceof TaskFlowJob) { validateJob((TaskFlowJob) job, data); fillUpdatedVariables((TaskFlowJob) job, data); } else { data.setValid(true); } } catch (JobCreationException e) { data.setTaskName(e.getTaskName()); data.setErrorMessage(e.getMessage()); data.setStackTrace(getStackTrace(e)); if (job != null && job instanceof TaskFlowJob) { fillUpdatedVariables((TaskFlowJob) job, data); } } return data; }

Target:
public static JobValidationData validateJob(String jobFilePath, Map<String, String> jobVariables, Scheduler scheduler, SchedulerSpaceInterface space) { JobValidationData data = new JobValidationData(); Job job = null; try { JobFactory factory = JobFactory.getFactory(); job = factory.createJob(jobFilePath, jobVariables, null, scheduler, space); if (job instanceof TaskFlowJob) { validateJob((TaskFlowJob) job, data); } else { data.setValid(true); } } catch (JobCreationException e) { data.setTaskName(e.getTaskName()); data.setErrorMessage(e.getMessage()); data.setStackTrace(getStackTrace(e)); } finally { if (job != null && job instanceof TaskFlowJob) { fillUpdatedVariables((TaskFlowJob) job, data); } } return data; }
Source:
public Monitor getMonitor(URL url) { url = url.setPath(MonitorService.class.getName()).addParameter(Constants.INTERFACE_KEY, MonitorService.class.getName()); String key = url.toServiceStringWithoutResolving(); Monitor monitor = MONITORS.get(key); Future<Monitor> future = FUTURES.get(key); if (monitor != null || future != null) { return monitor; } LOCK.lock(); try { monitor = MONITORS.get(key); future = FUTURES.get(key); if (monitor != null || future != null) { return monitor; } final URL monitorUrl = url; final CompletableFuture<Monitor> completableFuture = CompletableFuture.supplyAsync(()->{ Monitor newMonitor = AbstractMonitorFactory.this.createMonitor(monitorUrl); return newMonitor; },executor); completableFuture.thenRunAsync(new MonitorListener(key)); FUTURES.put(key, completableFuture); return null; } finally { LOCK.unlock(); } }

Target:
public Monitor getMonitor(URL url) { url = url.setPath(MonitorService.class.getName()).addParameter(Constants.INTERFACE_KEY, MonitorService.class.getName()); String key = url.toServiceStringWithoutResolving(); Monitor monitor = MONITORS.get(key); Future<Monitor> future = FUTURES.get(key); if (monitor != null || future != null) { return monitor; } LOCK.lock(); try { monitor = MONITORS.get(key); future = FUTURES.get(key); if (monitor != null || future != null) { return monitor; } final URL monitorUrl = url; final CompletableFuture<Monitor> completableFuture = CompletableFuture.supplyAsync(() -> AbstractMonitorFactory.this.createMonitor(monitorUrl)); completableFuture.thenRunAsync(new MonitorListener(key), executor); FUTURES.put(key, completableFuture); return null; } finally { LOCK.unlock(); } }
Source:
public Collection readObject(ObjectInput input) throws IOException, ClassNotFoundException { int magicNumber = input.readUnsignedByte(); switch (magicNumber) { case ARRAY_LIST: return MarshallUtil.unmarshallCollection(input, ArrayList::new); case LINKED_LIST: return MarshallUtil.unmarshallCollection(input, s -> new LinkedList<>()); case SINGLETON_LIST: return Collections.singletonList(input.readObject()); case EMPTY_LIST: return Collections.emptyList(); case HASH_SET: return MarshallUtil.unmarshallCollection(input, s -> new HashSet<>()); case TREE_SET: Comparator<Object> comparator = (Comparator<Object>) input.readObject(); return MarshallUtil.unmarshallCollection(input, s -> new TreeSet<>(comparator)); case SINGLETON_SET: return Collections.singleton(input.readObject()); case SYNCHRONIZED_SET: return Collections.synchronizedSet( MarshallUtil.unmarshallCollection(input, s -> new HashSet<>())); case ARRAY_DEQUE: return MarshallUtil.unmarshallCollection(input, ArrayDeque::new); case READ_ONLY_SEGMENT_AWARE_COLLECTION: return MarshallUtil.unmarshallCollection(input, ArrayList::new); default: throw new IllegalStateException("Unknown Set type: " + magicNumber); } }

Target:
public Collection readObject(ObjectInput input) throws IOException, ClassNotFoundException { int magicNumber = input.readUnsignedByte(); switch (magicNumber) { case ARRAY_LIST: return MarshallUtil.unmarshallCollection(input, ArrayList::new); case LINKED_LIST: return MarshallUtil.unmarshallCollectionUnbounded(input, LinkedList::new); case SINGLETON_LIST: return Collections.singletonList(input.readObject()); case EMPTY_LIST: return Collections.emptyList(); case HASH_SET: return MarshallUtil.unmarshallCollection(input, s -> new HashSet<>()); case TREE_SET: Comparator<Object> comparator = (Comparator<Object>) input.readObject(); return MarshallUtil.unmarshallCollection(input, s -> new TreeSet<>(comparator)); case SINGLETON_SET: return Collections.singleton(input.readObject()); case SYNCHRONIZED_SET: return Collections.synchronizedSet( MarshallUtil.unmarshallCollection(input, s -> new HashSet<>())); case ARRAY_DEQUE: return MarshallUtil.unmarshallCollection(input, ArrayDeque::new); case READ_ONLY_SEGMENT_AWARE_COLLECTION: return MarshallUtil.unmarshallCollection(input, ArrayList::new); default: throw new IllegalStateException("Unknown Set type: " + magicNumber); } }
Source:
private void prepareMariaDB() throws IllegalStateException { boolean initDbSuccess = false; int i = 0; while (i < 3) { try { db = DB.newEmbeddedDB(DBConfigurationBuilder.newBuilder().build()); db.start(); dbUrl = db.getConfiguration().getURL(DEFAULT_DB_NAME); connection = DriverManager.getConnection(dbUrl); try (Statement statement = connection.createStatement()) { statement.execute("CREATE DATABASE IF NOT EXISTS `" + DEFAULT_DB_NAME + "`;"); ResultSet resultSet = statement.executeQuery("SELECT SCHEMA_NAME FROM " + "INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + DEFAULT_DB_NAME + "';"); if (resultSet.next()) { String dbName = resultSet.getString(1); initDbSuccess = DEFAULT_DB_NAME.equalsIgnoreCase(dbName); } } } catch (Exception e) { log.info("Initialize DB fail caused by {}", e); } if (initDbSuccess) { break; } i++; } if (!initDbSuccess) { throw new IllegalStateException("Initialize MySQL database instance failed after 3 attempts," + " please open an issue."); } }

Target:
public static void prepareMariaDB() throws IllegalStateException { boolean initDbSuccess = false; int i = 0; while (i < INITIALIZE_DB_MAX_RETRY) { try { db = DB.newEmbeddedDB(DBConfigurationBuilder.newBuilder().build()); db.start(); dbUrl = db.getConfiguration().getURL(DEFAULT_DB_NAME); connection = DriverManager.getConnection(dbUrl); try (Statement statement = connection.createStatement()) { statement.execute("CREATE DATABASE IF NOT EXISTS `" + DEFAULT_DB_NAME + "`;"); ResultSet resultSet = statement.executeQuery("SELECT SCHEMA_NAME FROM " + "INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + DEFAULT_DB_NAME + "';"); if (resultSet.next()) { String dbName = resultSet.getString(1); initDbSuccess = DEFAULT_DB_NAME.equalsIgnoreCase(dbName); } } } catch (Exception e) { logger.warn("Initialize DB fail caused by {}", e); stopDb(); } if (initDbSuccess) { break; } i++; } if (!initDbSuccess) { throw new IllegalStateException(String.format("Initialize MySQL database instance failed after attempts," + " please open an issue.", INITIALIZE_DB_MAX_RETRY)); } }
Source:
public ValueHolder<V> get(final K key) throws CacheAccessException { try { final ValueHolder<V> valueHolder = cachingTier.getOrComputeIfAbsent(key, new Function<K, ValueHolder<V>>() { @Override public ValueHolder<V> apply(K key) { try { return authoritativeTier.getAndFault(key); } catch (CacheAccessException cae) { throw new ComputationException(cae); } } }); if(valueHolder != null && valueHolder.isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS)) { authoritativeTier.flush(key, valueHolder); return null; } return valueHolder; } catch (ComputationException ce) { throw ce.getCacheAccessException(); } }

Target:
public ValueHolder<V> get(final K key) throws CacheAccessException { try { final ValueHolder<V> valueHolder = cachingTier.getOrComputeIfAbsent(key, new Function<K, ValueHolder<V>>() { @Override public ValueHolder<V> apply(K key) { try { return authoritativeTier.getAndFault(key); } catch (CacheAccessException cae) { throw new ComputationException(cae); } } }); return valueHolder; } catch (ComputationException ce) { throw ce.getCacheAccessException(); } }
Source:
public <T> void post(TypeReference<T> typeReference, ResultCallback<T> resultCallback, InputStream body) { HttpRequestProvider requestProvider = httpPostRequestProvider(null); Channel channel = getChannel(); HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback); channel.pipeline().addLast(new ChunkedWriteHandler()); channel.pipeline().addLast(responseHandler); if (!Void.class.equals(typeReference.getType())) { JsonResponseCallbackHandler<T> jsonResponseHandler = new JsonResponseCallbackHandler<T>(typeReference, resultCallback); channel.pipeline().addLast(new JsonObjectDecoder()); channel.pipeline().addLast(jsonResponseHandler); } HttpRequest request = requestProvider.getHttpRequest(resource); if (request instanceof FullHttpRequest) { throw new DockerClientException("fatal: request is instance of FullHttpRequest"); } request.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); request.headers().remove(HttpHeaderNames.CONTENT_LENGTH); channel.write(request); channel.write(new ChunkedStream(new BufferedInputStream(body, 1024 * 1024), 1024 * 1024)); channel.write(LastHttpContent.EMPTY_LAST_CONTENT); channel.flush(); }

Target:
public <T> void post(TypeReference<T> typeReference, ResultCallback<T> resultCallback, InputStream body) { HttpRequestProvider requestProvider = httpPostRequestProvider(null); Channel channel = getChannel(); JsonResponseCallbackHandler<T> jsonResponseHandler = new JsonResponseCallbackHandler<T>(typeReference, resultCallback); HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback); channel.pipeline().addLast(new ChunkedWriteHandler()); channel.pipeline().addLast(responseHandler); channel.pipeline().addLast(new JsonObjectDecoder()); channel.pipeline().addLast(jsonResponseHandler); postChunkedStreamRequest(requestProvider, channel, body); }
Source:
@Test public void shouldOpenCompareEditorInGitChangeSet() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare1"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare1"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotTree syncViewTree = bot.viewByTitle("Synchronize").bot().tree(); syncViewTree.getTreeItem("<working tree>"); syncViewTree.getAllItems()[0].collapse().doubleClick(); syncViewTree.getAllItems()[0].getItems()[0].getNode(FOLDER) .getNode(FILE1).doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }

Target:
@Test public void shouldOpenCompareEditorInGitChangeSet() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare1"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare1"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotTree syncViewTree = bot.viewByTitle("Synchronize").bot().tree(); syncViewTree.getTreeItem(UIText.GitModelWorkingTree_workingTree); syncViewTree.getAllItems()[0].collapse().doubleClick(); syncViewTree.getAllItems()[0].getItems()[0].getNode(FOLDER) .getNode(FILE1).doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }
Source:
public void mapClick(final double lat, final double lng) { Log.d(TAG, "mapClick - " + lat + ", " + lng); handler.post(new Runnable() { @Override public void run() { if (mOnMapClickListener != null) { mOnMapClickListener.onMapClick(new LatLng(lat, lng)); } if (mInfoWindowView != null) { mLayout.removeView(mInfoWindowView); } } }); }

Target:
public void mapClick(final double lat, final double lng) { handler.post(new Runnable() { @Override public void run() { if (mOnMapClickListener != null) { mOnMapClickListener.onMapClick(new LatLng(lat, lng)); } if (mInfoWindowView != null) { mLayout.removeView(mInfoWindowView); } } }); }
Source:
public static void main(String[] args) { ArgsHolder.init(args, ArgsHolder.ArgType.SLAVE); RestartHelper.init(); if (ArgsHolder.getMasterHost() == null) { ArgsHolder.printUsageAndExit(ArgsHolder.ArgType.SLAVE); } Slave slave = new Slave(new RemoteMasterConnection(ArgsHolder.getMasterHost(), ArgsHolder.getMasterPort())); try { slave.run(ArgsHolder.getSlaveIndex()); } catch (IOException e) { System.err.println("Communication with master failed"); e.printStackTrace(); ShutDownHook.exit(127); } catch (Exception e) { System.err.println("Unexpected error in scenario"); e.printStackTrace(); ShutDownHook.exit(127); } }

Target:
public static void main(String[] args) { ArgsHolder.init(args, ArgsHolder.ArgType.SLAVE); RestartHelper.init(); if (ArgsHolder.getMasterHost() == null) { ArgsHolder.printUsageAndExit(ArgsHolder.ArgType.SLAVE); } Slave slave = new Slave(new RemoteMasterConnection(ArgsHolder.getMasterHost(), ArgsHolder.getMasterPort())); try { slave.run(ArgsHolder.getSlaveIndex()); } catch (Exception e) { System.err.println("Unexpected error in scenario"); e.printStackTrace(); ShutDownHook.exit(127); } }
Source:
protected void executeQueryCommand() { List<VDS> vdsList = getDbFacade().getVdsDao() .getAllForNetwork(getParameters().getId()); List<VdsNetworkInterface> vdsNetworkInterfaceList = getDbFacade().getInterfaceDao() .getVdsInterfacesByNetworkId(getParameters().getId()); final Map<Guid, VDS> vdsById = Entities.businessEntitiesById(vdsList); List<PairQueryable<VdsNetworkInterface, VDS>> vdsInterfaceVdsPairs = new ArrayList<PairQueryable<VdsNetworkInterface, VDS>>(); Network network = getDbFacade().getNetworkDao().get(getParameters().getId()); HostNetworkQos qos = getDbFacade().getHostNetworkQosDao().get(network.getQosId()); for (final VdsNetworkInterface vdsNetworkInterface : vdsNetworkInterfaceList) { vdsInterfaceVdsPairs.add(new PairQueryable<VdsNetworkInterface, VDS>(vdsNetworkInterface, vdsById.get(vdsNetworkInterface.getVdsId()))); vdsNetworkInterface.setNetworkImplementationDetails(NetworkUtils.calculateNetworkImplementationDetails(network, qos, vdsNetworkInterface)); } getQueryReturnValue().setReturnValue(vdsInterfaceVdsPairs); }

Target:
protected void executeQueryCommand() { List<VDS> vdsList = getVdsDAO().getAllForNetwork(getParameters().getId()); List<VdsNetworkInterface> vdsNetworkInterfaceList = getInterfaceDao().getVdsInterfacesByNetworkId(getParameters().getId()); final Map<Guid, VDS> vdsById = Entities.businessEntitiesById(vdsList); List<PairQueryable<VdsNetworkInterface, VDS>> vdsInterfaceVdsPairs = new ArrayList<PairQueryable<VdsNetworkInterface, VDS>>(); Network network = getNetworkDao().get(getParameters().getId()); HostNetworkQos qos = getHostNetworkQosDao().get(network.getQosId()); for (final VdsNetworkInterface vdsNetworkInterface : vdsNetworkInterfaceList) { vdsInterfaceVdsPairs.add(new PairQueryable<VdsNetworkInterface, VDS>(vdsNetworkInterface, vdsById.get(vdsNetworkInterface.getVdsId()))); VdsNetworkInterface.NetworkImplementationDetails vdsInterfaceNetworkImplementationDetails = NetworkUtils.calculateNetworkImplementationDetails(network, qos, vdsNetworkInterface); vdsNetworkInterface.setNetworkImplementationDetails(vdsInterfaceNetworkImplementationDetails); } getQueryReturnValue().setReturnValue(vdsInterfaceVdsPairs); }
Source:
public Server createHttpServerInstance(int port) throws IOException { Server webServer = new Server(port); Handler[] handlerList = new Handler[6]; ContextHandler contextHandlerForScreen = new ContextHandler(); contextHandlerForScreen.setContextPath("/getscreen/"); contextHandlerForScreen.setHandler(new ConsoleProxyThumbnailHandler()); handlerList[0] = contextHandlerForScreen; ContextHandler contextHandlerForResources = new ContextHandler(); contextHandlerForScreen.setContextPath("/resource/"); contextHandlerForScreen.setHandler(new ConsoleProxyResourceHandler()); handlerList[1] = contextHandlerForResources; ContextHandler contextHandlerForAjax = new ContextHandler(); contextHandlerForAjax.setContextPath("/ajax/"); contextHandlerForAjax.setHandler(new ConsoleProxyAjaxHandler()); handlerList[2] = contextHandlerForAjax; ContextHandler contextHandlerForAjaxImage = new ContextHandler(); contextHandlerForAjaxImage.setContextPath("/ajaximg/"); contextHandlerForAjaxImage.setHandler(new ConsoleProxyAjaxImageHandler()); handlerList[3] = contextHandlerForAjaxImage; ContextHandler contextHandlerForNoVnc = new ContextHandler(); contextHandlerForNoVnc.setContextPath("/novnc/"); contextHandlerForNoVnc.setHandler(new NoVncConsoleHandler()); handlerList[4] = contextHandlerForNoVnc; ContextHandler contextHandlerForWebSockify = new ContextHandler(); contextHandlerForWebSockify.setContextPath("/websockify/"); contextHandlerForWebSockify.setHandler(new WebSocketHandlerForNovnc()); handlerList[5] = contextHandlerForWebSockify; ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlerList); webServer.setHandler(contexts); return webServer; }

Target:
public Server createHttpServerInstance(int port) throws IOException { Server webServer = new Server(port); return webServer; }
Source:
public void testLinkage3_Bug299482() throws Exception { fOptions.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_LINKAGE_DECLARATION, DefaultCodeFormatterConstants.NEXT_LINE); }

Target:
public void testLinkage3_Bug299482() throws Exception { fOptions.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_LINKAGE_DECLARATION, DefaultCodeFormatterConstants.NEXT_LINE); assertFormatterResult(); }
Source:
public DataFormatChooserValues() { super( DataFormat.AVRO, DataFormat.DELIMITED, DataFormat.EXCEL, DataFormat.JSON, DataFormat.LOG, DataFormat.PROTOBUF, DataFormat.SDC_JSON, DataFormat.TEXT, DataFormat.WHOLE_FILE, DataFormat.XML, DataFormat.SAS ); }

Target:
public DataFormatChooserValues() { super( DataFormat.AVRO, DataFormat.DELIMITED, DataFormat.EXCEL, DataFormat.JSON, DataFormat.LOG, DataFormat.PROTOBUF, DataFormat.SDC_JSON, DataFormat.TEXT, DataFormat.WHOLE_FILE, DataFormat.XML ); }
Source:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Project project = call.rel(1); if (RexOver.containsOver(project.getProjects(), null)) { return; } RexNode newCondition = RelOptUtil.pushPastProject(filter.getCondition(), project); final RelBuilder relBuilder = call.builder(); RelNode newFilterRel; if (copyFilter) { final RelNode input = project.getInput(); final RelTraitSet traitSet = filter.getTraitSet() .replaceIfs(RelCollationTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelCollationTraitDef.INSTANCE))) .replaceIfs(RelDistributionTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE))); newCondition = simplifyFilterCondition(newCondition, call); newFilterRel = filter.copy(traitSet, input, newCondition); } else { newFilterRel = relBuilder.push(project.getInput()).filter(newCondition).build(); } RelNode newProjRel = copyProject ? project.copy(project.getTraitSet(), newFilterRel, project.getProjects(), project.getRowType()) : relBuilder.push(newFilterRel) .project(project.getProjects(), project.getRowType().getFieldNames()) .build(); if (newCondition.isAlwaysFalse() && newFilterRel.getInputs().stream() .map(RelOptUtil::getVariablesUsed) .allMatch(Collection::isEmpty)) { newProjRel = relBuilder.push(newProjRel).empty().build(); } call.transformTo(newProjRel); }

Target:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Project project = call.rel(1); if (RexOver.containsOver(project.getProjects(), null)) { return; } RexNode newCondition = RelOptUtil.pushPastProject(filter.getCondition(), project); final RelBuilder relBuilder = call.builder(); RelNode newFilterRel; if (copyFilter) { final RelNode input = project.getInput(); final RelTraitSet traitSet = filter.getTraitSet() .replaceIfs(RelCollationTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelCollationTraitDef.INSTANCE))) .replaceIfs(RelDistributionTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE))); newCondition = RexUtil.removeNullabilityCast(relBuilder.getTypeFactory(), newCondition); newFilterRel = filter.copy(traitSet, input, newCondition); } else { newFilterRel = relBuilder.push(project.getInput()).filter(newCondition).build(); } RelNode newProjRel = copyProject ? project.copy(project.getTraitSet(), newFilterRel, project.getProjects(), project.getRowType()) : relBuilder.push(newFilterRel) .project(project.getProjects(), project.getRowType().getFieldNames()) .build(); call.transformTo(newProjRel); }
Source:
private void checkForNonResponsiveHosts(final ConfirmationModel confirmModel) { startProgress(null); Frontend.RunQuery(VdcQueryType.GetHostsByClusterId, new IdQueryParameters(((VDSGroup) getSelectedItem()).getId()), new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterListModel model = (ClusterListModel) target; ArrayList<VDS> hosts = null; if (returnValue instanceof ArrayList) { hosts = (ArrayList<VDS>) returnValue; } else if (returnValue instanceof VdcQueryReturnValue && ((VdcQueryReturnValue) returnValue).getReturnValue() instanceof ArrayList) { hosts = (ArrayList<VDS>) ((VdcQueryReturnValue) returnValue).getReturnValue(); } else { throw new IllegalArgumentException("The return value should be ArrayList<VDS> or VdcQueryReturnValue with return value ArrayList<VDS>"); } boolean result = false; for (VDS host : hosts) { if (VDSStatus.NonResponsive == host.getStatus()) { result = true; break; } } if (result) { confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .youAreAboutChangeClusterCompatibilityVersionNonResponsiveHostsMsg()); } else { confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .youAreAboutChangeClusterCompatibilityVersionMsg()); } model.stopProgress(); } })); }

Target:
private void checkForNonResponsiveHosts(final ConfirmationModel confirmModel) { startProgress(null); Frontend.RunQuery(VdcQueryType.GetHostsByClusterId, new IdQueryParameters(((VDSGroup) getSelectedItem()).getId()), new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterListModel model = (ClusterListModel) target; ArrayList<VDS> hosts = null; if (returnValue instanceof ArrayList) { hosts = (ArrayList<VDS>) returnValue; } else if (returnValue instanceof VdcQueryReturnValue && ((VdcQueryReturnValue) returnValue).getReturnValue() instanceof ArrayList) { hosts = (ArrayList<VDS>) ((VdcQueryReturnValue) returnValue).getReturnValue(); } boolean foundNRHosts = false; if (hosts != null) { for (VDS host : hosts) { if (VDSStatus.NonResponsive == host.getStatus()) { foundNRHosts = true; break; } } } if (foundNRHosts) { confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .youAreAboutChangeClusterCompatibilityVersionNonResponsiveHostsMsg()); } else { confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .youAreAboutChangeClusterCompatibilityVersionMsg()); } model.stopProgress(); } })); }