auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void calculateIntStreamPartitions(JobGraph jobGraph, Config config) { int partitions = config.getInt(JobConfig.JOB_INTERMEDIATE_STREAM_PARTITIONS(), StreamEdge.PARTITIONS_UNKNOWN); if (partitions < 0) { int maxInPartitions = maxPartition(jobGraph.getSources()); int maxOutPartitions = maxPartition(jobGraph.getSinks()); partitions = Math.max(maxInPartitions, maxOutPartitions); if (partitions > MAX_INFERRED_PARTITIONS) { partitions = MAX_INFERRED_PARTITIONS; log.warn(String.format("Inferred intermediate stream partition count %d is greater than the max %d. Using the max.", partitions, MAX_INFERRED_PARTITIONS)); } } for (StreamEdge edge : jobGraph.getIntermediateStreamEdges()) { if (edge.getPartitionCount() <= 0) { log.info("Initialize the partition count for edge to {}.", edge.getName(), partitions); edge.setPartitionCount(partitions); } } }

Target:
private static void calculateIntStreamPartitions(JobGraph jobGraph, Config config) { int partitions = config.getInt(JobConfig.JOB_INTERMEDIATE_STREAM_PARTITIONS(), StreamEdge.PARTITIONS_UNKNOWN); if (partitions < 0) { int maxInPartitions = maxPartition(jobGraph.getSources()); int maxOutPartitions = maxPartition(jobGraph.getSinks()); partitions = Math.max(maxInPartitions, maxOutPartitions); if (partitions > MAX_INFERRED_PARTITIONS) { partitions = MAX_INFERRED_PARTITIONS; log.warn(String.format("Inferred intermediate stream partition count %d is greater than the max %d. Using the max.", partitions, MAX_INFERRED_PARTITIONS)); } } for (StreamEdge edge : jobGraph.getIntermediateStreamEdges()) { if (edge.getPartitionCount() <= 0) { log.info("Set the partition count for intermediate stream to {}.", edge.getName(), partitions); edge.setPartitionCount(partitions); } } }
Source:
protected View.OnClickListener validateAndSubmit(){ return new View.OnClickListener() { @Override public void onClick(View view) { List<String> errorStrings = new ArrayList<String>(); if (mTitleField.getText().toString().length() == 0) errorStrings.add("Title"); if (mDescriptionField.getText().toString().length() == 0) errorStrings.add("Description"); if (mAddressField.getText().toString().length() == 0) errorStrings.add("Address"); if (errorStrings.size() > 0) Utility.setEmpty(mParentActivity, errorStrings); else { submitListener(); SiteViewPagerFragment returnFragment = SiteViewPagerFragment.newInstance(); mParentActivity.replaceFragment(returnFragment); } } }; }

Target:
protected View.OnClickListener validateAndSubmit(){ return new View.OnClickListener() { @Override public void onClick(View view) { List<String> errorStrings = new ArrayList<String>(); if (mTitleField.getText().toString().length() == 0) { errorStrings.add("Title"); } if (mDescriptionField.getText().toString().length() == 0) { errorStrings.add("Description"); } if (mAddressField.getText().toString().length() == 0) { errorStrings.add("Address"); } if (errorStrings.size() > 0) { Utility.setEmpty(mParentActivity, errorStrings); } else { submitListener(); SiteViewPagerFragment returnFragment = SiteViewPagerFragment.newInstance(); mParentActivity.replaceFragment(returnFragment); } } }; }
Source:
protected static boolean skipFile(@SuppressWarnings("unused") @NotNull Path path, @NotNull Long modificationTime, Long lastModificationTime) throws IOException { if(lastModificationTime == null) { return false; } return (!(lastModificationTime == null || modificationTime > lastModificationTime)); }

Target:
protected static boolean skipFile(@SuppressWarnings("unused") @NotNull Path path, @NotNull Long modificationTime, Long lastModificationTime) throws IOException { return (!(lastModificationTime == null || modificationTime > lastModificationTime)); }
Source:
public RegionCoprocessorHost(final HRegion region, final RegionServerServices rsServices, final Configuration conf) { super(rsServices); this.conf = conf; this.rsServices = rsServices; this.region = region; this.pathPrefix = Integer.toString(this.region.getRegionInfo().hashCode()); loadSystemCoprocessors(conf, REGION_COPROCESSOR_CONF_KEY); if (!region.getRegionInfo().getTable().isSystemTable()) { loadSystemCoprocessors(conf, USER_REGION_COPROCESSOR_CONF_KEY); } loadTableCoprocessors(conf); boolean hasCustomPostScannerFilterRow = false; out: for (RegionCoprocessorEnvironment env: coprocEnvironments) { if (env.getInstance() instanceof RegionObserver) { Class<?> clazz = env.getInstance().getClass(); for(;;) { if (clazz == null) { hasCustomPostScannerFilterRow = true; break out; } try { clazz.getDeclaredMethod("postScannerFilterRow", ObserverContext.class, InternalScanner.class, Cell.class, boolean.class); hasCustomPostScannerFilterRow = true; break out; } catch (NoSuchMethodException ignore) { } try { clazz.getDeclaredMethod("postScannerFilterRow", ObserverContext.class, InternalScanner.class, byte[].class, int.class, short.class, boolean.class); hasCustomPostScannerFilterRow = true; break out; } catch (NoSuchMethodException ignore) { } clazz = clazz.getSuperclass(); if (clazz == Object.class) { break out; } } } } this.hasCustomPostScannerFilterRow = hasCustomPostScannerFilterRow; }

