auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private RestRule getRuleInternal(String ruleId, User user) { Rule input = getRule(ruleId, user); RestRule restRule = ruleTransform.appToRest(input, user); if(restRule == null) { throw new NotFoundException("Rule not found: '%s'", ruleId); } return restRule; }

Target:
private RestRule getRuleInternal(String ruleId, User user) { Rule input = getRule(ruleId, user); RestRule restRule = ruleTransform.appToRest(input, user); return restRule; }
Source:
public void testClientIsInstrumentedWithTracer() throws InterruptedException { server.enqueue(new MockResponse().setBody("\"server\"")); OpenSpan parentTrace = Tracer.startSpan(""); AtomicInteger called = new AtomicInteger(); Tracer.subscribe(TracerTest.class.getName(), span -> { if (span.type().equals(SpanType.CLIENT_OUTGOING)) { assertThat(span.getOperation(), is("GET /{param}")); } else { assertThat(span.getOperation(), is("acquireLimiter")); } called.getAndIncrement(); }); String traceId = Tracer.getTraceId(); service.param("somevalue"); Tracer.unsubscribe(TracerTest.class.getName()); assertThat(called.intValue(), is(2)); RecordedRequest request = server.takeRequest(); assertThat(request.getHeader(TraceHttpHeaders.TRACE_ID), is(traceId)); assertThat(request.getHeader(TraceHttpHeaders.SPAN_ID), is(not(parentTrace.getSpanId()))); }

Target:
public void testClientIsInstrumentedWithTracer() throws InterruptedException { server.enqueue(new MockResponse().setBody("\"server\"")); OpenSpan parentTrace = Tracer.startSpan(""); List<Map.Entry<SpanType, String>> observedSpans = Lists.newArrayList(); Tracer.subscribe(TracerTest.class.getName(), span -> observedSpans.add(Maps.immutableEntry(span.type(), span.getOperation()))); String traceId = Tracer.getTraceId(); service.param("somevalue"); Tracer.unsubscribe(TracerTest.class.getName()); assertThat(observedSpans, contains( Maps.immutableEntry(SpanType.LOCAL, "acquireLimiter"), Maps.immutableEntry(SpanType.CLIENT_OUTGOING, "GET /{param}"))); RecordedRequest request = server.takeRequest(); assertThat(request.getHeader(TraceHttpHeaders.TRACE_ID), is(traceId)); assertThat(request.getHeader(TraceHttpHeaders.SPAN_ID), is(not(parentTrace.getSpanId()))); }
Source:
protected void handleNoOffsetForPartitionException(NoOffsetForPartitionException e, AbstractKafkaConsumer consumer) { AbstractBaseKafkaInputOperator.InitialOffset io = AbstractBaseKafkaInputOperator.InitialOffset.valueOf(ownerOperator.getInitialOffset()); if (io == AbstractBaseKafkaInputOperator.InitialOffset.APPLICATION_OR_EARLIEST || io == AbstractBaseKafkaInputOperator.InitialOffset.EARLIEST) { consumer.seekToBeginning(e.partitions().toArray(new TopicPartition[0])); } else { consumer.seekToEnd(e.partitions().toArray(new TopicPartition[0])); } }

Target:
protected void handleNoOffsetForPartitionException(NoOffsetForPartitionException e, AbstractKafkaConsumer consumer) { AbstractKafkaInputOperator.InitialOffset io = AbstractKafkaInputOperator.InitialOffset.valueOf(ownerOperator.getInitialOffset()); if (io == AbstractKafkaInputOperator.InitialOffset.APPLICATION_OR_EARLIEST || io == AbstractKafkaInputOperator.InitialOffset.EARLIEST) { consumer.seekToBeginning(e.partitions().toArray(new TopicPartition[0])); } else { consumer.seekToEnd(e.partitions().toArray(new TopicPartition[0])); } }
Source:
void submitSharingAccount() { if (Network.isOnline(getContext())) { SharingPayload sharingPayload = new SharingPayload(); sharingPayload.setExternalId(etClientExternalId.getEditableText().toString()); sharingPayload.setLocale("en"); sharingPayload.setSubmittedDate(submissionDate); sharingPayload.setDateFormat("dd MMMM yyyy"); sharingPayload.setClientId(clientId); sharingPayload.setProductId(productId); sharingPayload.setRequestedShares(Integer.parseInt(etRequestedShares. getEditableText().toString())); sharingPayload.setMinimumActivePeriod(etMinActivePeriod.getEditableText() .toString()); sharingPayload.setMinimumActivePeriodFrequencyType(minActivePeriodId); sharingPayload.setLockinPeriodFrequency(etLockinPeriod. getEditableText().toString()); sharingPayload.setLockinPeriodFrequencyType(lockinPeriodId); sharingPayload.setApplicationDate(applicationDate); sharingPayload.setAllowDividendCalculationForInactiveClients(isAllowDividend); sharingPayload.setSavingsAccountId(savingId); List<ChargeOptions> chargeOptionsList = shareChargesAdapter.getChargeOptionList(); List<ShareChargePayload> shareChargePayloadList = new ArrayList<ShareChargePayload>(); for (ChargeOptions chargeOptions : chargeOptionsList) { shareChargePayloadList.add(new ShareChargePayload(chargeOptions.getId(), chargeOptions.getAmount())); } sharingPayload.setChargePayload(shareChargePayloadList); mSharingAccountPresenter.createSharingAccount(sharingPayload); } else { Toaster.show(rootView, R.string.error_network_not_available); } }

