auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void link(Collection<org.onebusaway.gtfs.model.Stop> gtfsStops) { for (org.onebusaway.gtfs.model.Stop gtfsStop : gtfsStops) { if (gtfsStop.getLocationType() == 0 && gtfsStop.getParentStation() != null) { Stop otpStop = getOtpStop(gtfsStop); Station otpStation = getOtpParentStation(gtfsStop); if (otpStation == null) { LOG.warn("Parent station not found. Stop will not be linked to a parent" + " station.", gtfsStop.getParentStation(), gtfsStop.getId().getId()); continue; } otpStop.setParentStation(otpStation); otpStation.addChildStop(otpStop); } } }

Target:
void link(Collection<org.onebusaway.gtfs.model.Stop> gtfsStops) { for (org.onebusaway.gtfs.model.Stop gtfsStop : gtfsStops) { if (gtfsStop.getLocationType() == 0 && gtfsStop.getParentStation() != null) { Stop otpStop = getOtpStop(gtfsStop); Station otpStation = getOtpParentStation(gtfsStop); if (otpStation == null) { addBuilderAnnotation.addBuilderAnnotation( new ParentStationNotFoundAnnotation( otpStop, gtfsStop.getParentStation() ) ); continue; } otpStop.setParentStation(otpStation); otpStation.addChildStop(otpStop); } } }
Source:
public SslCertResponse uploadSslCert(final UploadSslCertCmd certCmd) { try { final String cert = certCmd.getCert(); final String key = certCmd.getKey(); final String password = certCmd.getPassword(); final String chain = certCmd.getChain(); validate(cert, key, password, chain); s_logger.debug("Certificate Validation succeeded"); final String fingerPrint = generateFingerPrint(parseCertificate(cert)); final CallContext ctx = CallContext.current(); final Account caller = ctx.getCallingAccount(); Account owner = null; if (certCmd.getAccountName() != null && certCmd.getDomainId() != null || certCmd.getProjectId() != null) { owner = _accountMgr.finalizeOwner(caller, certCmd.getAccountName(), certCmd.getDomainId(), certCmd.getProjectId()); } else { owner = caller; } final Long accountId = owner.getId(); final Long domainId = owner.getDomainId(); final SslCertVO certVO = new SslCertVO(cert, key, password, chain, accountId, domainId, fingerPrint); _sslCertDao.persist(certVO); return createCertResponse(certVO, null); } catch (final Exception e) { throw new CloudRuntimeException("Error parsing certificate data " + e.getMessage()); } }

Target:
public SslCertResponse uploadSslCert(final UploadSslCertCmd certCmd) { Preconditions.checkNotNull(certCmd); final String cert = certCmd.getCert(); final String key = certCmd.getKey(); final String password = certCmd.getPassword(); final String chain = certCmd.getChain(); validate(cert, key, password, chain); s_logger.debug("Certificate Validation succeeded"); final String fingerPrint = CertificateHelper.generateFingerPrint(parseCertificate(cert)); final CallContext ctx = CallContext.current(); final Account caller = ctx.getCallingAccount(); Account owner = null; if (!Strings.isNullOrEmpty(certCmd.getAccountName()) && certCmd.getDomainId() != null || certCmd.getProjectId() != null) { owner = _accountMgr.finalizeOwner(caller, certCmd.getAccountName(), certCmd.getDomainId(), certCmd.getProjectId()); } else { owner = caller; } final Long accountId = owner.getId(); final Long domainId = owner.getDomainId(); final SslCertVO certVO = new SslCertVO(cert, key, password, chain, accountId, domainId, fingerPrint); _sslCertDao.persist(certVO); return createCertResponse(certVO, null); }
Source:
public Map<String, String> serializeJetpackParams() { Map<String, String> params = new HashMap<>(); params.put(JP_MONITOR_ACTIVE_KEY, String.valueOf(mSettings.monitorActive)); params.put(JP_MONITOR_EMAIL_NOTES_KEY, String.valueOf(mSettings.emailNotifications)); params.put(JP_MONITOR_WP_NOTES_KEY, String.valueOf(mSettings.wpNotifications)); return params; }

Target:
private Map<String, String> serializeJetpackParams() { Map<String, String> params = new HashMap<>(); params.put(JP_MONITOR_ACTIVE_KEY, String.valueOf(mSettings.monitorActive)); params.put(JP_MONITOR_EMAIL_NOTES_KEY, String.valueOf(mSettings.emailNotifications)); params.put(JP_MONITOR_WP_NOTES_KEY, String.valueOf(mSettings.wpNotifications)); return params; }
Source:
public String[] getDetailedLoad() { return null; }