Target:
public RegionCoprocessorHost(final HRegion region, final RegionServerServices rsServices, final Configuration conf) { super(rsServices); this.conf = conf; this.rsServices = rsServices; this.region = region; this.pathPrefix = Integer.toString(this.region.getRegionInfo().hashCode()); loadSystemCoprocessors(conf, REGION_COPROCESSOR_CONF_KEY); if (!region.getRegionInfo().getTable().isSystemTable()) { loadSystemCoprocessors(conf, USER_REGION_COPROCESSOR_CONF_KEY); } loadTableCoprocessors(conf); boolean hasCustomPostScannerFilterRow = false; out: for (RegionCoprocessorEnvironment env: coprocEnvironments) { if (env.getInstance() instanceof RegionObserver) { Class<?> clazz = env.getInstance().getClass(); for (;;) { if (clazz == Object.class) { break; } try { clazz.getDeclaredMethod("postScannerFilterRow", ObserverContext.class, InternalScanner.class, Cell.class, boolean.class); hasCustomPostScannerFilterRow = true; break out; } catch (NoSuchMethodException ignore) { } try { clazz.getDeclaredMethod("postScannerFilterRow", ObserverContext.class, InternalScanner.class, byte[].class, int.class, short.class, boolean.class); hasCustomPostScannerFilterRow = true; break out; } catch (NoSuchMethodException ignore) { } clazz = clazz.getSuperclass(); } } } this.hasCustomPostScannerFilterRow = hasCustomPostScannerFilterRow; }
Source:
public void testWaitForStartAndCancelBeforeStart() throws Exception { final OneShotEvent ev = new OneShotEvent(); FreeStyleProject p = createFreeStyleProject(); QueueTaskFuture<FreeStyleBuild> f = p.scheduleBuild2(10); final Queue.Item item = Queue.getInstance().getItem(p); assertNotNull(item); final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); executor.schedule(new Runnable() { @Override public void run() { try { Queue.getInstance().doCancelItem(item.id); } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } }, 2, TimeUnit.SECONDS); try { f.waitForStart(); assertTrue(f.isCancelled()); } catch (CancellationException e) }

Target:
public void testWaitForStartAndCancelBeforeStart() throws Exception { final OneShotEvent ev = new OneShotEvent(); FreeStyleProject p = createFreeStyleProject(); QueueTaskFuture<FreeStyleBuild> f = p.scheduleBuild2(10); final Queue.Item item = Queue.getInstance().getItem(p); assertNotNull(item); final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); executor.schedule(new Runnable() { @Override public void run() { try { Queue.getInstance().doCancelItem(item.id); } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } }, 2, TimeUnit.SECONDS); try { f.waitForStart(); fail("Expected an CancellationException to be thrown"); } catch (CancellationException e) }
Source:
public void addEvent(IResourceChangeEvent event) { synchronized (pendingJobs) { if (!noMoreEvents) { events.add(event); } else { throw new IllegalStateException("This job is underway, no new events can be added"); } } }

Target:
void addEvent(IResourceChangeEvent event) { synchronized (pendingJobs) { if (!noMoreEvents) { events.add(event); } else { throw new IllegalStateException("This job is underway, no new events can be added"); } } }
Source:
public void testSsModule() { ITmfStateSystem ss = fModule.getStateSystem(); assertNull(ss); fModule.schedule(); if (fModule.waitForCompletion()) { ss = fModule.getStateSystem(); assertNotNull(ss); try { int quark = ss.getQuarkAbsolute(TestExperimentAnalysis.TRACE_QUARK_NAME); ITmfStateInterval interval = ss.querySingleState(ss.getCurrentEndTime(), quark); System.out.println("Exp ss value at " + ss.getCurrentEndTime() + ": " + interval); assertEquals(2, interval.getStateValue().unboxInt()); } catch (AttributeNotFoundException e) { fail("The quark for number of traces does not exist"); } catch (StateSystemDisposedException e) { fail("Error: state system disposed"); } } else { fail("Module did not complete properly"); } }

Target:
public void testSsModule() { ITmfStateSystem ss = fModule.getStateSystem(); assertNull(ss); fModule.schedule(); if (fModule.waitForCompletion()) { ss = fModule.getStateSystem(); assertNotNull(ss); try { int quark = ss.getQuarkAbsolute(TestExperimentAnalysis.TRACE_QUARK_NAME); ITmfStateInterval interval = ss.querySingleState(ss.getCurrentEndTime(), quark); assertEquals(2, interval.getStateValue().unboxInt()); } catch (AttributeNotFoundException e) { fail("The quark for number of traces does not exist"); } catch (StateSystemDisposedException e) { fail("Error: state system disposed"); } } else { fail("Module did not complete properly"); } }
Source:
File getTempFile(ParseFile.State state) { if (state.url() == null) { return null; } return new File(cachePath, ParseDigestUtils.md5(state.url())); }

Target:
File getTempFile(ParseFile.State state) { if (state.url() == null) { return null; } return new File(cachePath, state.url() + ".tmp"); }
Source:
public void delete() throws IOException { root.retrieve().method("POST").withPreview(INERTIA).method("DELETE").withUrlPath(getApiRoute()).to(); }

Target:
public void delete() throws IOException { root.createRequest().withPreview(INERTIA).method("DELETE").withUrlPath(getApiRoute()).send(); }
Source:
public void start(ComponentContext context) { init(); ConfigurationService configuration = Framework.getService(ConfigurationService.class); storeState = Boolean.parseBoolean(configuration.getProperty(STORESTATE_KEY)); stateTTL = Long.parseLong(configuration.getProperty(STATETTL_KEY, STATETTL_DEFAULT_VALUE)); }