Target:
void submitSharingAccount() { if (Network.isOnline(getActivity())) { SharingPayload sharingPayload = new SharingPayload(); sharingPayload.setExternalId(etClientExternalId.getEditableText().toString()); sharingPayload.setLocale("en"); sharingPayload.setSubmittedDate(submissionDate); sharingPayload.setDateFormat("dd MMMM yyyy"); sharingPayload.setClientId(clientId); sharingPayload.setProductId(productId); sharingPayload.setRequestedShares(Integer.parseInt(etRequestedShares. getEditableText().toString())); sharingPayload.setMinimumActivePeriod(etMinActivePeriod.getEditableText() .toString()); sharingPayload.setMinimumActivePeriodFrequencyType(minActivePeriodId); sharingPayload.setLockinPeriodFrequency(etLockinPeriod. getEditableText().toString()); sharingPayload.setLockinPeriodFrequencyType(lockinPeriodId); sharingPayload.setApplicationDate(applicationDate); sharingPayload.setAllowDividendCalculationForInactiveClients(isAllowDividend); sharingPayload.setSavingsAccountId(savingId); List<ShareChargePayload> shareChargePayloadList = new ArrayList<ShareChargePayload>(); for (ChargeOptions chargeOptions : chargeOptionAdapterList) { shareChargePayloadList.add(new ShareChargePayload(chargeOptions.getId(), chargeOptions.getAmount())); } sharingPayload.setChargePayload(shareChargePayloadList); mSharingAccountPresenter.createSharingAccount(sharingPayload); } else { Toaster.show(rootView, R.string.error_network_not_available); } }
Source:
protected <T extends Projectile> T launchProjectile(Class<? extends T> type, Location location, Vector originalVector, float pitchOffset, float velocity) { double negDegreesPerRadian = Math.toRadians(-1); double x = cos(negDegreesPerRadian * location.getPitch()) * sin(negDegreesPerRadian * location.getYaw()); double y = sin(negDegreesPerRadian * (location.getPitch() - pitchOffset)); double z = cos(location.getPitch() * negDegreesPerRadian) * cos(location.getYaw() * negDegreesPerRadian); T projectile = launchProjectile(type, location, x, y, z, velocity); projectile.getVelocity().add(originalVector); return projectile; }

Target:
protected <T extends Projectile> T launchProjectile(Class<? extends T> type, Location location, Vector originalVector, float pitchOffset, float velocity) { double pitchRadians = Math.toRadians(location.getPitch()); double yawRadians = Math.toRadians(location.getYaw()); double verticalMultiplier = cos(pitchRadians); double x = verticalMultiplier * sin(-yawRadians); double z = verticalMultiplier * cos(yawRadians); double y = sin(-(Math.toRadians(location.getPitch() - pitchOffset))); T projectile = launchProjectile(type, location, x, y, z, velocity); projectile.getVelocity().add(originalVector); return projectile; }
Source:
public void testDuplicatesInWindowOrderBy() throws Exception { ExpectedValueProvider<WindowNode.Specification> specification = specification( ImmutableList.of(), ImmutableList.of("A"), ImmutableMap.of("A", SortOrder.ASC_NULLS_LAST)); assertUnitPlan("WITH x as (SELECT a, a as b FROM (VALUES 1) t(a))" + "SELECT *, row_number() OVER(ORDER BY a ASC, b DESC)" + "FROM x", anyTree( window(windowMatcherBuilder -> windowMatcherBuilder .specification(specification) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), values(ImmutableMap.of("A", 0))) )); }

Target:
public void testDuplicatesInWindowOrderBy() throws Exception { ExpectedValueProvider<WindowNode.Specification> specification = specification( ImmutableList.of(), ImmutableList.of("A"), ImmutableMap.of("A", SortOrder.ASC_NULLS_LAST)); assertUnitPlan("WITH x as (SELECT a, a as b FROM (VALUES 1) t(a))" + "SELECT *, row_number() OVER(ORDER BY a ASC, b DESC)" + "FROM x", anyTree( window(windowMatcherBuilder -> windowMatcherBuilder .specification(specification) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), values("A")))); }
Source:
public String toString() { return getName(); }