Target:
public Map<String,String> getDetailedLoad() { return fDetailedLoad; }
Source:
public void testToJSONFunctionExtension3() throws InterruptedException { log.info("ToJSONFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select " + "map:createFromJSON(\"{'symbol':'WSO2','price':100,'volume':100,'last5val':{'price':150,'volume':200}}\") as hashMap insert into outputStream;" + "from outputStream " + "select map:toJSON() as jsonString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }

Target:
public void testToJSONFunctionExtension3() throws InterruptedException { log.info("ToJSONFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select " + "map:createFromJSON(\"{'symbol':'WSO2','price':100,'volume':100,'last5val':{'price':150,'volume'" + ":200}}\") as hashMap insert into outputStream;" + "from outputStream " + "select map:toJSON() as jsonString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }
Source:
public void testJvmtiAgentAppExternal() throws Exception { runJvmtiAgentLoadTest((ITestDevice device, String pkg, String apk, String abiName) -> { try { String pwd = device.executeShellCommand( "run-as " + pkg + " --user " + mCurrentUser + " pwd"); if (pwd == null) { throw new RuntimeException("pwd failed"); } pwd = pwd.trim(); if (pwd.isEmpty()) { throw new RuntimeException("pwd failed"); } String libInDataData = AGENT.substring(0, AGENT.length() - ".so".length()) + "2.so"; String agentInDataData = installLibToDataData(device, pkg, abiName, apk, pwd, AGENT, libInDataData); String setAgentAppCmd = "cmd activity set-agent-app " + pkg + " " + agentInDataData; device.executeShellCommand(setAgentAppCmd); } catch (Exception e) { throw new RuntimeException("Failed running set-agent-app", e); } try { runAttachTestCmd(device, pkg, ""); runAttachTestCmd(device, pkg, ""); } catch (Exception e) { throw new RuntimeException("Failed agent-app attaching", e); } }); }

Target:
public void testJvmtiAgentAppExternal() throws Exception { runJvmtiAgentLoadTest((ITestDevice device, String pkg, String apk, String abiName) -> { try { String pwd = getPwd(device, pkg); String libInDataData = AGENT.substring(0, AGENT.length() - ".so".length()) + "2.so"; String agentInDataData = installLibToDataData(device, pkg, abiName, apk, pwd, AGENT, libInDataData); String setAgentAppCmd = "cmd activity set-agent-app " + pkg + " " + agentInDataData; device.executeShellCommand(setAgentAppCmd); } catch (Exception e) { throw new RuntimeException("Failed running set-agent-app", e); } try { runAttachTestCmd(device, pkg, ""); runAttachTestCmd(device, pkg, ""); } catch (Exception e) { throw new RuntimeException("Failed agent-app attaching", e); } }); }
Source:
public void selectPhotosOnly() { filterPhotos.click(); }

Target:
public void selectPhotosOnly() { filterPhotos.click(); PageObjectLogging.log("selectPhotosOnly", "Photos option is selected", true, driver); }
Source:
public <T, ASSERT extends AbstractAssert<?, ?>> ASSERT extracting(Function<? super ACTUAL, T> extractor, InstanceOfAssertFactory<?, ASSERT> assertFactory) { return extracting(extractor, this::newObjectAssert).asInstanceOf(assertFactory); }

Target:
public <T, ASSERT extends AbstractAssert<?, ?>> ASSERT extracting(Function<? super ACTUAL, T> extractor, InstanceOfAssertFactory<?, ASSERT> assertFactory) { return super.extracting(extractor, this::newObjectAssert).asInstanceOf(assertFactory); }
Source:
public GenieResourceHttpRequestHandler(final DirectoryWriter directoryWriter, final JobFileService jobFileService) { super(); this.directoryWriter = directoryWriter; this.jobFileService = jobFileService; try { this.jobFileService.createJobDirectory(V4_MOCK_JOB_ID); } catch (final IOException ioe) { log.error( "Unable to create V4 placeholder job directory. All requests for V4 output will return 404.", ioe ); } }

Target:
public GenieResourceHttpRequestHandler(final DirectoryWriter directoryWriter, final JobFileService jobFileService) { super(); this.directoryWriter = directoryWriter; this.jobFileService = jobFileService; try { this.jobFileService.createJobDirectory(V4_MOCK_JOB_ID); this.jobFileService.updateFile(V4_MOCK_JOB_ID, JobConstants.STDOUT_LOG_FILE_NAME, 0L, new byte[0]); this.jobFileService.updateFile(V4_MOCK_JOB_ID, JobConstants.STDERR_LOG_FILE_NAME, 0L, new byte[0]); this.jobFileService.updateFile(V4_MOCK_JOB_ID, JobConstants.GENIE_JOB_LAUNCHER_SCRIPT, 0L, new byte[0]); } catch (final IOException ioe) { log.error( "Unable to create V4 placeholder job directory. All requests for V4 output will return 404.", ioe ); } }
Source:
public Set<String> committers() { return getCommitters(build); }

Target:
public Set<String> committers() { return buildCulpritsRetriever.getCommitters(build); }
Source:
private boolean isOwn() { return (reviewitem != null) && (reviewitem.getReview() != null) && (reviewitem.getReview().getRepository() != null) && (reviewitem.getReview().getRepository() != null) && (reviewitem.getReview().getRepository().getTaskRepository() != null) && (reviewitem.getReview() .getRepository() .getTaskRepository() .getCredentials(AuthenticationType.REPOSITORY) != null) && (reviewitem.getReview() .getRepository() .getTaskRepository() .getCredentials(AuthenticationType.REPOSITORY) .getUserName() .compareTo(currentAuthor) == 0); }

Target:
private boolean isOwn() { return (reviewitem != null) && (reviewitem.getReview() != null) && (reviewitem.getReview().getRepository() != null) && (reviewitem.getReview().getRepository().getTaskRepository() != null) && (reviewitem.getReview() .getRepository() .getTaskRepository() .getCredentials(AuthenticationType.REPOSITORY) != null) && (reviewitem.getReview() .getRepository() .getTaskRepository() .getCredentials(AuthenticationType.REPOSITORY) .getUserName() .compareTo(currentAuthor) == 0); }
Source:
public void recycleAttributes(long ts) { fPoolAttributes.entrySet().stream().forEach(e -> { NonNullUtils.checkNotNull(e.getKey()).recycle(e.getValue(), ts); }); }

Target:
public void recycleAttributes(long ts) { fPoolAttributes.entrySet().forEach(e -> { NonNullUtils.checkNotNull(e.getKey()).recycle(e.getValue(), ts); }); }
Source:
private void updateEventMask() { if (this.status == ACTIVE && (this.endOfStream || this.sslEngine.isInboundDone())) { this.status = CLOSING; } if (this.status == CLOSING && !this.outEncrypted.hasData()) { this.sslEngine.closeOutbound(); final int n = this.outboundClosedCount.incrementAndGet(); if (n > 5) { this.status = CLOSED; } } if (this.status == CLOSING && this.sslEngine.isOutboundDone() && (this.endOfStream || this.sslEngine.isInboundDone())) { this.status = CLOSED; } if (this.status <= CLOSING && this.endOfStream && this.sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) { this.status = CLOSED; } if (this.status == CLOSED) { this.session.close(); if (disconnectedCallback != null) { disconnectedCallback.execute(this); } return; } final int oldMask = this.session.getEventMask(); int newMask = oldMask; switch (this.sslEngine.getHandshakeStatus()) { case NEED_WRAP: newMask = EventMask.READ_WRITE; break; case NEED_UNWRAP: newMask = EventMask.READ; break; case NOT_HANDSHAKING: newMask = this.appEventMask; break; case NEED_TASK: break; case FINISHED: break; } if (this.endOfStream) { newMask = newMask & ~EventMask.READ; } if (this.outEncrypted.hasData()) { newMask = newMask | EventMask.WRITE; } if (oldMask != newMask) { this.session.setEventMask(newMask); } }

Target:
private void updateEventMask() { if (this.status == ACTIVE && (this.endOfStream || this.sslEngine.isInboundDone())) { this.status = CLOSING; } if (this.status == CLOSING && !this.outEncrypted.hasData()) { this.sslEngine.closeOutbound(); this.outboundClosedCount.incrementAndGet(); } if (this.status == CLOSING && this.sslEngine.isOutboundDone() && (this.endOfStream || this.sslEngine.isInboundDone())) { this.status = CLOSED; } if (this.status <= CLOSING && this.endOfStream && this.sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) { this.status = CLOSED; } if (this.status == CLOSED) { this.session.close(); if (disconnectedCallback != null) { disconnectedCallback.execute(this); } return; } final int oldMask = this.session.getEventMask(); int newMask = oldMask; switch (this.sslEngine.getHandshakeStatus()) { case NEED_WRAP: newMask = EventMask.READ_WRITE; break; case NEED_UNWRAP: newMask = EventMask.READ; break; case NOT_HANDSHAKING: newMask = this.appEventMask; break; case NEED_TASK: break; case FINISHED: break; } if (this.endOfStream && !this.inPlain.hasData()) { newMask = newMask & ~EventMask.READ; } if (this.outEncrypted.hasData()) { newMask = newMask | EventMask.WRITE; } if (oldMask != newMask) { this.session.setEventMask(newMask); } }
Source:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTableView reviewTableView = GerritTableView.getActiveView(); GerritUi.Ftracer.traceInfo(NLS.bind(Messages.AllReviewsHandler_executeCommand, GerritQuery.QUERY_ALL_ABANDONED_CHANGES)); reviewTableView.processCommands(GerritQuery.QUERY_ALL_ABANDONED_CHANGES); return null; }

Target:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTableView reviewTableView = GerritTableView.getActiveView(); reviewTableView.processCommands(GerritQuery.QUERY_ALL_ABANDONED_CHANGES); return null; }
Source:
static HttpClient createFixed(HttpClientConfig httpClientConfig) { if (httpClientConfig.getConfigs() == null) { throw new IllegalArgumentException("HttpClientConfig is null"); } Integer maxIdleConnectionTimeoutInMillis = 60 * 1000; if (httpClientConfig.getMaxIdleConnectionTimeoutInMillis() != null) { maxIdleConnectionTimeoutInMillis = httpClientConfig.getMaxIdleConnectionTimeoutInMillis(); } Integer maxPoolSize = 500; if (httpClientConfig.getMaxPoolSize() != null) { maxPoolSize = httpClientConfig.getMaxPoolSize(); } int connectionAcquireTimeoutInMillis = 45 * 1000; ConnectionProvider fixedConnectionProvider = ConnectionProvider.fixed(httpClientConfig.getConfigs().getReactorNettyConnectionPoolName(), maxPoolSize, connectionAcquireTimeoutInMillis, Duration.ofMillis(maxIdleConnectionTimeoutInMillis)); return ReactorNettyClient.createWithConnectionProvider(fixedConnectionProvider, httpClientConfig); }

Target:
static HttpClient createFixed(HttpClientConfig httpClientConfig) { if (httpClientConfig.getConfigs() == null) { throw new IllegalArgumentException("HttpClientConfig is null"); } Integer maxIdleConnectionTimeoutInMillis = httpClientConfig.getConfigs().getMaxIdleConnectionTimeoutInMillis(); if (httpClientConfig.getMaxIdleConnectionTimeoutInMillis() != null) { maxIdleConnectionTimeoutInMillis = httpClientConfig.getMaxIdleConnectionTimeoutInMillis(); } Integer maxPoolSize = httpClientConfig.getConfigs().getReactorNettyMaxConnectionPoolSize(); if (httpClientConfig.getMaxPoolSize() != null) { maxPoolSize = httpClientConfig.getMaxPoolSize(); } int connectionAcquireTimeoutInMillis = httpClientConfig.getConfigs().getConnectionAcquireTimeoutInMillis(); ConnectionProvider fixedConnectionProvider = ConnectionProvider.fixed(httpClientConfig.getConfigs().getReactorNettyConnectionPoolName(), maxPoolSize, connectionAcquireTimeoutInMillis, Duration.ofMillis(maxIdleConnectionTimeoutInMillis)); return ReactorNettyClient.createWithConnectionProvider(fixedConnectionProvider, httpClientConfig); }
Source:
protected void writeValue( VarValueDef value) { ConditionWriter conditionWriter = new ConditionWriter( value.getCondition()); xmlWriter_.writeElement( VALUE_TAG, MapBuilder .of( NAME_ATR, String.valueOf( value.getName())) .putIf( FAILURE_ATR, Optional.ofNullable( value.getType() == FAILURE? "true" : null)) .putIf( ONCE_ATR, Optional.ofNullable( value.getType() == ONCE? "true" : null)) .putIf( WHEN_ATR, conditionWriter.getWhenAttribute()) .putIf( PROPERTY_ATR, propertyList( toStream( value.getProperties().getProperties()))) .build(), () -> { writeAnnotations( value); conditionWriter.writeWhenElement(); }); }

Target:
protected void writeValue( VarValueDef value) { ConditionWriter conditionWriter = new ConditionWriter( value.getCondition()); xmlWriter_ .element( VALUE_TAG) .attribute( NAME_ATR, String.valueOf( value.getName())) .attributeIf( value.getType() == FAILURE, FAILURE_ATR, "true") .attributeIf( value.getType() == ONCE, ONCE_ATR, "true") .attributeIf( WHEN_ATR, conditionWriter.getWhenAttribute()) .attributeIf( PROPERTY_ATR, propertyList( toStream( value.getProperties().getProperties()))) .content( () -> { writeAnnotations( value); conditionWriter.writeWhenElement(); }) .write(); }
Source:
public void remove() { throw new RuntimeException("Removal of records not implemented."); }

Target:
public void remove() { throw new UnsupportedOperationException("Removal of records not implemented."); }
Source:
protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); ruleEngine.updateRule(element, (disabledRulesStorage != null && disabledRulesStorage.get(uid) == null)); String templateUID = element.getTemplateUID(); if (templateUID != null) { synchronized (this) { Set<String> ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs != null) { ruleUIDs.remove(uid); } } } postRuleUpdatedEvent(element, oldElement); }