Target:
public void start(ComponentContext context) { init(); ConfigurationService configuration = Framework.getService(ConfigurationService.class); storeState = configuration.isBooleanPropertyTrue(STORESTATE_KEY); stateTTL = Long.parseLong(configuration.getProperty(STATETTL_KEY, STATETTL_DEFAULT_VALUE)); }
Source:
public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { FSDataOutputStream out; final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); final Path path = new Path(filename); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); out = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()) .create(path); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } } @Override public void close() { try { writer.close(); out.close(); } catch (IOException e) { throw new DataException(e); } } @Override public void commit() }; }

Target:
public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { FileSystem fs; final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); final Path path = new Path(filename); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); FSDataOutputStream out = fs.create(path); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } } @Override public void close() { IOException error = null; try { writer.close(); } catch (IOException e) { error = e; throw new DataException(e); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { if (error == null) { throw new DataException(e); } } } } } @Override public void commit() }; }
Source:
public Builder addOptions(String... keyValuePairs) { Preconditions.checkArgument(keyValuePairs.length % 2 == 0 && keyValuePairs.length > 0, "Require an even, positive number of arguments, got %s", keyValuePairs.length); for (int i = 0; i < keyValuePairs.length; i += 2) { addOption(keyValuePairs[i], keyValuePairs[i + 1]); } return this; }

Target:
public Builder addOptions(String... keyValuePairs) { Preconditions.checkArgument(keyValuePairs.length % 2 == 0 && keyValuePairs.length > 0, "Require an even, positive number of arguments, got %s", keyValuePairs.length); for (int i = 1; i < keyValuePairs.length; i += 2) { addOption(keyValuePairs[i - 1], keyValuePairs[i]); } return this; }
Source:
public SegmentArchiveReader open(String archiveName) throws IOException { AwsContext directoryContext = awsContext.withDirectory(archiveName); if (!directoryContext.doesObjectExist("closed")) { throw new IOException("The archive " + archiveName + " hasn't been closed correctly."); } return new AwsSegmentArchiveReader(directoryContext, archiveName, ioMonitor); }

Target:
public SegmentArchiveReader open(String archiveName) throws IOException { S3Directory archiveDirectory = directory.withDirectory(archiveName); if (!archiveDirectory.doesObjectExist("closed")) { throw new IOException("The archive " + archiveName + " hasn't been closed correctly."); } return new AwsSegmentArchiveReader(archiveDirectory, archiveName, ioMonitor); }
Source:
private void finalizeResolving() { if (!shutdownInProgress.get()) { shutdownPools(); } if (diagnostic.getSeverity() >= Diagnostic.ERROR) { dependencyGraph.clear(); } resolvedResources = null; diagnostic = null; notResolving.signal(); lock.unlock(); }

Target:
private void finalizeResolving() { if (!shutdownInProgress.get()) { shutdownPools(); } if (diagnostic.getSeverity() >= Diagnostic.ERROR) { dependencyGraph.clear(); } resolvedResources = null; diagnostic = null; }
Source:
public List<DBNote> searchNotes(long accountId, @Nullable CharSequence query, @Nullable String category, @Nullable Boolean favorite) { validateAccountId(accountId); List<String> where = new ArrayList<>(); List<String> args = new ArrayList<>(); where.add(key_status + " != ?"); args.add(DBStatus.LOCAL_DELETED.getTitle()); where.add(key_account_id + " = ?"); args.add("" + accountId); if (query != null) { where.add(key_status + " != ?"); args.add(DBStatus.LOCAL_DELETED.getTitle()); where.add("(" + key_title + " LIKE ? OR " + key_content + " LIKE ? OR " + key_category + " LIKE ?" + ")"); args.add("%" + query + "%"); args.add("%" + query + "%"); args.add("%" + query + "%"); } if (category != null) { List<Integer> ids = getCategoryIdsByTitle(accountId, category); if (ids.size() == 0) { return new ArrayList<DBNote>(); } StringBuffer tmpSQL = new StringBuffer(); String tmp = String.format(" %s = ? ", key_category); for (int i = 0; i < ids.size(); i++) { tmpSQL.append(tmp); if (i != ids.size() - 1) { tmpSQL.append(" or "); } } where.add(String.format("( %s )", tmpSQL.toString())); for (int i = 0; i < ids.size(); i++) { args.add(String.valueOf(ids.get(i))); } } if (favorite != null) { where.add(key_favorite + "=?"); args.add(favorite ? "1" : "0"); } String order = category == null ? default_order : key_category + ", " + key_title; return getNotesCustom(accountId, TextUtils.join(" AND ", where), args.toArray(new String[]{}), order, true); }