Target:
public String toString() { return CommonHelper.toString(this.getClass(), "profiles", getProfiles()); }
Source:
protected EmbeddedMysql(final MysqldConfig config) { logger.info("Preparing EmbeddedMysql version '{}'...", config.getVersion()); this.config = config; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(config.getVersion()).build(); lock.lock(); try { this.executable = new MysqldStarter(runtimeConfig).prepare(config); } finally { lock.unlock(); } try { executable.start(); getClient(SCHEMA).executeCommands( format("CREATE USER '%s'@'%%' IDENTIFIED BY '%s';", config.getUsername(), config.getPassword())); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
protected EmbeddedMysql(final MysqldConfig config) { logger.info("Preparing EmbeddedMysql version '{}'...", config.getVersion()); this.config = config; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(config.getVersion()).build(); MysqldStarter mysqldStarter = new MysqldStarter(runtimeConfig); localRepository.lock(); try { this.executable = mysqldStarter.prepare(config); } finally { localRepository.unlock(); } try { executable.start(); getClient(SCHEMA).executeCommands( format("CREATE USER '%s'@'%%' IDENTIFIED BY '%s';", config.getUsername(), config.getPassword())); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
private boolean isStackOrClusterStatusFailed(Status status) { return (Status.BACKUP_FAILED.equals(status) || Status.RESTORE_FAILED.equals(status)) ? true : false; }

Target:
private boolean isStackOrClusterStatusFailed(Status status) { return Status.BACKUP_FAILED.equals(status) || Status.RESTORE_FAILED.equals(status); }
Source:
public SecretBoxOpener(byte[] key) { checkNotNull(key, "null key passed"); checkArgument(key.length == 32, "key should be 32B, is: " + key.length + "B"); this.key = key; }

Target:
public SecretBoxOpener(byte[] key) { checkNotNull(key, "null key passed"); checkArgument(key.length == 32, "key length must be 32 bytes, but is " + key.length + " bytes"); this.key = key; }
Source:
void run() throws Throwable; } public static Throwable expectThrows(ThrowingRunnable runnable) { return expectThrows(null, runnable); }

Target:
void run() throws Throwable; } public static void assertThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) { expectThrows(expectedThrowable, runnable); }
Source:
protected Response performRemove(String id) { return null; }

Target:
protected Response performRemove(String id) { throw new UnsupportedOperationException(); }
Source:
private void validateAddTaskConfigs(String workflowName, String jobName, TaskConfig taskConfig) { WorkflowConfig workflowConfig = TaskUtil.getWorkflowConfig(_accessor, workflowName); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); JobConfig jobConfig = TaskUtil.getJobConfig(_accessor, nameSpaceJobName); if (workflowConfig == null) { throw new IllegalArgumentException( String.format("Workflow config for workflow %s does not exist!", workflowName)); } if (jobConfig == null) { throw new IllegalArgumentException( String.format("Job config for job %s does not exist!", nameSpaceJobName)); } if (taskConfig == null) { throw new IllegalArgumentException("TaskConfig is null!"); } if (taskConfig.getId() == null) { throw new HelixException("Task cannot be added because taskID is null!"); } if (jobConfig.getTargetResource() != null) { throw new HelixException(String.format( "Job %s is a targeted job. New task cannot be added to this job!", nameSpaceJobName)); } if (taskConfig.getCommand() == null && jobConfig.getCommand() == null) { throw new HelixException( "Task cannot be added because both of the job and task have null command!"); } if (taskConfig.getCommand() != null && jobConfig.getCommand() != null) { throw new HelixException( "Task cannot be added because command existed for both of job and task!"); } for (String taskEntry : jobConfig.getMapConfigs().keySet()) { if (taskEntry.equals(taskConfig.getId())) { throw new HelixException( "Task cannot be added because another task with the same ID already exists!"); } } }