Target:
protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); ruleEngine.updateRule(element, (disabledRulesStorage != null && disabledRulesStorage.get(uid) == null)); String templateUID = element.getTemplateUID(); if (templateUID != null) { synchronized (this) { Set<String> ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs != null) { ruleUIDs.remove(uid); } } } }
Source:
private void refreshPackages(Bundle[] bundles, BundleContext context) { if (bundles.length == 0 || packageAdminService == null) { return; } CountDownLatch latch = new CountDownLatch(1); FrameworkListener listener = event -> { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { latch.countDown(); } }; context.addFrameworkListener(listener); packageAdminService.refreshPackages(bundles); try { latch.await(); } catch (InterruptedException e) { } context.removeFrameworkListener(listener); }

Target:
private void refreshPackages(Bundle[] bundles, BundleContext context) { if (bundles.length == 0 || packageAdminService == null) return; CountDownLatch latch = new CountDownLatch(1); Set<Bundle> allSameBSNs = new LinkedHashSet<>(); for (Bundle bundle : bundles) { allSameBSNs.add(bundle); String bsn = bundle.getSymbolicName(); if (bsn != null) { Bundle[] sameBSNs = packageAdminService.getBundles(bsn, null); if (sameBSNs != null) { allSameBSNs.addAll(Arrays.asList(sameBSNs)); } } } final boolean[] flag = new boolean[] {false}; FrameworkListener listener = event -> { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { latch.countDown(); } }; context.addFrameworkListener(listener); packageAdminService.refreshPackages(allSameBSNs.toArray(new Bundle[0])); try { latch.await(); } catch (InterruptedException e) { } context.removeFrameworkListener(listener); }
Source:
public ExecResponse create() throws Exception { try { session = acquire(execConnection()); Command output = session.exec(checkNotNull(command, "command")); String outputString = IOUtils.readFully(output.getInputStream()).toString(); output.join(sshClientConnection.getSessionTimeout(), TimeUnit.MILLISECONDS); int errorStatus = output.getExitStatus() != null ? output.getExitStatus() : -1; String errorString = IOUtils.readFully(output.getErrorStream()).toString(); return new ExecResponse(outputString, errorString, errorStatus); } finally { clear(); } }