Target:
public List<DBNote> searchNotes(long accountId, @Nullable CharSequence query, @Nullable String category, @Nullable Boolean favorite) { validateAccountId(accountId); List<String> where = new ArrayList<>(); List<String> args = new ArrayList<>(); where.add(key_status + " != ?"); args.add(DBStatus.LOCAL_DELETED.getTitle()); where.add(key_account_id + " = ?"); args.add("" + accountId); if (query != null) { where.add(key_status + " != ?"); args.add(DBStatus.LOCAL_DELETED.getTitle()); where.add("(" + key_title + " LIKE ? OR " + key_content + " LIKE ? OR " + key_category + " LIKE ?" + ")"); args.add("%" + query + "%"); args.add("%" + query + "%"); args.add("%" + query + "%"); } if (category != null) { where.add(key_category + " IN (SELECT " + key_category_id + " FROM " + table_category + " WHERE " + key_category_title + " =? OR " + key_category_title + " LIKE ?)"); args.add(category); args.add(category + "/%"); } if (favorite != null) { where.add(key_favorite + "=?"); args.add(favorite ? "1" : "0"); } String order = category == null ? default_order : key_category + ", " + key_title; return getNotesCustom(accountId, TextUtils.join(" AND ", where), args.toArray(new String[]{}), order, true); }
Source:
public static <T> T get(String key) { ensureKeyIsValid(key); String fullText = storage.get(key); try { return encoder.decode(fullText); } catch (Exception e) { Logger.d(e.getMessage()); } return null; }

Target:
public static <T> T get(String key) { if (key == null) { throw new NullPointerException("Key cannot be null"); } String fullText = storage.get(key); try { return encoder.decode(fullText); } catch (Exception e) { Logger.d(e.getMessage()); } return null; }
Source:
protected void preConsumerPollHook() { while (!_taskUpdates.isEmpty()) { TaskUpdateType updateType = _taskUpdates.remove(); if (updateType == null) { continue; } else if (updateType == TaskUpdateType.PAUSE_RESUME_PARTITIONS) { pausePartitions(); } } }

Target:
protected void preConsumerPollHook() { while (!_taskUpdates.isEmpty()) { DatastreamConstants.UpdateType updateType = _taskUpdates.remove(); if (updateType != null) { switch (updateType) { case PAUSE_RESUME_PARTITIONS: pausePartitions(); break; default: String msg = String.format("Unknown update type for task {}.", updateType, _taskName); _logger.error(msg); throw new DatastreamRuntimeException(msg); } } } }
Source:
public ListenableFuture<SegmentsAndMetadata> publish( final TransactionalSegmentPublisher publisher, final Committer committer, final Collection<String> sequenceNames ) { final List<SegmentIdentifier> theSegments = getSegmentWithStates(sequenceNames) .map(SegmentWithState::getSegmentIdentifier) .collect(Collectors.toList()); final ListenableFuture<SegmentsAndMetadata> publishFuture = ListenableFutures.transformAsync( pushInBackground(wrapCommitter(committer), theSegments), sam -> publishInBackground( sam, publisher ) ); return ListenableFutures.transformAsync(publishFuture, sam -> { synchronized (segments) { sequenceNames.forEach(segments::remove); } final SettableFuture<SegmentsAndMetadata> future = SettableFuture.create(); future.set(sam); return future; }); }

Target:
public ListenableFuture<SegmentsAndMetadata> publish( final TransactionalSegmentPublisher publisher, final Committer committer, final Collection<String> sequenceNames ) { final List<SegmentIdentifier> theSegments = getSegmentWithStates(sequenceNames) .map(SegmentWithState::getSegmentIdentifier) .collect(Collectors.toList()); final ListenableFuture<SegmentsAndMetadata> publishFuture = ListenableFutures.transformAsync( pushInBackground(wrapCommitter(committer), theSegments), sam -> publishInBackground( sam, publisher ) ); return Futures.transform( publishFuture, (Function<? super SegmentsAndMetadata, ? extends SegmentsAndMetadata>) sam -> { synchronized (segments) { sequenceNames.forEach(segments::remove); } return sam; } ); }
Source:
private void watchLogsIfDebugEnabled(Map<String, String> startOptions, Pod pluginBrokerPod) throws InfrastructureException { if (startOptions == null) { LOG.debug( "'startOptions' is null so we won't watch the plugin broker pod logs for workspace '{}'", runtimeId.getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { namespace .deployments() .watchLogs( new PodLogHandlerToEventPublisher(runtimeEventsPublisher, runtimeId), new LogWatchTimeouts(5_000, 100, 2_500), ImmutableSet.of(pluginBrokerPod.getMetadata().getName())); } }

Target:
private void watchLogsIfDebugEnabled(Map<String, String> startOptions, Pod pluginBrokerPod) throws InfrastructureException { if (startOptions == null || startOptions.isEmpty()) { LOG.debug( "'startOptions' is null or empty so we won't watch the plugin broker pod logs for workspace '{}'", runtimeId.getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { namespace .deployments() .watchLogs( new PodLogToEventPublisher(runtimeEventsPublisher, runtimeId), LogWatchTimeouts.AGGRESSIVE, ImmutableSet.of(pluginBrokerPod.getMetadata().getName()), LogWatcher.getLogLimitBytes(startOptions)); } }
Source:
public Diff getPrimeRefining() { Diff main = null; if (primeRefining != null) { main = primeRefining; } else { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { main = rc; break; } } } } return main; }

Target:
public Diff getPrimeRefining() { if (primeRefining == null) { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { primeRefining = rc; break; } } } } return primeRefining; }
Source:
public void runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { String workflowURL = localPrimaryDescriptorFile.getName(); final File tempDir = Files.createTempDir(); List<File> workflowAttachment = new ArrayList<>(); workflowAttachment.add(localPrimaryDescriptorFile); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry, tempDir); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); String languageType = this.languageType.toString().toUpperCase(); String workflowTypeVersion = WORKFLOW_TYPE_VERSION; if ("CWL".equals(languageType.toUpperCase())) { workflowTypeVersion = "v" + WORKFLOW_TYPE_VERSION; } else if ("WDL".equals(languageType.toUpperCase())) { workflowTypeVersion = WDL_WORKFLOW_TYPE_VERSION; } try { RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, languageType, workflowTypeVersion, TAGS, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.openapi.wes.client.ApiException e) { LOG.error("Error launching WES run", e); } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException ioe) { LOG.error("Could not delete temporary directory" + tempDir + " for workflow attachment files", ioe); } } }