Target:
private void validateAddTaskConfigs(String workflowName, String jobName, TaskConfig taskConfig) { WorkflowConfig workflowConfig = TaskUtil.getWorkflowConfig(_accessor, workflowName); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); JobConfig jobConfig = TaskUtil.getJobConfig(_accessor, nameSpaceJobName); if (workflowConfig == null) { throw new IllegalArgumentException( String.format("Workflow config for workflow %s does not exist!", workflowName)); } if (jobConfig == null) { throw new IllegalArgumentException( String.format("Job config for job %s does not exist!", nameSpaceJobName)); } if (taskConfig == null) { throw new IllegalArgumentException("TaskConfig is null!"); } if (taskConfig.getId() == null) { throw new HelixException("Task cannot be added because taskID is null!"); } if (jobConfig.getTargetResource() != null) { throw new HelixException(String.format( "Job %s is a targeted job. New task cannot be added to this job!", nameSpaceJobName)); } if ((taskConfig.getCommand() == null) == (jobConfig.getCommand() == null)) { throw new HelixException("Command must exist in either job or task, not both!"); } for (String taskEntry : jobConfig.getMapConfigs().keySet()) { if (taskEntry.equals(taskConfig.getId())) { throw new HelixException( "Task cannot be added because another task with the same ID already exists!"); } } }
Source:
public void onAssignmentChange(List<DatastreamTask> tasks) { _logger.info("onAssignmentChange called with tasks {}", tasks); HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { AbstractKafkaBasedConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { AbstractKafkaBasedConnectorTask kafkaBasedConnectorTask = _runningTasks.get(task); if (kafkaBasedConnectorTask != null) { kafkaBasedConnectorTask.checkAndUpdateTask(task); _runningTasks.remove(task); _runningTasks.put(task, kafkaBasedConnectorTask); continue; } _logger.info("creating task for {}.", task); AbstractKafkaBasedConnectorTask connectorTask = createKafkaBasedConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }

Target:
public void onAssignmentChange(List<DatastreamTask> tasks) { _logger.info("onAssignmentChange called with tasks {}", tasks); HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { AbstractKafkaBasedConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { AbstractKafkaBasedConnectorTask kafkaBasedConnectorTask = _runningTasks.get(task); if (kafkaBasedConnectorTask != null) { kafkaBasedConnectorTask.checkForUpdateTask(task); _runningTasks.put(task, kafkaBasedConnectorTask); continue; } _logger.info("creating task for {}.", task); AbstractKafkaBasedConnectorTask connectorTask = createKafkaBasedConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }
Source:
public List<ArtifactId> getBranchViewsForApplicability(BranchId branch, ApplicabilityId applId) { List<ArtifactId> arts = new ArrayList<>(); for (Iterator<Long> iterator = queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId()).iterator(); iterator.hasNext();) { Long long1 = iterator.next(); arts.add(ArtifactId.valueOf(long1)); } return arts; }

Target:
public List<ArtifactId> getBranchViewsForApplicability(BranchId branch, ApplicabilityId applId) { List<ArtifactId> arts = new ArrayList<>(); for (Long long1 : queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId())) { arts.add(ArtifactId.valueOf(long1)); } return arts; }
Source:
static double convertTimeUnit(final double valueFrom, final TimeUnit unitFrom, final TimeUnit unitTo) { if (unitFrom.ordinal() < unitTo.ordinal()) { return valueFrom / unitFrom.convert(1, unitTo); } else { return valueFrom * unitTo.convert(1, unitFrom); } }

Target:
static double convertTimeUnit(final double valueFrom, final TimeUnit unitFrom, final TimeUnit unitTo) { final long conversionRateTo = unitTo.convert(1, unitFrom); if (conversionRateTo == 0) { return valueFrom / unitFrom.convert(1, unitTo); } return valueFrom * conversionRateTo; }
Source:
public void finish() { String shellText = new DefaultShell().getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsActive(shellText)); }

Target:
public void finish() { String shellText = new DefaultShell().getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(shellText)); }
Source:
@Override public E peek() { lock.lock(); try { if (queue.isEmpty()) { return null; } return queue.peek(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return null; } finally { lock.unlock(); } }

Target:
@Override public E peek() { lock.lock(); try { return queue.peek(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
protected static String performInstanceDataMatching(final QName infrastructureNodeType, final Map<String, String> infrastructureProperties) { if (infrastructureNodeType != null) { final Set<Entry<String, String>> infrastructureEntrySet = getEntrySetWithoutState(infrastructureProperties); final NodeTemplateInstance matchingInstance = nodeTemplateInstanceRepository.findByTemplateType(infrastructureNodeType).stream() .filter((instance) -> instance.getServiceTemplateInstance().getState() .equals(ServiceTemplateInstanceState.CREATED)) .filter((instance) -> instance.getState() .equals(NodeTemplateInstanceState.STARTED)) .filter((instance) -> isBuildPlanFinished(instance)) .filter((instance) -> getEntrySetWithoutState(instance.getPropertiesAsMap()).equals(infrastructureEntrySet)) .findFirst().orElse(null); if (matchingInstance != null) { if (matchingInstance.getManagingContainer() == null) { return Settings.OPENTOSCA_CONTAINER_HOSTNAME; } else { return matchingInstance.getManagingContainer(); } } } return null; }

Target:
protected static String performInstanceDataMatching(final QName infrastructureNodeType, final Map<String, String> infrastructureProperties) { Objects.requireNonNull(infrastructureNodeType, "QName for NodeType of infrastructure node must not be null for instance data matching"); final Set<Entry<String, String>> infrastructureEntrySet = getEntrySetWithoutState(infrastructureProperties); final NodeTemplateInstance matchingInstance = nodeTemplateInstanceRepository.findByTemplateType(infrastructureNodeType).stream() .filter(instance -> instance.getServiceTemplateInstance().getState() .equals(ServiceTemplateInstanceState.CREATED)) .filter(instance -> instance.getState() .equals(NodeTemplateInstanceState.STARTED)) .filter(instance -> isBuildPlanFinished(instance)) .filter(instance -> getEntrySetWithoutState(instance.getPropertiesAsMap()).equals(infrastructureEntrySet)) .findFirst().orElse(null); if (Objects.nonNull(matchingInstance)) { if (Objects.isNull(matchingInstance.getManagingContainer())) { return Settings.OPENTOSCA_CONTAINER_HOSTNAME; } else { return matchingInstance.getManagingContainer(); } } return null; }
Source:
private CompletableFuture<Layout> getLatestLayout(List<String> layoutServers) { CompletableFuture<Layout> latestLayoutFuture = null; long latestEpoch = -1; List<CompletableFuture<Layout>> layoutFutures = new ArrayList<>(); for (String layoutServer : layoutServers) { try { log.debug("Trying to connect to layout server: {}", layoutServer); IClientRouter router = getRouter(layoutServer); CompletableFuture<Layout> layoutFuture = new LayoutClient(router, Layout.INVALID_EPOCH).getLayout(); layoutFutures.add(layoutFuture); } catch (Exception ex) { log.warn("Tried to connect to layoutServer but failed with exception:", layoutServer, ex); } } for (CompletableFuture<Layout> layoutFuture : layoutFutures) { try { Layout l = layoutFuture.get(); if (l.getEpoch() > latestEpoch) { latestEpoch = l.getEpoch(); latestLayoutFuture = layoutFuture; } } catch (Exception e) { log.warn("Tried to get layout from server but failed with exception:", layoutFuture, e); } } if (latestLayoutFuture == null) { latestLayoutFuture = new CompletableFuture<>(); latestLayoutFuture.completeExceptionally( new Exception("Could not fetch layout from any of the layout servers.")); } return latestLayoutFuture; }

Target:
private Layout getLatestLayout(List<String> layoutServers) { long latestEpoch = -1; Layout latestLayout = null; int quorum = (layoutServers.size() / 2) + 1; CompletableFuture<Layout>[] layoutFutures = new CompletableFuture[layoutServers.size()]; for(int i = 0; i < layoutServers.size(); i++) { try { log.debug("Trying to connect to layout server: {}", layoutServers.get(i)); IClientRouter router = getRouter(layoutServers.get(i)); CompletableFuture<Layout> layoutFuture = new LayoutClient(router, Layout.INVALID_EPOCH).getLayout(); layoutFutures[i] = layoutFuture; } catch (Exception ex) { CompletableFuture<Layout> future = new CompletableFuture<Layout>(); future.completeExceptionally(ex); layoutFutures[i] = future; } } int responseCount = 0; for(int i = 0; i < layoutFutures.length; i++) { try { Layout l = (Layout) CompletableFuture.anyOf(layoutFutures).get(); responseCount++; if (l.getEpoch() > latestEpoch) { latestEpoch = l.getEpoch(); latestLayout = l; } if(responseCount >= quorum) { return latestLayout; } }catch(Exception ex) { log.warn("Tried to get layout from server but failed with exception:{}", layoutServers.get(i), ex); } } return latestLayout; }
Source:
public void testValidationDomainClass() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int rand = 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { editDomainClassValue(current, attribute, rand); if (rand < 3) { rand++; } else { rand = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is not valid, it should have popup error message", Diagnostic.ERROR, diagnostic.getSeverity()); }

Target:
public void testValidationDomainClass() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int i = 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { editDomainClassValue(current, attribute, i); if (i < 3) { i++; } else { i = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is not valid, it should have popup error message", Diagnostic.ERROR, diagnostic.getSeverity()); }
Source:
public void writeObject(ObjectOutput output, CompositeKeyFilter object) throws IOException { output.writeInt(object.filters.length); for (KeyFilter filter : object.filters) { output.writeObject(filter); } }

Target:
public void writeObject(ObjectOutput output, CompositeKeyFilter object) throws IOException { UnsignedNumeric.writeUnsignedInt(output, object.filters.length); for (KeyFilter filter : object.filters) { output.writeObject(filter); } }
Source:
protected void modified(Map<String, Object> config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.error("Invalid configuration value: {}. It MUST be Number.", value); } }

Target:
protected void modified(Map<String, Object> config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } }
Source:
public ProjectQualityGate getQualityGate52() throws Exception { String url = serverUrl + API_PROJECT_STATUS + "?projectKey=" + projectKey; String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); JSONObject projectStatus = json.getJSONObject("projectStatus"); String status = projectStatus.getString("status"); String projectName = getProjectName(); return new ProjectQualityGate(projectName, status); }

Target:
public ProjectQualityGate getQualityGate52() throws Exception { String url = serverUrl + API_PROJECT_STATUS + encode(projectKey); String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); JSONObject projectStatus = json.getJSONObject("projectStatus"); String status = projectStatus.getString("status"); String projectName = getProjectName(); return new ProjectQualityGate(projectName, status); }
Source:
public static void main(String[] args) throws IOException, TimeoutException, TException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ConnectionFactory cf = new ConnectionFactory(ConnectionFactory.DEFAULT_URL); Connection conn = cf.createConnection(); FTransport transport = new FNatsTransport(conn, NatsServer.SERVICE_SUBJECT); transport.open(); FStore.Client storeClient = new FStore.Client(transport, protocolFactory); FContext context = new FContext(); context.setTimeout(1000); Album album = storeClient.buyAlbum(context, "ASIN-1290AIUBOA89", "ACCOUNT-12345"); System.out.println("Bought the album: " + album); storeClient.enterAlbumGiveaway(context, "kevin@workiva.com", "Kevin"); transport.close(); conn.close(); }

Target:
public static void main(String[] args) throws IOException, TimeoutException, TException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ConnectionFactory cf = new ConnectionFactory(ConnectionFactory.DEFAULT_URL); Connection conn = cf.createConnection(); FTransport transport = new FNatsTransport(conn, NatsServer.SERVICE_SUBJECT); transport.open(); FStore.Client storeClient = new FStore.Client(transport, protocolFactory); Album album = storeClient.buyAlbum(new FContext("corr-id-1"), "ASIN-1290AIUBOA89", "ACCOUNT-12345"); System.out.println("Bought the album: " + album); storeClient.enterAlbumGiveaway(new FContext("corr-id-2"), "kevin@workiva.com", "Kevin"); transport.close(); conn.close(); }
Source:
public void shutdown() { fListeners = new ListenerList<>(); fLaunchesListeners = new ListenerList<>(); fLaunchConfigurationListeners = new ListenerList<>(); ILaunch[] launches = getLaunches(); ILaunch launch = null; for (ILaunch launche : launches) { launch = launche; if(launch != null) { try { if (launch instanceof IDisconnect) { IDisconnect disconnect = (IDisconnect)launch; if (disconnect.canDisconnect()) { disconnect.disconnect(); } } if (launch.canTerminate()) { launch.terminate(); } } catch (DebugException e) { DebugPlugin.log(e); } } } persistPreferredLaunchDelegates(); clearAllLaunchConfigurations(); fStepFilterManager = null; ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); }

Target:
public void shutdown() { fListeners = new ListenerList<>(); fLaunchesListeners = new ListenerList<>(); fLaunchConfigurationListeners = new ListenerList<>(); for (ILaunch launch : getLaunches()) { if(launch != null) { try { if (launch instanceof IDisconnect) { IDisconnect disconnect = (IDisconnect)launch; if (disconnect.canDisconnect()) { disconnect.disconnect(); } } if (launch.canTerminate()) { launch.terminate(); } } catch (DebugException e) { DebugPlugin.log(e); } } } persistPreferredLaunchDelegates(); clearAllLaunchConfigurations(); fStepFilterManager = null; ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); }
Source:
public long reload() { Long adjustedValue = jdbcTemplate.queryForObject(adjustedValueQuery, Long.class); if (adjustedValue == null) { adjustedValue = cachedAdjustedValue.get(); logger.warn("adjusted value is null. use {}", adjustedValue); } else if (isUseCache()) { logger.debug("cache adjustd value = {}", adjustedValue); cachedAdjustedValue.set(adjustedValue); } return adjustedValue; }