Target:
public ExecResponse create() throws Exception { try { session = acquire(execConnection()); Command output = session.exec(checkNotNull(command, "command")); String outputString = IOUtils.readFully(output.getInputStream()).toString(); output.join(sshClientConnection.getSessionTimeout(), TimeUnit.MILLISECONDS); String errorString = IOUtils.readFully(output.getErrorStream()).toString(); return new ExecResponse(outputString, errorString, output.getExitStatus()); } finally { clear(); } }
Source:
public void getPatientIdentifiers_shouldGetByPatients() { List<Patient> patients = Arrays.asList( hibernatePatientDAO.getPatient(6), hibernatePatientDAO.getPatient(7) ); List<PatientIdentifier> identifiers = hibernatePatientDAO .getPatientIdentifiers(null, emptyList(), emptyList(), patients, null); List<Integer> identifierIds = identifiers.stream().map(identifier -> identifier.getId()) .collect(Collectors.toList()); Assert.assertEquals(2, identifiers.size()); Assert.assertEquals(true, identifierIds.contains(3)); Assert.assertEquals(true, identifierIds.contains(4)); }

Target:
public void getPatientIdentifiers_shouldGetByPatients() { List<Patient> patients = Arrays.asList( hibernatePatientDao.getPatient(6), hibernatePatientDao.getPatient(7) ); List<PatientIdentifier> identifiers = hibernatePatientDao .getPatientIdentifiers(null, emptyList(), emptyList(), patients, null); List<Integer> identifierIds = identifiers.stream().map(identifier -> identifier.getId()) .collect(Collectors.toList()); Assert.assertEquals(2, identifiers.size()); Assert.assertThat(identifierIds, hasItems(3, 4)); }
Source:
public ResponseEntity harvestConfigurationMetadata(@RequestBody String configurationMetadataJsonPayload) { try { logger.debug(configurationMetadataJsonPayload); List<ConfigurationMetaData> configurationMetaDataList = this.mapper.readValue(configurationMetadataJsonPayload , mapper.getTypeFactory().constructCollectionType(List.class, ConfigurationMetaDataImpl.class)); this.configurationMetaDataBatchInsert.insert(configurationMetaDataList); } catch (Exception e) { e.printStackTrace(); throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "An error has occurred attempting to perform a batch insert of ConfigurationMetaData!", e); } return new ResponseEntity("Configuration metadata successfully captured!", HttpStatus.OK); }