Target:
public void runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { String workflowURL = localPrimaryDescriptorFile.getName(); final File tempDir = Files.createTempDir(); List<File> workflowAttachment = new ArrayList<>(); workflowAttachment.add(localPrimaryDescriptorFile); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry, tempDir); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); String languageType = this.languageType.toString().toUpperCase(); String workflowTypeVersion = WORKFLOW_TYPE_VERSION; if ("CWL".equalsIgnoreCase(languageType)) { workflowTypeVersion = "v" + WORKFLOW_TYPE_VERSION; } else if ("WDL".equalsIgnoreCase(languageType)) { workflowTypeVersion = WDL_WORKFLOW_TYPE_VERSION; } try { RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, languageType, workflowTypeVersion, TAGS, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.openapi.wes.client.ApiException e) { LOG.error("Error launching WES run", e); } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException ioe) { LOG.error("Could not delete temporary directory" + tempDir + " for workflow attachment files", ioe); } } }
Source:
public void set(double position) { if (isInverted) { position = invertPosition(lastPosition); } for (Servo servo : servos) { servo.set(position); } lastPosition = position; }

Target:
public void set(double position) { if (isInverted) { position = ServoSubsystem.invertPosition(position); } for (Servo servo : servos) { servo.set(position); } lastPosition = position; }
Source:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(gn, ()->GraphViewSwitchable.createNamedGraph(this, key)); }

Target:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(key, ()->GraphViewSwitchable.createNamedGraph(this, key)); }
Source:
private DirectoryUser findDirectoryUser(String directoryName, User user) { DirectoryUser result = null; if (user.isSetId()) { String userId = DirectoryEntryIdUtils.decode(user.getId()); result = getEntity( DirectoryUser.class, VdcQueryType.GetDirectoryUserById, new DirectoryIdQueryParameters(directoryName, user.getNamespace(), userId), userId, true); } else { if (user.isSetUserName()) { result = getEntity( DirectoryUser.class, SearchType.DirectoryUser, getDirectoryUserSearchPattern( user.getUserName().contains("@") ? user.getUserName().substring(0, user.getUserName().indexOf("@")) : user.getUserName(), user.getNamespace(), directoryName) ); } } return result; }

Target:
private DirectoryUser findDirectoryUser(String directoryName, User user) { DirectoryUser result = null; String namespace = user.getNamespace(); if (user.isSetDomainEntryId()) { result = getUserById(directoryName, namespace, user.getDomainEntryId()); } else if (user.isSetId()) { result = getUserById(directoryName, namespace, user.getId()); } else { if (user.isSetUserName()) { result = getEntity( DirectoryUser.class, SearchType.DirectoryUser, getDirectoryUserSearchPattern( user.getUserName().contains("@") ? user.getUserName().substring(0, user.getUserName().indexOf("@")) : user.getUserName(), user.getNamespace(), directoryName) ); } } return result; }
Source:
public void doRun(IProgressMonitor monitor, String projectID, String bsId) throws CoreException { if (bsId == null) { SubMonitor submonitor = SubMonitor.convert(monitor, 1); doRun(submonitor.split(1), projectID); } else { Object[] selection = getCheckedElements(); if (selection != null) { int totalSelected = selection.length; if (totalSelected > 0) { if (monitor == null) { monitor = new NullProgressMonitor(); } SubMonitor submonitor = SubMonitor.convert(monitor, 1); submonitor.subTask(CUIPlugin.getResourceString(KEY_TITLE)); convertProjects(selection, bsId, submonitor.split(1)); } } } }

Target:
public void doRun(IProgressMonitor monitor, String projectID, String bsId) throws CoreException { if (bsId == null) { SubMonitor submonitor = SubMonitor.convert(monitor, 1); doRun(submonitor.split(1), projectID); } else { Object[] selection = getCheckedElements(); if (selection != null) { int totalSelected = selection.length; if (totalSelected > 0) { SubMonitor submonitor = SubMonitor.convert(monitor, CUIPlugin.getResourceString(KEY_TITLE), 1); convertProjects(selection, bsId, submonitor.split(1)); } } } }
Source:
public void MethodReferenceUsingThis() throws Exception { Result result = Result.createFor("MethodReferencesThis"); JavaSymbol bar1 = result.symbol("bar1"); assertThat(bar1.usages()).hasSize(2); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); MethodReferenceTree methodRef = (MethodReferenceTree) bar.usages().get(0).parent(); assertThat(methodRef.symbolType().is("java.util.function.Consumer")).isTrue(); MethodInvocationTree foreach = (MethodInvocationTree) methodRef.parent().parent(); assertThat(foreach.symbol().isUnknown()).isFalse(); assertThat(foreach.symbol().owner().type().is("java.lang.Iterable")).isTrue(); }