Target:
public long reload() { Long adjustedValue = jdbcTemplate.queryForObject(adjustedValueQuery, Long.class); if (adjustedValue == null) { adjustedValue = cachedAdjustedValue.get(); logger.warn("adjusted value is null. use {}", adjustedValue); } else if (isUseCache()) { logger.debug("cache adjusted value = {}", adjustedValue); cachedAdjustedValue.set(adjustedValue); } return adjustedValue; }
Source:
private JSONObject updateContainers(JSONObject containersPayload) throws RestServiceException { Short accountId = RestUtils.getNumericalHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_ID, false, Short::parseShort); String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, false); if (accountId == null && accountName == null) { throw new RestServiceException("Missing required header: " + RestUtils.Headers.TARGET_ACCOUNT_NAME, RestServiceErrorCode.BadRequest); } Account account = accountName != null ? accountService.getAccountByName(accountName) : accountService.getAccountById(accountId); if (account == null) { throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.BadRequest); } accountId = account.getId(); accountName = account.getName(); Collection<Container> containersToUpdate; try { containersToUpdate = AccountCollectionSerde.containersFromJson(containersPayload, accountId); } catch (JSONException e) { throw new RestServiceException("Bad container update request body", e, RestServiceErrorCode.BadRequest); } try { Collection<Container> updatedContainers = accountService.updateContainers(accountName, containersToUpdate); return AccountCollectionSerde.containersToJson(updatedContainers); } catch (AccountServiceException ex) { throw new RestServiceException("Container update failed for accountId " + accountId, RestServiceErrorCode.BadRequest); } }