Target:
public ResponseEntity harvestConfigurationMetadata(@RequestBody String configurationMetadataJsonPayload) { try { logger.debug(configurationMetadataJsonPayload); List<ConfigurationMetaData> configurationMetaDataList = this.mapper.readValue(configurationMetadataJsonPayload , mapper.getTypeFactory().constructCollectionType(List.class, ConfigurationMetaDataImpl.class)); this.configurationMetaDataBatchInsert.insert(configurationMetaDataList); } catch (Exception e) { throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "An error has occurred attempting to perform a batch insert of ConfigurationMetaData!", e); } return new ResponseEntity("Configuration metadata successfully captured!", HttpStatus.OK); }
Source:
public void test_evaluateAllDecisionsOnInputDataStringModel() { DMNContext dmnContext = dmnClient.newContext(); dmnContext.set( "Full Name", "John Doe" ); ServiceResponse<DMNResult> evaluateAllDecisions = dmnClient.evaluateAllDecisions(CONTAINER_1_ID, "<LINK_0>", "input-data-string", dmnContext); DMNResult dmnResult = evaluateAllDecisions.getResult(); assertThat( dmnResult.getDecisionResults().size(), is( 1 ) ); assertThat( dmnResult.getDecisionResultByName( "Greeting Message" ).getResult(), is( "Hello John Doe" ) ); DMNContext result = dmnResult.getContext(); assertThat( result.get( "Greeting Message" ), is( "Hello John Doe" ) ); }

Target:
public void test_evaluateAllDecisionsOnInputDataStringModel() { DMNContext dmnContext = dmnClient.newContext(); dmnContext.set( "Full Name", "John Doe" ); ServiceResponse<DMNResult> evaluateAllDecisions = dmnClient.evaluateAllDecisions(CONTAINER_1_ID, "<LINK_0>", "input-data-string", dmnContext); assertEquals(ResponseType.SUCCESS, evaluateAllDecisions.getType()); DMNResult dmnResult = evaluateAllDecisions.getResult(); assertThat( dmnResult.getDecisionResults().size(), is( 1 ) ); assertThat( dmnResult.getDecisionResultByName( "Greeting Message" ).getResult(), is( "Hello John Doe" ) ); DMNContext result = dmnResult.getContext(); assertThat( result.get( "Greeting Message" ), is( "Hello John Doe" ) ); }
Source:
public ClusterExecutor executor() { if (!started) { throw new IllegalStateException("CacheManager must be started before retrieving a ClusterExecutor!"); } JGroupsTransport transport = (JGroupsTransport) globalComponentRegistry.getComponent(Transport.class); if (transport != null) { long time = getCacheManagerConfiguration().transport().distributedSyncTimeout(); return new ClusterExecutorImpl(null, transport, time, TimeUnit.MILLISECONDS, globalComponentRegistry.getComponent(ExecutorService.class, KnownComponentNames.REMOTE_COMMAND_EXECUTOR)); } else { return new ClusterExecutorImpl(null, null, -1, TimeUnit.MILLISECONDS, ForkJoinPool.commonPool()); } }

Target:
public ClusterExecutor executor() { if (globalComponentRegistry.getStatus() != ComponentStatus.RUNNING) { throw new IllegalStateException("CacheManager must be started before retrieving a ClusterExecutor!"); } JGroupsTransport transport = (JGroupsTransport) globalComponentRegistry.getComponent(Transport.class); if (transport != null) { long time = getCacheManagerConfiguration().transport().distributedSyncTimeout(); return new ClusterExecutorImpl(null, this, transport, time, TimeUnit.MILLISECONDS, globalComponentRegistry.getComponent(ExecutorService.class, KnownComponentNames.REMOTE_COMMAND_EXECUTOR)); } else { return new ClusterExecutorImpl(null, this, null, -1, TimeUnit.MILLISECONDS, ForkJoinPool.commonPool()); } }
Source:
public boolean add(XWikiAttachment attachment) { map.put(attachment.getFilename(), attachment); this.list = new ArrayList<XWikiAttachment>(map.values()); onUpdate(); added(attachment); return true; }

Target:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return set != attachment; }
Source:
public static AnnotationProvider createAnnotationProvider(ServletContext sc) { AnnotationProvider annotationProvider = createDefaultProvider(sc); String[] services = ServiceFactoryUtils.getServiceEntries(ANNOTATION_PROVIDER_SERVICE_KEY); if (services.length > 0) { Object provider = null; try { provider = ServiceFactoryUtils.getProviderFromEntry(services[0], new Class[] { ServletContext.class, AnnotationProvider.class }, new Object[] { sc , annotationProvider }); } catch (FacesException e) { throw e; } catch (NoSuchMethodException e) { } if (provider == null) { try { provider = ServiceFactoryUtils.getProviderFromEntry(services[0], new Class[] { ServletContext.class }, new Object[] { sc }); } catch (FacesException | NoSuchMethodException e) { throw new FacesException(e); } } if (provider != null) { if (!(provider instanceof AnnotationProvider)) { throw new FacesException("Class " + provider.getClass().getName() + " is not an instance of com.sun.faces.spi.AnnotationProvider"); } annotationProvider = (AnnotationProvider)provider; } } else { ServiceLoader<AnnotationProvider> serviceLoader = ServiceLoader.load(AnnotationProvider.class); Iterator iterator = serviceLoader.iterator(); if (iterator.hasNext()) { AnnotationProvider defaultAnnotationProvider = annotationProvider; annotationProvider = (AnnotationProvider) iterator.next(); annotationProvider.initialize(sc, defaultAnnotationProvider); } } return annotationProvider; }