Target:
public void MethodReferenceUsingThis() throws Exception { Result result = Result.createFor("MethodReferencesThis"); JavaSymbol bar1 = result.symbol("bar1"); assertThat(bar1.usages()).hasSize(2); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); MethodReferenceTree methodRef = (MethodReferenceTree) bar.usages().get(0).parent(); assertThat(methodRef.symbolType().is("java.util.function.Consumer")).isTrue(); MethodInvocationTree foreach = (MethodInvocationTree) methodRef.parent().parent(); assertThat(foreach.symbol().owner().type().is("java.lang.Iterable")).isTrue(); }
Source:
public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata) { Context context = new Context(); List<RelationshipMetadataValue> fullMetadataValueList = new LinkedList<>(); try { List<MetadataValue> list = item.getMetadata(); String entityType = getEntityTypeStringFromMetadata(list); if (StringUtils.isNotBlank(entityType)) { List<Relationship> relationships = relationshipService.findByItem(context, item); for (Relationship relationship : relationships) { fullMetadataValueList .addAll(handleItemRelationship(context, item, entityType, relationship, enableVirtualMetadata)); } } } catch (SQLException e) { log.error(e, e); } return fullMetadataValueList; }

Target:
public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata) { Context context = new Context(); List<RelationshipMetadataValue> fullMetadataValueList = new LinkedList<>(); try { List<MetadataValue> list = item.getMetadata(); String entityType = getEntityTypeStringFromMetadata(list); if (StringUtils.isNotBlank(entityType)) { List<Relationship> relationships = relationshipService.findByItem(context, item); for (Relationship relationship : relationships) { fullMetadataValueList .addAll(handleItemRelationship(context, item, entityType, relationship, enableVirtualMetadata)); } } } catch (SQLException e) { log.error("Lookup for Relationships for item with uuid: " + item.getID() + " caused DSpace to crash", e); } return fullMetadataValueList; }
Source:
public NetMatcher(String commaSeparatedNets, DNSService dnsServer) { this.dnsServer = dnsServer; List<String> nets = Arrays.asList(commaSeparatedNets.split(NETS_SEPARATOR_PATTERN)); initInetNetworks(nets); }

Target:
public NetMatcher(String commaSeparatedNets, DNSService dnsServer) { this.dnsServer = dnsServer; List<String> nets = Splitter.on(NETS_SEPARATOR).trimResults().splitToList(commaSeparatedNets); initInetNetworks(nets); }
Source:
public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { Location location = Context.getLocationService().getLocation(1); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(1,results.size()); }

Target:
public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { Location location = Context.getLocationService().getLocation(4); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(0,results.size()); }
Source:
public void testSearchResult() { final List<Long> ll = Collections.singletonList(Long.MAX_VALUE - 1); final SearchResult infos = new SearchResult(ll, 1L); final List<Long> result = infos.getMessageNumbers(); final long modSeq = infos.getHighestModSeq(); Assert.assertEquals(result.size(), 1, "Result mismatched."); Assert.assertEquals(result.get(0), Long.valueOf(Long.MAX_VALUE - 1), "Result mismatched."); Assert.assertEquals(modSeq, 1L, "Result mismatched."); }

Target:
public void testSearchResult() { final List<Long> ll = Collections.singletonList(Long.MAX_VALUE - 1); final SearchResult sr = new SearchResult(ll, 1L); final List<Long> result = sr.getMessageNumbers(); final Long modSeq = sr.getHighestModSeq(); Assert.assertNotNull(result, "getMessageNumbers() should not return null."); Assert.assertEquals(result.size(), 1, "getMessageNumbers() size mismatched."); Assert.assertEquals(result.get(0), Long.valueOf(Long.MAX_VALUE - 1), "getMessageNumbers() mismatched."); Assert.assertNotNull(modSeq, "getHighestModSeq() should not return null"); Assert.assertEquals(modSeq, Long.valueOf(1), "getHighestModSeq() mismatched."); }
Source:
public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) { final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); final SortingCollection<String> sequenceNames = makeSortingCollection(); while (samSequenceRecordIterator.hasNext()) { final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next(); samDictCodec.encodeSequenceRecord(samSequenceRecord); sequenceNames.add(samSequenceRecord.getSequenceName()); } final CloseableIterator<String> iterator = sequenceNames.iterator(); if(!iterator.hasNext()) return; String current = iterator.next(); while (iterator.hasNext()) { final String next = iterator.next(); if (current.equals(next)) { throw new PicardException("Sequence name " + current + " appears more than once in reference file"); } current = next; } }

Target:
public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) { final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); final SortingCollection<String> sequenceNames = makeSortingCollection(); while (samSequenceRecordIterator.hasNext()) { final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next(); samDictCodec.encodeSequenceRecord(samSequenceRecord); sequenceNames.add(samSequenceRecord.getSequenceName()); } final CloseableIterator<String> iterator = sequenceNames.iterator(); if (!iterator.hasNext()) { return; } String current = iterator.next(); while (iterator.hasNext()) { final String next = iterator.next(); if (current.equals(next)) { throw new PicardException("Sequence name " + current + " appears more than once in reference file"); } current = next; } }
Source:
public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; if (objectNode.hasNonNull("count")) { long count = objectNode.get("count").asLong(); if (count == 0) { return; } if (objectNode.has("max")) { item = getValue(objectNode.get("max")); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) > 0) { this.value = item; } }

Target:
public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; if (objectNode.hasNonNull(MinAggregator.COUNT_PROPERTY_NAME)) { long count = objectNode.get(MinAggregator.COUNT_PROPERTY_NAME).asLong(); if (count == 0) { return; } if (objectNode.has(MAX_PROPERTY_NAME)) { item = getValue(objectNode.get(MAX_PROPERTY_NAME)); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) > 0) { this.value = item; } }
Source:
public void setDiagramScaleLevel(Integer theDiagramScaleLevel) { this.diagramScaleLevel = theDiagramScaleLevel; }