Target:
private JSONObject updateContainers(JSONObject containersPayload) throws RestServiceException { Short accountId = RestUtils.getNumericalHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_ID, false, Short::parseShort); String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, false); if (accountId == null && accountName == null) { throw new RestServiceException("Missing required header: " + RestUtils.Headers.TARGET_ACCOUNT_NAME, RestServiceErrorCode.BadRequest); } Account account = accountName != null ? accountService.getAccountByName(accountName) : accountService.getAccountById(accountId); if (account == null) { throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound); } accountId = account.getId(); accountName = account.getName(); Collection<Container> containersToUpdate; try { containersToUpdate = AccountCollectionSerde.containersFromJson(containersPayload, accountId); } catch (JSONException e) { throw new RestServiceException("Bad container update request body", e, RestServiceErrorCode.BadRequest); } try { Collection<Container> updatedContainers = accountService.updateContainers(accountName, containersToUpdate); return AccountCollectionSerde.containersToJson(updatedContainers); } catch (AccountServiceException ex) { throw new RestServiceException("Container update failed for accountId " + accountId, RestServiceErrorCode.getRestServiceErrorCode(ex.getErrorCode())); } }
Source:
public void drawGridLines(Rectangle bounds, GC gc) { if (!fGridLinesVisible) { return; } gc.setForeground(fGridLineColor); gc.setAlpha(fGridLineColor.getAlpha()); for (int x : fTimeGraphScale.getTickList()) { gc.drawLine(x, bounds.y, x, bounds.y + bounds.height); } gc.setAlpha(BLACK.getAlpha()); }

Target:
public void drawGridLines(Rectangle bounds, GC gc) { if (!fGridLinesVisible) { return; } gc.setForeground(fGridLineColor); gc.setAlpha(fGridLineColor.getAlpha()); for (int x : fTimeGraphScale.getTickList()) { gc.drawLine(x, bounds.y, x, bounds.y + bounds.height); } gc.setAlpha(OPAQUE); }
Source:
private static Version parseBuiltInMetricsVersion(final String builtInMetricsVersion) { if (builtInMetricsVersion.equals("latest")) { return Version.LATEST; } else { return Version.FROM_100_TO_23; } }

Target:
private static Version parseBuiltInMetricsVersion(final String builtInMetricsVersion) { if (builtInMetricsVersion.equals(StreamsMetricsImpl.METRICS_LATEST)) { return Version.LATEST; } else { return Version.FROM_100_TO_23; } }
Source:
GoogleAnalyticsNavigationTracker( @GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; if (GWT.isScript()) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); } }

Target:
GoogleAnalyticsNavigationTracker(@GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); }
Source:
public void deleteDefaultReadGroups(Collection collection) throws Exception { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Group defaultItemReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_ITEM_DEFAULT_READ"); Group defaultBitstreamReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_BITSTREAM_DEFAULT_READ"); if (defaultItemReadGroup != null) { groupService.delete(c, defaultItemReadGroup); } if (defaultBitstreamReadGroup != null) { groupService.delete(c, defaultBitstreamReadGroup); } c.complete(); } indexingService.commit(); }

Target:
public void deleteDefaultReadGroups(Collection collection) throws Exception { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Group defaultItemReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_ITEM_DEFAULT_READ"); Group defaultBitstreamReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_BITSTREAM_DEFAULT_READ"); if (defaultItemReadGroup != null) { groupService.delete(c, defaultItemReadGroup); } if (defaultBitstreamReadGroup != null) { groupService.delete(c, defaultBitstreamReadGroup); } c.complete(); } }
Source:
public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { if (alreadyVisited) { return true; } clearNodeFromTeststyleProblem(node); for (BaseCheck chk : ProblemCont.instance.getChecksFor(node)) { int severity = getIntForSeverity(chk.getSeverity()); String message = chk.getDescription(); if (severity > IStatus.INFO) { node.addProblem(ProblemFactory.createProblem( new Status(severity, Activator.PLUGIN_ID, message))); } } if (node instanceof IExecTestCasePO) { IExecTestCasePO execTestCase = (IExecTestCasePO) node; handleExecTestCase(execTestCase); } return true; }