Target:
public static AnnotationProvider createAnnotationProvider(ServletContext sc) { AnnotationProvider annotationProvider = createDefaultProvider(sc); String[] services = ServiceFactoryUtils.getServiceEntries(ANNOTATION_PROVIDER_SERVICE_KEY); if (services.length > 0) { Object provider = null; try { provider = ServiceFactoryUtils.getProviderFromEntry(services[0], new Class[] { ServletContext.class, AnnotationProvider.class }, new Object[] { sc , annotationProvider }); } catch (FacesException e) { if(!NoSuchMethodException.class.isInstance(e.getCause())) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, e.toString(), e); } } } if (provider == null) { try { provider = ServiceFactoryUtils.getProviderFromEntry(services[0], new Class[] { ServletContext.class }, new Object[] { sc }); } catch (FacesException e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, e.toString(), e); } } } if (provider != null) { if (!(provider instanceof AnnotationProvider)) { throw new FacesException("Class " + provider.getClass().getName() + " is not an instance of com.sun.faces.spi.AnnotationProvider"); } annotationProvider = (AnnotationProvider)provider; } } else { ServiceLoader<AnnotationProvider> serviceLoader = ServiceLoader.load(AnnotationProvider.class); Iterator iterator = serviceLoader.iterator(); if (iterator.hasNext()) { AnnotationProvider defaultAnnotationProvider = annotationProvider; annotationProvider = (AnnotationProvider) iterator.next(); annotationProvider.initialize(sc, defaultAnnotationProvider); } } return annotationProvider; }
Source:
public synchronized void load() throws IOException { UpdateSite defaultSite = new UpdateSite(LEGACY_ID_DEFAULT, config.getUpdateCenterUrl() + "update-center.json"); XmlFile file = getConfigFile(); if(file.exists()) { try { sites.replaceBy(((PersistedList)file.unmarshal(sites)).toList()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } for (UpdateSite site : sites) { if (site.isLegacyDefault()) { sites.remove(site); sites.add(defaultSite); break; } } } else { if (sites.isEmpty()) { sites.add(defaultSite); } } }

Target:
public synchronized void load() throws IOException { XmlFile file = getConfigFile(); if(file.exists()) { try { sites.replaceBy(((PersistedList)file.unmarshal(sites)).toList()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } boolean defaultSiteExists = false; for (UpdateSite site : sites) { if (site.isLegacyDefault()) { sites.remove(site); } else if (ID_DEFAULT.equals(site.getId())) { defaultSiteExists = true; } } if (!defaultSiteExists) { sites.add(createDefaultUpdateSite()); } } else { if (sites.isEmpty()) { sites.add(createDefaultUpdateSite()); } } }
Source:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws DAOException { if (patientProgram.getPatientProgramId() == null) { sessionFactory.getCurrentSession().save(patientProgram); } else { sessionFactory.getCurrentSession().merge(patientProgram); } CustomDatatypeUtil.saveAttributesIfNecessary(patientProgram); return patientProgram; }

Target:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws DAOException { CustomDatatypeUtil.saveAttributesIfNecessary(patientProgram); if (patientProgram.getPatientProgramId() == null) { sessionFactory.getCurrentSession().save(patientProgram); } else { sessionFactory.getCurrentSession().merge(patientProgram); } return patientProgram; }
Source:
public Collection<PatchSetApproval> currentApprovals(Provider<ReviewDb> db) throws OrmException { if (currentApprovals == null) { Change c = change(db); if (c == null) { currentApprovals = Collections.emptyList(); } else if (approvals != null) { currentApprovals = approvalsMap(db).get(c.currentPatchSetId()); if (currentApprovals == null) { currentApprovals = Collections.emptyList(); } } else { currentApprovals = db.get().patchSetApprovals() .byPatchSet(c.currentPatchSetId()).toList(); } } return currentApprovals; }

Target:
public Collection<PatchSetApproval> currentApprovals(Provider<ReviewDb> db) throws OrmException { if (currentApprovals == null) { Change c = change(db); if (c == null) { currentApprovals = Collections.emptyList(); } else if (approvals != null) { Map<Id, Collection<PatchSetApproval>> map = approvalsMap(db); currentApprovals = map.get(c.currentPatchSetId()); if (currentApprovals == null) { currentApprovals = Collections.emptyList(); map.put(c.currentPatchSetId(), currentApprovals); } } else { currentApprovals = db.get().patchSetApprovals() .byPatchSet(c.currentPatchSetId()).toList(); } } return currentApprovals; }
Source:
public void clearSort() { ColumnSortInfo columnSortInfo2 = new ColumnSortInfo(null, false); SSDataGrid.this.dataGrid.getColumnSortList().push(columnSortInfo2); }

Target:
public void clearSort() { ColumnSortInfo columnSortInfo = new ColumnSortInfo(null, false); SSDataGrid.this.dataGrid.getColumnSortList().push(columnSortInfo); }
Source:
public void deactivate() { logger.debug("deactivate"); smlDevices.clear(); }

Target:
public void deactivate() { smlDevices.clear(); }
Source:
protected boolean isCookieSecure(final HttpServletRequest request, CookieConfig config) { boolean configSecure = config.isSecure(); Resolver<Boolean> resolver = getSecureCookieRequired(); boolean resolverSecure = resolver.get(request, null); boolean likelyLocalhost = resolver instanceof SecureRequiredExceptForLocalhostResolver; boolean warnable = !configSecure || (!resolverSecure && !likelyLocalhost); if (!secureWarned && warnable) { secureWarned = true; String msg = "INSECURE IDENTITY COOKIE CONFIGURATION: Your current Stormpath SDK account cookie " + "configuration allows insecure identity cookies (transmission over non-HTTPS connections)! " + "This should never occur on staging/production machines otherwise your users will be " + "susceptible to man-in-the-middle attacks. If you see this warning on a development-only " + "machine, you can likely safely ignore this message. For more information in Servlet-only " + "environments, please see the Security Notice here: " + "<LINK_4> and the " + "documentation on authentication state here: " + "<LINK_3> and here: " + "<LINK_5> (the " + "callout entitled 'Secure Cookies'). If you are using Spring Boot, Spring Boot-specific " + "documentation for these concepts are here: " + "<LINK_0> " + "<LINK_2> and " + "<LINK_1>"; log.warn(msg); } return configSecure && resolverSecure; }

Target:
protected boolean isCookieSecure(final HttpServletRequest request, CookieConfig config) { boolean configSecure = config.isSecure(); Resolver<Boolean> resolver = getSecureCookieRequired(); boolean resolverSecure = resolver.get(request, null); boolean likelyLocalhost = resolver instanceof SecureRequiredExceptForLocalhostResolver; boolean warnable = !configSecure || (!resolverSecure && !likelyLocalhost); if (!secureWarned && warnable) { secureWarned = true; String msg = "INSECURE IDENTITY COOKIE CONFIGURATION: Your current Stormpath SDK account cookie " + "configuration allows insecure identity cookies (transmission over non-HTTPS connections)! " + "This should typically never occur otherwise your users will be " + "susceptible to man-in-the-middle attacks. For more information in Servlet-only " + "environments, please see the Security Notice here: " + "<LINK_4> and the " + "documentation on authentication state here: " + "<LINK_3> and here: " + "<LINK_5> (the " + "callout entitled 'Secure Cookies'). If you are using Spring Boot, Spring Boot-specific " + "documentation for these concepts are here: " + "<LINK_0> " + "<LINK_2> and " + "<LINK_1>"; log.warn(msg); } return configSecure && resolverSecure; }
Source:
public static String getJar() { final String command = getCommand(); if (command != null) { final String[] segments = command.split(" "); if (segments.length >= 1) { if (segments[0].endsWith(".jar")) { return segments[0]; } } } else { String classpath = System.getProperty("java.class.path"); if (!classpath.isEmpty() && !classpath.contains(File.pathSeparator) && classpath.endsWith(".jar")) { return classpath; } } return null; }

Target:
public static String getJar() { String segment = getFirstSegmentOfCommand(); if (segment != null && segment.endsWith(".jar")) { return segment; } else { String classpath = System.getProperty("java.class.path"); if (!classpath.isEmpty() && !classpath.contains(File.pathSeparator) && classpath.endsWith(".jar")) { return classpath; } } return null; }
Source:
protected void executeCommand() { List<VM> vms = runInternalQuery(VdcQueryType.GetVmsByStorageDomain, new IdQueryParameters(getStorageDomain().getId())) .getReturnValue(); Map<Guid, Guid> vmIdSnapshotIdMap = new HashMap<>(); for (VM vm : vms) { CreateAllSnapshotsFromVmParameters param = new CreateAllSnapshotsFromVmParameters(vm.getId(), vm.getName() + getStorageDomain().getName() + DR_SNAPSHOT_NAME_SUFFIX, false, vm.getDiskList()); Guid createdSnapshotId = runInternalAction(VdcActionType.CreateAllSnapshotsFromVm, param).getActionReturnValue(); vmIdSnapshotIdMap.put(vm.getId(), createdSnapshotId); } getParameters().setVmIdSnapshotIds(vmIdSnapshotIdMap); persistCommandIfNeeded(); if (getSession().getStatus() != GeoRepSessionStatus.ACTIVE) { Future<VdcReturnValueBase> geoRepCmd = CommandCoordinatorUtil.executeAsyncCommand(VdcActionType.StartGlusterVolumeGeoRep, new GlusterVolumeGeoRepSessionParameters(getSession().getMasterVolumeId(), getSession().getId()), cloneContext()); VdcReturnValueBase result; try { result = geoRepCmd.get(); if (!result.getSucceeded()) { propagateFailure(result); setSucceeded(false); return; } } catch (InterruptedException | ExecutionException e) { log.error("Exception", e); setSucceeded(false); return; } } GlusterVolumeGeoRepSessionConfigParameters configParams = new GlusterVolumeGeoRepSessionConfigParameters(getSession().getMasterVolumeId(), getSession().getId(), "checkpoint", "now"); VdcReturnValueBase result = runInternalAction(VdcActionType.SetGeoRepConfig, configParams); if (!result.getSucceeded()) { propagateFailure(result); return; } setSucceeded(true); }

Target:
protected void executeCommand() { setSucceeded(false); List<VM> vms = runInternalQuery(VdcQueryType.GetVmsByStorageDomain, new IdQueryParameters(getStorageDomain().getId())) .getReturnValue(); Map<Guid, Guid> vmIdSnapshotIdMap = new HashMap<>(); for (VM vm : vms) { try { Future<VdcReturnValueBase> future = CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.CreateAllSnapshotsFromVm, getCreateSnapshotParameters(vm), cloneContextAndDetachFromParent()); vmIdSnapshotIdMap.put(vm.getId(), future.get().getActionReturnValue()); } catch (InterruptedException | ExecutionException e) { log.error("Error creating VM snapshots for DR sync", e.getMessage()); log.debug("Exception", e); endWithFailure(); getParameters().setTaskGroupSuccess(false); } } getParameters().setVmIdSnapshotIds(vmIdSnapshotIdMap); getParameters().setNextStep(DRStep.GEO_REP); persistCommandIfNeeded(); setSucceeded(true); }
Source:
public static void loadFile(ScoreBoard scoreBoard, File f) throws Exception{ JSONObject json = new JSONObject(FileUtils.readFileToString(f, "utf-8")); List<ScoreBoardJSONSetter.JSONSet> jsl = new ArrayList<>(); JSONObject state = json.getJSONObject("state"); for (String key: state.keySet()) { Object value = state.get(key); String v; if (value == JSONObject.NULL) { v = null; } else { v = value.toString(); } jsl.add(new ScoreBoardJSONSetter.JSONSet(key, v, Flag.FROM_AUTOSAVE)); } ScoreBoardJSONSetter.set(scoreBoard, jsl); }

Target:
public static void loadFile(ScoreBoard scoreBoard, File f) throws Exception { JSONObject json = new JSONObject(FileUtils.readFileToString(f, "utf-8")); ScoreBoardJSONSetter.set(scoreBoard, json); }
Source:
public boolean matchesSafely(Engine.Searcher searcher) { try { this.count = (int) searcher.searcher().count(query); return count == totalHits; } catch (IOException e) { return false; } }

Target:
public boolean matchesSafely(Engine.Searcher searcher) { try { this.count = searcher.searcher().count(query); return count == totalHits; } catch (IOException e) { return false; } }
Source:
public void commandRun() { if (zkServer == null) { pw.print(ZK_NOT_SERVING); } else { List<ZxidDigest> digestLog = zkServer.getZKDatabase().getDataTree().getDigestLog(); for (ZxidDigest zd : digestLog) { pw.println(Long.toHexString(zd.getZxid()) + ": " + zd.getDigest()); } } }

Target:
public void commandRun() { if (!isZKServerRunning()) { pw.print(ZK_NOT_SERVING); } else { List<ZxidDigest> digestLog = zkServer.getZKDatabase().getDataTree().getDigestLog(); for (ZxidDigest zd : digestLog) { pw.println(Long.toHexString(zd.getZxid()) + ": " + zd.getDigest()); } } }
Source:
public InMemoryNoteBucket getRoot() { return root; }

Target:
InMemoryNoteBucket getRoot() { return root; }
Source:
private EntityModelLabelEditor getInstanceOfDateEditor() { return new EntityModelLabelEditor(new EntityModelRenderer(){ @Override public String render(Object entity) { return FullDateTimeRenderer.getLocalizedDateTimeFormat().format((Date) entity); } }, new EntityModelParser()); }

Target:
private EntityModelLabelEditor getInstanceOfDateEditor() { return new EntityModelLabelEditor(new EntityModelRenderer(){ @Override public String render(Object entity) { if((Date) entity == null) { return ConstantsManager.getInstance().getConstants().notAvailableLabel(); } return FullDateTimeRenderer.getLocalizedDateTimeFormat().format((Date) entity); } }, new EntityModelParser()); }
Source:
public void enableStatistics(Collection<String> cacheNames, boolean enabled) throws IgniteCheckedException { Collection<IgniteInternalCache> caches = manageStatisticsCaches(cacheNames); Collection<String> globalCaches = new HashSet<>(caches.size()); for (IgniteInternalCache cache : caches) { cache.context().statisticsEnabled(enabled); if(!cache.context().isLocal()) globalCaches.add(cache.name()); } if (globalCaches.isEmpty()) return; CacheStatisticsModeChangeMessage msg = new CacheStatisticsModeChangeMessage(UUID.randomUUID(), globalCaches, enabled); EnableStatisticsFuture fut = new EnableStatisticsFuture(msg.requestId()); manageStatisticsFuts.put(msg.requestId(), fut); ctx.grid().context().discovery().sendCustomEvent(msg); fut.get(); }

Target:
public void enableStatistics(Collection<String> cacheNames, boolean enabled) throws IgniteCheckedException { Collection<IgniteInternalCache> caches = manageStatisticsCaches(cacheNames); Collection<String> globalCaches = new HashSet<>(U.capacity(caches.size())); for (IgniteInternalCache cache : caches) { cache.context().statisticsEnabled(enabled); if (!cache.context().isLocal()) globalCaches.add(cache.name()); } if (globalCaches.isEmpty()) return; CacheStatisticsModeChangeMessage msg = new CacheStatisticsModeChangeMessage(UUID.randomUUID(), globalCaches, enabled); EnableStatisticsFuture fut = new EnableStatisticsFuture(msg.requestId()); manageStatisticsFuts.put(msg.requestId(), fut); ctx.grid().context().discovery().sendCustomEvent(msg); fut.get(); }
Source:
public void createWebInfFolderIfNotExist() { File folder = new File("target/test-classes/WEB-INF"); if (!folder.exists()) { folder.mkdirs(); } }

Target:
public void createWebInfFolderIfNotExist() { File folder = new File(Paths.get("target", "test-classes", "WEB-INF").toString()); if (!folder.exists()) { folder.mkdirs(); } }
Source:
public UnaryTestSubexpr visit(UnaryTestListNode n) { List<BaseNode> collect = new ArrayList<>(); for (BaseNode e : n.getElements()) { UnaryTestSubexpr accept = e.accept(this); if (accept.isWildcard()) { collect.add(asWildcard(accept.node)); } else if (!accept.isUnaryTest()) { collect.add(asUnaryEq(accept.node)); } else { collect.add(accept.node); } } return new TopLevel( ASTBuilderFactory.newUnaryTestListNode(n.getParserRuleContext(), collect, n.getState())); }

Target:
public UnaryTestSubexpr visit(UnaryTestListNode n) { List<BaseNode> collect = new ArrayList<>(); for (BaseNode e : n.getElements()) { UnaryTestSubexpr accept = e.accept(this); if (accept.isWildcard()) { collect.add(rewriteToUnaryTestExpr(accept.node)); } else if (!accept.isUnaryTest()) { collect.add(rewriteToUnaryEqInExpr(accept.node)); } else { collect.add(accept.node); } } return new TopLevel( ASTBuilderFactory.newUnaryTestListNode(n.getParserRuleContext(), collect, n.getState())); }
Source:
private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnWildProject(section.getName(), permissionName)) { section.removePermission(permissionName); } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }

Target:
private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { final List<Permission> permissions = section.getPermissions(); section = new AccessSection(section.getName()); section.setPermissions(permissions); for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnAllProjects(section.getName(), permissionName)) { section.removePermission(permissionName); } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }
Source:
private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: "; Boolean invalidAction = false; String errorMessage = null; if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) && !samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId()) ) { errorMessage = String.format("%s invalid processor id neither in running or pending processors", errorMessagePrefix); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format("%s duplicate UUID of the request, please retry", errorMessagePrefix); invalidAction = true; } else if (standbyContainerManager.isPresent() && !standbyContainerManager.get() .checkStandbyConstraints(requestMessage.getProcessorId(), requestMessage.getDestinationHost())) { errorMessage = String.format("%s destination host does not meet standby constraints", errorMessagePrefix); invalidAction = true; } if (invalidAction) { return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); }

Target:
private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: %s"; Boolean invalidAction = false; String errorMessage = null; if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) && !samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId()) ) { errorMessage = String.format(errorMessagePrefix, "invalid processor id neither in running or pending processors"); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format(errorMessagePrefix, "duplicate UUID of the request, please retry"); invalidAction = true; } else if (standbyContainerManager.isPresent() && !standbyContainerManager.get() .checkStandbyConstraints(requestMessage.getProcessorId(), requestMessage.getDestinationHost())) { errorMessage = String.format(errorMessagePrefix, "destination host does not meet standby constraints"); invalidAction = true; } if (invalidAction) { return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); }