Target:
public void setDiagramScaleLevel(Integer theDiagramScaleLevel) { if (theDiagramScaleLevel < 0 && theDiagramScaleLevel > 100) { throw new IllegalArgumentException(Messages.ExportAction_invalidLevel); } else { this.diagramScaleLevel = theDiagramScaleLevel; } }
Source:
public void postMessage(Direction direction, Tuple update) { Map<Tuple, Integer> activeQueue = getActiveQueue(); Integer count = activeQueue.get(update); if (count == null) { count = 0; } if (direction == Direction.REVOKE) { count--; } else { count++; } if (count == 0) { activeQueue.remove(update); } else { activeQueue.put(update, count); } if (container != null) { if (activeQueue.isEmpty()) { container.getTracker().notifyLostAllMessages(this); } else { container.getTracker().notifyHasMessage(this); } } }

Target:
public void postMessage(Direction direction, Tuple update) { Map<Tuple, Integer> activeQueue = getActiveQueue(); Integer count = activeQueue.get(update); if (count == null) { count = 0; } if (direction == Direction.REVOKE) { count--; } else { count++; } if (count == 0) { activeQueue.remove(update); } else { activeQueue.put(update, count); } if (container != null) { if (activeQueue.isEmpty()) { tracker.notifyLostAllMessages(this); } else { tracker.notifyHasMessage(this); } } }
Source:
public IntegerStateValue(int valueAsInt) { this.value = new Integer(valueAsInt); }

Target:
public IntegerStateValue(int valueAsInt) { this.value = valueAsInt; }
Source:
public void shutdown() { logger.info("Terminating executor health checker."); this.scheduler.shutdown(); try { if (!this.scheduler.awaitTermination(60, TimeUnit.SECONDS)) { this.scheduler.shutdownNow(); } } catch (final InterruptedException ex) { this.scheduler.shutdownNow(); Thread.currentThread().interrupt(); } }

Target:
public void shutdown() { logger.info("Shutting down executor health checker."); this.scheduler.shutdown(); try { if (!this.scheduler.awaitTermination(60, TimeUnit.SECONDS)) { this.scheduler.shutdownNow(); } } catch (final InterruptedException ex) { this.scheduler.shutdownNow(); Thread.currentThread().interrupt(); } }
Source:
public void throttle() { if (log.isDebugEnabled()) { log.debug("try to wait for te engine update the host memory and cpu stats"); } decreaseLock.lock(); try { decreased.await(Config.<Integer> GetValue(ConfigValues.VdsRefreshRate), TimeUnit.SECONDS); } catch (InterruptedException e) { } finally { decreaseLock.unlock(); } }

Target:
public void throttle() { if (log.isDebugEnabled()) { log.debug("try to wait for te engine update the host memory and cpu stats"); } decreaseLock.lock(); try { long t = Math.max( ResourceManager.getInstance().GetVdsManager(getCurrentVdsId()).getLastUpdateElapsed(), TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(VdsRefreshRate))); t = Math.max(Config.<Integer> GetValue(ConfigValues.ThrottlerMaxWaitForVdsUpdateInMillis), t); decreased.await(t, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } finally { decreaseLock.unlock(); } }
Source:
public long getRawSize() throws IOException { if (size() == Integer.MAX_VALUE) { throw new IOException("Unknown block size of at least " + Integer.MAX_VALUE + " bytes."); } return size() & 0x00000000ffffffffL; }

Target:
public long getRawSize() throws IOException { return size() & 0x00000000ffffffffL; }
Source:
public FilterResult isFiltered(StructuralNode node) { HistoryReference href = node.getHistoryReference(); if (href != null) { int statusCode = href.getStatusCode(); return this.isFiltered(statusCode, null); } else { return FilterResult.NOT_FILTERED; } }

Target:
public FilterResult isFiltered(StructuralNode node) { HistoryReference href = node.getHistoryReference(); int statusCode = href.getStatusCode(); return this.isFiltered(statusCode); }
Source:
public boolean isDisplay() { if (displayNetwork == null) return true; else return displayNetwork; }

Target:
public boolean isDisplay() { if (displayNetwork == null) { return true; } else { return displayNetwork; } }
Source:
public static int compareAccessibility(int a, int b) { a = getAccessibility(a); b = getAccessibility(b); if (a == b) { return 0; } switch (a) { case JModifier.PRIVATE: return -1; case JModifier.DEFAULT: return b == JModifier.PRIVATE ? 1 : -1; case JModifier.PROTECTED: return b == JModifier.PUBLIC ? -1 : 1; default: assert a == JModifier.PUBLIC; return 1; } }