Target:
public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { clearNodeFromTeststyleProblem(node); for (BaseCheck chk : ProblemCont.instance.getChecksFor(node)) { int severity = getIntForSeverity(chk.getSeverity()); String message = chk.getDescription(); if (severity > IStatus.INFO) { node.addProblem(ProblemFactory.createProblem( new Status(severity, Activator.PLUGIN_ID, message))); } } if (node instanceof IExecTestCasePO) { IExecTestCasePO execTestCase = (IExecTestCasePO) node; handleExecTestCase(execTestCase); } return true; }
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.get(); if (json.has("primaryView")) { final String viewName = json.getString("primaryView"); final View newPrimaryView = j.getView(viewName); if (newPrimaryView == null) { throw new FormException(Messages.GlobalDefaultViewConfiguration_ViewDoesNotExist(viewName), "primaryView"); } j.setPrimaryView(newPrimaryView); } else { if(j.getViews().iterator().hasNext()) { j.setPrimaryView(j.getViews().iterator().next()); } } return true; }

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.get(); if (json.has("primaryView")) { final String viewName = json.getString("primaryView"); final View newPrimaryView = j.getView(viewName); if (newPrimaryView == null) { throw new FormException(Messages.GlobalDefaultViewConfiguration_ViewDoesNotExist(viewName), "primaryView"); } j.setPrimaryView(newPrimaryView); } else { Iterator<View> iter = j.getViews().iterator(); if(iter.hasNext()) { j.setPrimaryView(iter.next()); } } return true; }
Source:
protected void initializeExtraSubystemsAndModel(ExtensionRegistry registry, Resource root, ManagementResourceRegistration registration, RuntimeCapabilityRegistry capabilityRegistry) { List<String> list = new ArrayList<>(); for (String requirement : this.requirements) { list.add(requirement); } registerCapabilities(capabilityRegistry, list.toArray(new String[0])); }

Target:
protected void initializeExtraSubystemsAndModel(ExtensionRegistry registry, Resource root, ManagementResourceRegistration registration, RuntimeCapabilityRegistry capabilityRegistry) { registerCapabilities(capabilityRegistry, this.requirements.stream().toArray(String[]::new)); }
Source:
public DoubleStream stream() { return Arrays.stream(elements); }

Target:
public DoubleStream stream() { int effectiveSize = Math.min(count, samples.length); return Arrays.stream(samples, 0, effectiveSize); }
Source:
public MesosCluster(String clusterId) { this.clusterId = clusterId; List<Container> containers = dockerClient.listContainersCmd().exec(); Collections.sort(containers, (c1,c2) -> Long.compare(c1.getCreated(), c2.getCreated())); for (Container container : containers) { for (String name : container.getNames()) { if (name.matches("^/minimesos-.+-" + clusterId + "-\\d+$")) { String[] parts = name.split("-"); String role = parts[1]; String uuid = parts[3]; switch (role) { case "zookeeper": this.containers.add(new ZooKeeper(dockerClient, clusterId, uuid)); break; case "agent": this.containers.add(new MesosSlave(dockerClient, clusterId, uuid)); break; case "master": this.containers.add(new MesosMaster(dockerClient, clusterId, uuid)); break; case "marathon": this.containers.add(new Marathon(dockerClient, clusterId, uuid)); } break; } } } if (containers.isEmpty()) { throw new RuntimeException("No containers found for cluster ID " + clusterId); } if (getZkContainer() != null) { for (MesosSlave mesosSlave : getSlaves()) { mesosSlave.setZooKeeperContainer(getZkContainer()); } getMesosMasterContainer().setZooKeeperContainer(getZkContainer()); getMarathonContainer().setZooKeeper(getZkContainer()); } }