Target:
static ComparisonResult compareAccessibility(int a, int b) { a = JModifier.getAccessibility(a); b = JModifier.getAccessibility(b); if (a == b) { return ComparisonResult.EQUAL; } switch (a) { case JModifier.PRIVATE: return ComparisonResult.SECOND_WIDER; case JModifier.DEFAULT: return b == JModifier.PRIVATE ? ComparisonResult.FIRST_WIDER : ComparisonResult.SECOND_WIDER; case JModifier.PROTECTED: return b == JModifier.PUBLIC ? ComparisonResult.SECOND_WIDER : ComparisonResult.FIRST_WIDER; default: assert a == JModifier.PUBLIC; return ComparisonResult.FIRST_WIDER; } }
Source:
public void doPost(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doPOST: Called"); try { if(request.getParameterMap().containsKey("oauth_consumer_key")){ for (Object e : request.getParameterMap().entrySet()) { Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e; String name = entry.getKey(); for (String value : entry.getValue()) { System.out.println(name + " = " + value); } } Properties appExtSecureProperties = SectionUtilityToolFilter.appExtSecurePropertiesFile; if(appExtSecureProperties!=null) { ltiKey = appExtSecureProperties.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_KEY); ltiSecret = appExtSecureProperties.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_SECRET); ltiUrl = props.getString(SectionUtilityToolFilter.PROPERTY_LTI_URL); boolean myRequest = RequestSignatureUtils.verifySignature(request, ltiKey, ltiSecret, ltiUrl); M_log.info("MyRequest: " + myRequest); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); return; } doRequest(request, response); return; } canvasRestApiCall(request, response); }catch(Exception e) { M_log.error("POST request has some exceptions",e); } }

Target:
public void doPost(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doPOST: Called"); try { if(request.getParameterMap().containsKey("oauth_consumer_key")){ processLti(request, response); return; } canvasRestApiCall(request, response); }catch(Exception e) { M_log.error("POST request has some exceptions",e); } }
Source:
private SelectionListener onImportProject(ServerSettingsWizardPageModel model, final Shell shell) { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Map<com.openshift.restclient.model.IProject, Collection<IBuildConfig>> projectsAndBuildConfigs = new HashMap<>(); if (model.getResource() != null) { projectsAndBuildConfigs.put(model.getResource().getProject(), Collections.emptyList()); } ImportApplicationWizard wizard = new ImportApplicationWizard(projectsAndBuildConfigs); final boolean done = WizardUtils.openWizardDialog(wizard, shell); if (done) { model.setDeployProject(ResourcesPlugin.getWorkspace().getRoot().getProject(wizard.getModel().getRepoName())); } } }; }

Target:
private SelectionListener onImportProject(ServerSettingsWizardPageModel model, final Shell shell) { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (model.getResource() == null) { MessageDialog.openWarning(shell, "No Build Configurations found", "A build config is used to import a project to Eclipse"); return; } Map<com.openshift.restclient.model.IProject, Collection<IBuildConfig>> projectsAndBuildConfigs = new HashMap<>(); projectsAndBuildConfigs.put(model.getResource().getProject(), Collections.emptyList()); ImportApplicationWizard wizard = new ImportApplicationWizard(projectsAndBuildConfigs); final boolean done = WizardUtils.openWizardDialog(wizard, shell); if (done) { model.setDeployProject(ResourcesPlugin.getWorkspace().getRoot().getProject(wizard.getModel().getRepoName())); } } }; }
Source:
public CaffeineCache(long maxSize) { final Caffeine<String, Entries> caffeine = Caffeine.newBuilder() .expireAfter(new Expiry<String, Entries>() { @Override public long expireAfterCreate(String key, Entries value, long currentTime) { return TimeUnit.SECONDS.toNanos(value.ttl()); } @Override public long expireAfterUpdate(String key, Entries value, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(String key, Entries value, long currentTime, long currentDuration) { return currentDuration; } }) .recordStats(); if (maxSize > 0) { caffeine.maximumSize(maxSize); } cache = caffeine.build(); }

Target:
public CaffeineCache(long maxSize) { final Caffeine<String, Entries<E>> caffeine = Caffeine.newBuilder() .expireAfter(new Expiry<String, Entries<E>>() { @Override public long expireAfterCreate(String key, Entries<E> value, long currentTime) { return TimeUnit.SECONDS.toNanos(value.ttl()); } @Override public long expireAfterUpdate(String key, Entries<E> value, long currentTime, long currentDuration) { return Math.min(TimeUnit.SECONDS.toNanos(value.ttl()), currentDuration); } @Override public long expireAfterRead(String key, Entries<E> value, long currentTime, long currentDuration) { return currentDuration; } }) .recordStats(); if (maxSize > 0) { caffeine.maximumSize(maxSize); } cache = caffeine.build(); }
Source:
private static void evaluateApplicationInitiatedActionTrigger(final KeycloakSession session, final RequiredActionProvider provider, final RequiredActionProviderModel model, final AuthenticationSessionModel authSession ) { if (provider.initiatedActionSupport() == InitiatedActionSupport.NOT_SUPPORTED) return; String aia = authSession.getClientNote(AIA_REQUEST); if (aia == null) return; if (!aia.equalsIgnoreCase(model.getProviderId())) return; if (session.getContext().getClient().getRole(AccountRoles.INITIATE_ACTION) == null) { logger.error("Client must have initiate-action role to perform application-initiated action."); return; } authSession.addRequiredAction(model.getProviderId()); authSession.removeClientNote(AIA_REQUEST); authSession.setClientNote(IS_AIA_REQUEST, "true"); }

Target:
private static void evaluateApplicationInitiatedActionTrigger(final KeycloakSession session, final RequiredActionProvider provider, final RequiredActionProviderModel model, final AuthenticationSessionModel authSession ) { if (provider.initiatedActionSupport() == InitiatedActionSupport.NOT_SUPPORTED) return; String aia = authSession.getClientNote(AIA_REQUEST); if (aia == null) return; if (!aia.equalsIgnoreCase(model.getProviderId())) return; if (session.getContext().getClient().getRole(AccountRoles.MANAGE_ACCOUNT) == null) { throw new ForbiddenException("Client must have manage-account role to perform application-initiated actions."); } authSession.addRequiredAction(model.getProviderId()); authSession.removeClientNote(AIA_REQUEST); authSession.setClientNote(IS_AIA_REQUEST, "true"); }