Target:
private MesosCluster(String clusterId) { this.clusterId = clusterId; List<Container> containers = dockerClient.listContainersCmd().exec(); Collections.sort(containers, (c1,c2) -> Long.compare(c1.getCreated(), c2.getCreated())); ZooKeeper zkKeeper = null; for (Container container : containers) { String name = ContainerName.getFromDockerNames(container.getNames()); if (ContainerName.belongsToCluster(name, clusterId)) { String containerId = container.getId(); String[] parts = name.split("-"); String role = parts[1]; String uuid = parts[3]; switch (role) { case "zookeeper": zkKeeper = new ZooKeeper(dockerClient, clusterId, uuid, containerId); this.containers.add(zkKeeper); break; case "agent": this.containers.add(new MesosSlave(dockerClient, clusterId, uuid, containerId)); break; case "master": this.containers.add(new MesosMaster(dockerClient, clusterId, uuid, containerId)); break; case "marathon": this.containers.add(new Marathon(dockerClient, clusterId, uuid, containerId)); break; } } } if (containers.isEmpty()) { throw new RuntimeException("No containers found for cluster ID " + clusterId); } if (zkKeeper != null) { for (MesosSlave mesosSlave : getSlaves()) { mesosSlave.setZooKeeperContainer(zkKeeper); } getMasterContainer().setZooKeeperContainer(zkKeeper); getMarathonContainer().setZooKeeper(zkKeeper); } }
Source:
public void testOptions() throws Exception { mockMvc.perform(get("/tasks/ctr/options").accept(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.id == 'oauth2-client-credentials-scopes')].name", hasItems("oauth2-client-credentials-scopes"))); }

Target:
public void testOptions() throws Exception { mockMvc.perform(get("/tasks/ctr/options").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.id == 'oauth2-client-credentials-scopes')].name", hasItems("oauth2-client-credentials-scopes"))); }
Source:
public Mono<Void> runAsync() { return receiverAsync .receiveMessages() .map(messageContext -> { return messageContext; }) .take(options.getMessagesToReceive()) .then(); }

Target:
public Mono<Void> runAsync() { return receiverAsync .receiveMessages() .take(options.getMessagesToReceive()) .map(serviceBusReceivedMessageContext -> { return serviceBusReceivedMessageContext; }).then(); }
Source:
private void processBufferWindow( List<RowMetaAndData> list ) { if ( isProcessing.compareAndSet( false, true ) ) { if ( this.fallbackSubject != null ) { this.fallbackSubject.dispose(); this.fallbackSubject = this.fallbackBuffer.subscribe( bufferList -> processFallbackWindow( bufferList ) ); } hasWindow.compareAndSet( false, true ); unSubscribeStarter(); setCacheWindow( list ); isProcessing.compareAndSet( true, false ); } }

Target:
private void processBufferWindow( List<RowMetaAndData> list ) { if ( isProcessing.compareAndSet( false, true ) ) { if ( this.fallbackSubject != null ) { this.fallbackSubject.dispose(); this.fallbackSubject = this.fallbackBuffer.subscribe( bufferList -> processFallbackWindow( bufferList ) ); } hasWindow.set( true ); unSubscribeStarter(); setCacheWindow( list ); isProcessing.set( false ); } }
Source:
public void create(String namespace) throws AccumuloException, AccumuloSecurityException, NamespaceExistsException { checkArgument(namespace != null, "namespace is null"); checkArgument(namespace.length() <= MAX_NAMESPACE_LEN, "Namespace is longer than 1024 characters"); try { doNamespaceFateOperation(FateOperation.NAMESPACE_CREATE, Arrays.asList(ByteBuffer.wrap(namespace.getBytes(UTF_8))), Collections.emptyMap(), namespace); } catch (NamespaceNotFoundException e) { throw new AssertionError(e); } }

Target:
public void create(String namespace) throws AccumuloException, AccumuloSecurityException, NamespaceExistsException { checkArgument(namespace != null, "namespace is null"); checkArgument(namespace.length() <= MAX_NAMESPACE_LEN, "Namespace is longer than " + MAX_NAMESPACE_LEN + " characters"); try { doNamespaceFateOperation(FateOperation.NAMESPACE_CREATE, Arrays.asList(ByteBuffer.wrap(namespace.getBytes(UTF_8))), Collections.emptyMap(), namespace); } catch (NamespaceNotFoundException e) { throw new AssertionError(e); } }
Source:
public void visit(QueryMetadata.Builder queryBuilder) { System.out.println(queryBuilder.getNodeId()); ids.add(queryBuilder.getNodeId()); super.visit(queryBuilder); }

Target:
public void visit(QueryMetadata.Builder queryBuilder) { ids.add(queryBuilder.getNodeId()); super.visit(queryBuilder); }
Source:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }

Target:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }
Source:
public void initialize() { logger.debug("Initializing IOTA bridge"); Configuration config = getThing().getConfiguration(); setHost(getOrDefault(config.get(IotaBindingConstants.HOST), getHost())); setProtocol(getOrDefault(config.get(IotaBindingConstants.PROTOCOL), getProtocol())); setPort(getOrDefault(config.get(IotaBindingConstants.PORT), getPort())); setUtils(new IotaUtils(protocol, host, port)); if (utils.checkAPI()) { logger.debug("IOTA API checked, connexion successfull: bridge can be set ONLINE"); updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } }

Target:
public void initialize() { logger.debug("Initializing IOTA bridge"); Configuration configuration = getThing().getConfiguration(); setHost((String) configuration.get(IotaBindingConstants.HOST)); setProtocol((String) configuration.get(IotaBindingConstants.PROTOCOL)); int port = configuration.get(IotaBindingConstants.PORT) == null ? 0 : ((BigDecimal) configuration.get(IotaBindingConstants.PORT)).intValue(); setPort(port); try { this.utils.setIotaAPI(protocol, host, port); } catch (IllegalStateException e) { logger.warn("Wrong configuration detected: please check your configuration {}", e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } if (utils.checkAPI()) { logger.debug("IOTA API checked, connexion successfull: bridge can be set ONLINE"); updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } }
Source:
public ExtractRepresentationAction(Session session, Collection<DRepresentation> selection) { super(); this.session = session; this.representations = Collections2.filter(selection, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && !permissionAuthority.canCreateIn(container)) { return false; } } return true; } }); final ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/export.gif"); this.setImageDescriptor(descriptor); this.setText("Extract to ." + SiriusUtil.SESSION_RESOURCE_EXTENSION + " file ..."); if (this.representations.isEmpty()) { this.setEnabled(false); } }

Target:
public ExtractRepresentationAction(Session session, Collection<DRepresentation> selection) { super(); this.session = session; this.representations = Collections2.filter(selection, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && !permissionAuthority.canDeleteInstance(container)) { return false; } } return true; } }); final ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/export.gif"); this.setImageDescriptor(descriptor); this.setText("Extract to ." + SiriusUtil.SESSION_RESOURCE_EXTENSION + " file ..."); if (this.representations.isEmpty()) { this.setEnabled(false); } }