Example usage for com.google.common.collect Iterables any

List of usage examples for com.google.common.collect Iterables any

Introduction

In this page you can find the example usage for com.google.common.collect Iterables any.

Prototype

public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

From source file:io.druid.indexing.overlord.autoscaling.SimpleResourceManagementStrategy.java

private void updateTargetWorkerCount(final WorkerBehaviorConfig workerConfig,
        final Collection<RemoteTaskRunnerWorkItem> pendingTasks, final Collection<ZkWorker> zkWorkers) {
    synchronized (lock) {
        final Collection<ZkWorker> validWorkers = Collections2.filter(zkWorkers,
                createValidWorkerPredicate(config));
        final Predicate<ZkWorker> isLazyWorker = createLazyWorkerPredicate(config);
        final int minWorkerCount = workerConfig.getAutoScaler().getMinNumWorkers();
        final int maxWorkerCount = workerConfig.getAutoScaler().getMaxNumWorkers();

        if (minWorkerCount > maxWorkerCount) {
            log.error("Huh? minWorkerCount[%d] > maxWorkerCount[%d]. I give up!", minWorkerCount,
                    maxWorkerCount);/*from  w  w w.j  av a  2 s.  c o m*/
            return;
        }

        if (targetWorkerCount < 0) {
            // Initialize to size of current worker pool, subject to pool size limits
            targetWorkerCount = Math.max(Math.min(zkWorkers.size(), maxWorkerCount), minWorkerCount);
            log.info("Starting with a target of %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }

        final boolean notTakingActions = currentlyProvisioning.isEmpty() && currentlyTerminating.isEmpty();
        final boolean shouldScaleUp = notTakingActions && validWorkers.size() >= targetWorkerCount
                && targetWorkerCount < maxWorkerCount
                && (hasTaskPendingBeyondThreshold(pendingTasks) || targetWorkerCount < minWorkerCount);
        final boolean shouldScaleDown = notTakingActions && validWorkers.size() == targetWorkerCount
                && targetWorkerCount > minWorkerCount && Iterables.any(validWorkers, isLazyWorker);
        if (shouldScaleUp) {
            targetWorkerCount = Math.max(targetWorkerCount + 1, minWorkerCount);
            log.info("I think we should scale up to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else if (shouldScaleDown) {
            targetWorkerCount = Math.min(targetWorkerCount - 1, maxWorkerCount);
            log.info("I think we should scale down to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else {
            log.info("Our target is %,d workers, and I'm okay with that (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }
    }
}

From source file:google.registry.tools.CreateOrUpdateRegistrarCommand.java

@Override
protected final void init() throws Exception {
    initRegistrarCommand();//from  www.ja  v a 2s .co  m
    DateTime now = DateTime.now(UTC);
    for (String clientId : mainParameters) {
        Registrar oldRegistrar = getOldRegistrar(clientId);
        Registrar.Builder builder = (oldRegistrar == null) ? new Registrar.Builder().setClientId(clientId)
                : oldRegistrar.asBuilder();

        if (!isNullOrEmpty(password)) {
            builder.setPassword(password);
        }
        if (!isNullOrEmpty(registrarName)) {
            builder.setRegistrarName(registrarName);
        }
        if (email != null) {
            builder.setEmailAddress(email.orNull());
        }
        if (url != null) {
            builder.setUrl(url.orNull());
        }
        if (phone != null) {
            builder.setPhoneNumber(phone.orNull());
        }
        if (fax != null) {
            builder.setFaxNumber(fax.orNull());
        }
        if (registrarType != null) {
            builder.setType(registrarType);
        }
        if (registrarState != null) {
            builder.setState(registrarState);
        }
        if (driveFolderId != null) {
            builder.setDriveFolderId(driveFolderId.orNull());
        }
        if (!allowedTlds.isEmpty()) {
            checkArgument(addAllowedTlds.isEmpty(), "Can't specify both --allowedTlds and --addAllowedTlds");
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            for (String allowedTld : allowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!addAllowedTlds.isEmpty()) {
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            if (oldRegistrar != null) {
                allowedTldsBuilder.addAll(oldRegistrar.getAllowedTlds());
            }
            for (String allowedTld : addAllowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!ipWhitelist.isEmpty()) {
            ImmutableList.Builder<CidrAddressBlock> ipWhitelistBuilder = new ImmutableList.Builder<>();
            if (!(ipWhitelist.size() == 1 && ipWhitelist.get(0).contains("null"))) {
                for (String ipRange : ipWhitelist) {
                    ipWhitelistBuilder.add(CidrAddressBlock.create(ipRange));
                }
            }
            builder.setIpAddressWhitelist(ipWhitelistBuilder.build());
        }
        if (clientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(clientCertificateFilename), US_ASCII);
            builder.setClientCertificate(asciiCert, now);
        }
        if (failoverClientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(failoverClientCertificateFilename), US_ASCII);
            builder.setFailoverClientCertificate(asciiCert, now);
        }
        if (!isNullOrEmpty(clientCertificateHash)) {
            checkArgument(clientCertificateFilename == null, "Can't specify both --cert_hash and --cert_file");
            if ("null".equals(clientCertificateHash)) {
                clientCertificateHash = null;
            }
            builder.setClientCertificateHash(clientCertificateHash);
        }
        if (ianaId != null) {
            builder.setIanaIdentifier(ianaId.orNull());
        }
        if (billingId != null) {
            builder.setBillingIdentifier(billingId.orNull());
        }
        if (billingMethod != null) {
            if (oldRegistrar != null && !billingMethod.equals(oldRegistrar.getBillingMethod())) {
                Map<CurrencyUnit, Money> balances = RegistrarBillingUtils.loadBalance(oldRegistrar);
                for (Money balance : balances.values()) {
                    checkState(balance.isZero(),
                            "Refusing to change billing method on Registrar '%s' from %s to %s"
                                    + " because current balance is non-zero: %s",
                            clientId, oldRegistrar.getBillingMethod(), billingMethod, balances);
                }
            }
            builder.setBillingMethod(billingMethod);
        }
        List<Object> streetAddressFields = Arrays.asList(street, city, state, zip, countryCode);
        checkArgument(
                Iterables.any(streetAddressFields, isNull()) == Iterables.all(streetAddressFields, isNull()),
                "Must specify all fields of address");
        if (street != null) {
            // We always set the localized address for now. That should be safe to do since it supports
            // unrestricted UTF-8.
            builder.setLocalizedAddress(new RegistrarAddress.Builder().setStreet(ImmutableList.copyOf(street))
                    .setCity(city).setState("null".equals(state) ? null : state)
                    .setZip("null".equals(zip) ? null : zip).setCountryCode(countryCode).build());
        }
        if (blockPremiumNames != null) {
            builder.setBlockPremiumNames(blockPremiumNames);
        }
        if (contactsRequireSyncing != null) {
            builder.setContactsRequireSyncing(contactsRequireSyncing);
        }
        // When creating a new REAL registrar or changing the type to REAL, a passcode is required.
        // Leave existing REAL registrars alone.
        if (Registrar.Type.REAL.equals(registrarType)
                && (oldRegistrar == null || oldRegistrar.getPhonePasscode() == null)) {
            checkArgument(phonePasscode != null, "--passcode is required for REAL registrars.");
        }
        if (phonePasscode != null) {
            builder.setPhonePasscode(phonePasscode);
        }
        if (icannReferralEmail != null) {
            builder.setIcannReferralEmail(icannReferralEmail);
        }
        if (whoisServer != null) {
            builder.setWhoisServer(whoisServer);
        }

        // If the registrarName is being set, verify that it is either null or it normalizes uniquely.
        String oldRegistrarName = (oldRegistrar == null) ? null : oldRegistrar.getRegistrarName();
        if (registrarName != null && !registrarName.equals(oldRegistrarName)) {
            String normalizedName = normalizeRegistrarName(registrarName);
            for (Registrar registrar : Registrar.loadAll()) {
                if (registrar.getRegistrarName() != null) {
                    checkArgument(!normalizedName.equals(normalizeRegistrarName(registrar.getRegistrarName())),
                            "The registrar name %s normalizes identically to existing registrar name %s",
                            registrarName, registrar.getRegistrarName());
                }
            }
        }

        stageEntityChange(oldRegistrar, builder.build());
    }
}

From source file:org.gradle.plugins.ide.idea.model.internal.IdeaDependenciesProvider.java

private boolean isMappedToIdeaScope(final Configuration configuration, IdeaModule ideaModule) {
    Iterable<IdeaScopeMappingRule> rules = Iterables.concat(scopeMappings.values());
    boolean matchesRule = Iterables.any(rules, new Predicate<IdeaScopeMappingRule>() {
        public boolean apply(IdeaScopeMappingRule ideaScopeMappingRule) {
            return ideaScopeMappingRule.configurationNames.contains(configuration.getName());
        }/*w  ww  .j a v  a2  s .  c  om*/
    });
    if (matchesRule) {
        return true;
    }
    for (Map<String, Collection<Configuration>> scopeMap : ideaModule.getScopes().values()) {
        Iterable<Configuration> configurations = Iterables.concat(scopeMap.values());
        if (Iterables.any(configurations, Predicates.equalTo(configuration))) {
            return true;
        }
    }
    return false;
}

From source file:io.druid.indexing.overlord.scaling.SimpleResourceManagementStrategy.java

private void updateTargetWorkerCount(final WorkerSetupData workerSetupData,
        final Collection<RemoteTaskRunnerWorkItem> pendingTasks, final Collection<ZkWorker> zkWorkers) {
    synchronized (lock) {
        final Collection<ZkWorker> validWorkers = Collections2.filter(zkWorkers,
                createValidWorkerPredicate(config, workerSetupData));
        final Predicate<ZkWorker> isLazyWorker = createLazyWorkerPredicate(config, workerSetupData);
        final int minWorkerCount = workerSetupData.getMinNumWorkers();
        final int maxWorkerCount = workerSetupData.getMaxNumWorkers();

        if (minWorkerCount > maxWorkerCount) {
            log.error("Huh? minWorkerCount[%d] > maxWorkerCount[%d]. I give up!", minWorkerCount,
                    maxWorkerCount);/*from   w  w  w.  jav a2 s .c om*/
            return;
        }

        if (targetWorkerCount < 0) {
            // Initialize to size of current worker pool, subject to pool size limits
            targetWorkerCount = Math.max(Math.min(zkWorkers.size(), maxWorkerCount), minWorkerCount);
            log.info("Starting with a target of %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }

        final boolean notTakingActions = currentlyProvisioning.isEmpty() && currentlyTerminating.isEmpty();
        final boolean shouldScaleUp = notTakingActions && validWorkers.size() >= targetWorkerCount
                && targetWorkerCount < maxWorkerCount
                && (hasTaskPendingBeyondThreshold(pendingTasks) || targetWorkerCount < minWorkerCount);
        final boolean shouldScaleDown = notTakingActions && validWorkers.size() == targetWorkerCount
                && targetWorkerCount > minWorkerCount && Iterables.any(validWorkers, isLazyWorker);
        if (shouldScaleUp) {
            targetWorkerCount = Math.max(targetWorkerCount + 1, minWorkerCount);
            log.info("I think we should scale up to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else if (shouldScaleDown) {
            targetWorkerCount = Math.min(targetWorkerCount - 1, maxWorkerCount);
            log.info("I think we should scale down to %,d workers (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        } else {
            log.info("Our target is %,d workers, and I'm okay with that (current = %,d, min = %,d, max = %,d).",
                    targetWorkerCount, validWorkers.size(), minWorkerCount, maxWorkerCount);
        }
    }
}

From source file:com.twitter.aurora.scheduler.state.CronJobManager.java

/**
 * Triggers execution of a cron job, depending on the cron collision policy for the job.
 *
 * @param config The config of the job to be triggered.
 *///from   www  .  j a  v a2s.  c om
@VisibleForTesting
void cronTriggered(SanitizedConfiguration config) {
    IJobConfiguration job = config.getJobConfig();
    LOG.info(String.format("Cron triggered for %s at %s with policy %s", JobKeys.toPath(job), new Date(),
            job.getCronCollisionPolicy()));
    cronJobsTriggered.incrementAndGet();

    ImmutableMap.Builder<Integer, ITaskConfig> builder = ImmutableMap.builder();
    final Query.Builder activeQuery = Query.jobScoped(job.getKey()).active();
    Set<IScheduledTask> activeTasks = Storage.Util.consistentFetchTasks(storage, activeQuery);

    if (activeTasks.isEmpty()) {
        builder.putAll(config.getTaskConfigs());
    } else {
        // Assign a default collision policy.
        CronCollisionPolicy collisionPolicy = orDefault(job.getCronCollisionPolicy());

        switch (collisionPolicy) {
        case KILL_EXISTING:
            try {
                schedulerCore.killTasks(activeQuery, CRON_USER);
                // Check immediately if the tasks are gone.  This could happen if the existing tasks
                // were pending.
                if (!hasTasks(activeQuery)) {
                    builder.putAll(config.getTaskConfigs());
                } else {
                    delayedRun(activeQuery, config);
                }
            } catch (ScheduleException e) {
                LOG.log(Level.SEVERE, "Failed to kill job.", e);
            }
            break;

        case CANCEL_NEW:
            break;

        case RUN_OVERLAP:
            Map<Integer, IScheduledTask> byInstance = Maps.uniqueIndex(activeTasks,
                    Tasks.SCHEDULED_TO_INSTANCE_ID);
            Map<Integer, ScheduleStatus> existingTasks = Maps.transformValues(byInstance, Tasks.GET_STATUS);
            if (existingTasks.isEmpty()) {
                builder.putAll(config.getTaskConfigs());
            } else if (Iterables.any(existingTasks.values(), Predicates.equalTo(PENDING))) {
                LOG.info("Job " + JobKeys.toPath(job) + " has pending tasks, suppressing run.");
            } else {
                // To safely overlap this run, we need to adjust the instance IDs of the overlapping
                // run (maintaining the role/job/instance UUID invariant).
                int instanceOffset = Ordering.natural().max(existingTasks.keySet()) + 1;
                LOG.info("Adjusting instance IDs of " + JobKeys.toPath(job) + " by " + instanceOffset
                        + " for overlapping cron run.");
                for (Map.Entry<Integer, ITaskConfig> entry : config.getTaskConfigs().entrySet()) {
                    builder.put(entry.getKey() + instanceOffset, entry.getValue());
                }
            }
            break;

        default:
            LOG.severe("Unrecognized cron collision policy: " + job.getCronCollisionPolicy());
        }
    }

    Map<Integer, ITaskConfig> newTasks = builder.build();
    if (!newTasks.isEmpty()) {
        stateManager.insertPendingTasks(newTasks);
    }
}

From source file:org.eclipse.xtext.util.formallang.NfaToProduction.java

protected <T> boolean createAlternative(StateAliasNfa<T> states) {
    boolean created = false;
    Multimap<Pair<Set<StateAlias<T>>, Set<StateAlias<T>>>, StateAlias<T>> alternative = LinkedHashMultimap
            .create();/*from  ww w  .java  2s.co  m*/

    for (StateAlias<T> candidate : new NfaUtil().collect(states))
        if (!candidate.getIncoming().isEmpty() && !candidate.getOutgoing().isEmpty())
            alternative.put(Tuples.create(candidate.getIncoming(), candidate.getOutgoing()), candidate);

    for (Pair<Set<StateAlias<T>>, Set<StateAlias<T>>> inout : alternative.keySet()) {
        Collection<StateAlias<T>> candidates = alternative.get(inout);

        if (candidates.size() < 2)
            continue;

        boolean many = inout.getFirst().containsAll(candidates) && inout.getSecond().containsAll(candidates);
        boolean single = !Iterables.any(inout.getFirst(), Predicates.in(candidates))
                && !Iterables.any(inout.getSecond(), Predicates.in(candidates));
        if (!many && !single)
            continue;

        AlternativeAlias<T> alt = new AlternativeAlias<T>();
        alt.setMany(many);
        StateAlias<T> altState = new StateAlias<T>(alt);
        for (StateAlias<T> candidate : candidates) {
            alt.addChild(candidate.getElement());
            for (StateAlias<T> in : candidate.getIncoming())
                in.getOutgoing().remove(candidate);
            for (StateAlias<T> out : candidate.getOutgoing())
                out.getIncoming().remove(candidate);
        }
        for (StateAlias<T> in : inout.getFirst())
            if (!candidates.contains(in)) {
                altState.getIncoming().add(in);
                in.getOutgoing().add(altState);
            }
        for (StateAlias<T> out : inout.getSecond())
            if (!candidates.contains(out)) {
                altState.getOutgoing().add(out);
                out.getIncoming().add(altState);
            }
        created = true;
    }
    return created;
}

From source file:org.eclipse.emf.compare.internal.conflict.AbstractConflictSearch.java

/**
 * Checks whether the given {@code match} presents a difference of any kind on the given {@code feature}'s
 * {@code value}./*w w  w  .j ava  2s . co  m*/
 * 
 * @param match
 *            The match which differences we'll check.
 * @param feature
 *            The feature on which we expect a difference.
 * @param value
 *            The value we expect to have changed inside {@code feature}.
 * @return <code>true</code> if there is such a Diff on {@code match}, <code>false</code> otherwise.
 */
protected boolean hasDiff(Match match, EStructuralFeature feature, Object value) {
    return Iterables.any(match.getDifferences(), and(onFeature(feature.getName()), valueIs(value)));
}

From source file:org.eclipse.xtext.xbase.typesystem.internal.FeatureLinkingCandidate.java

/**
 * Validates this linking candidate and adds respective diagnostics to the given queue.
 * //from w  w  w.  j a v  a  2s.  c o  m
 * In addition to the checks that are inherited from {@link AbstractPendingLinkingCandidate#validate(IAcceptor)},
 * the candidate is validated according these criteria:
 * 
 * <ol>
 * <li>{@link #isInvalidStaticSyntax() syntax for static feature calls},</li>
 * <li>{@link #isStatic() static context for static members},</li>
 * <li>field accessed as a method, e.g. with parentheses,</li>
 * <li>usage of {@code this} or {@code super} in an invalid context,</li>
 * <li>direct invocation of an abstract method,</li>
 * <li>attempt to enclose a non-final local variable in a lambda expression,</li>
 * <li>reference to a private feature with a subclass instance,</li>
 * <li>{@link #isGetClassOnTypeLiteral() errorprone invocation of getClass()}.</li>
 * </ol>
 */
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
    XAbstractFeatureCall featureCall = getFeatureCall();
    if (isReassignFirstArgument(featureCall)) {
        XBinaryOperation binaryOperation = (XBinaryOperation) featureCall;

        LightweightTypeReference actualType = getDeclaredType(featureCall.getFeature());
        LightweightTypeReference expectedType = getActualType(binaryOperation.getLeftOperand());
        if (!expectedType.getIdentifier().equals(actualType.getIdentifier())) {
            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                    IssueCodes.INCOMPATIBLE_TYPES,
                    String.format("Type mismatch: cannot convert from %s to %s",
                            actualType.getHumanReadableName(), expectedType.getHumanReadableName()),
                    getExpression(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
            result.accept(diagnostic);
            return false;
        }
    }
    if (isInvalidStaticSyntax()) {
        Severity severity = getSeverity(IssueCodes.INSTANCE_ACCESS_TO_STATIC_MEMBER);
        if (severity != Severity.IGNORE) {
            String message = String.format("The static %1$s %2$s%3$s should be accessed in a static way",
                    getFeatureTypeName(), getFeature().getSimpleName(), getFeatureParameterTypesAsString());
            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(severity,
                    IssueCodes.INSTANCE_ACCESS_TO_STATIC_MEMBER, message, getExpression(),
                    XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
            result.accept(diagnostic);
            return false;
        } else {
            return true;
        }
    } else if (!isStatic() && isStaticAccessSyntax()) {
        EObject featureOwner = getFeature().eContainer();
        String message = String.format("Cannot make a static reference to the non-static %1$s %2$s%3$s",
                getFeatureTypeName(), getFeature().getSimpleName(), getFeatureParameterTypesAsString());
        if (featureOwner instanceof JvmDeclaredType)
            message += " from the type " + ((JvmDeclaredType) featureOwner).getSimpleName();
        AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                IssueCodes.STATIC_ACCESS_TO_INSTANCE_MEMBER, message, getExpression(),
                XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
        result.accept(diagnostic);
        return false;
    } else if (super.validate(result)) {
        if (isOperationCallSyntax() && !(getFeature() instanceof JvmExecutable)) {
            String typeName = getFeatureTypeName();
            String code = IssueCodes.FIELD_ACCESS_WITH_PARENTHESES;
            if (!(getFeature() instanceof JvmField)) {
                code = IssueCodes.LOCAL_VAR_ACCESS_WITH_PARENTHESES;
            }
            String message = "Cannot access the " + typeName + " " + getFeature().getSimpleName()
                    + " with parentheses";
            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR, code, message,
                    getExpression(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
            result.accept(diagnostic);
            return false;
        }
        JvmIdentifiableElement feature = getFeature();
        if (feature instanceof JvmType) {
            QualifiedName featureName = description.getName();
            if (!getState().isInstanceContext()) {
                if (!(SELF.equals(featureName))) {
                    String message = String.format("Cannot use %s in a static context", featureName);
                    AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                            IssueCodes.STATIC_ACCESS_TO_INSTANCE_MEMBER, message, getExpression(),
                            XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                    result.accept(diagnostic);
                    return false;
                }
            } else if (getExpression() instanceof XMemberFeatureCall && !(SELF.equals(featureName))) {
                XMemberFeatureCall memberFeatureCall = (XMemberFeatureCall) getExpression();
                XAbstractFeatureCall target = (XAbstractFeatureCall) memberFeatureCall.getMemberCallTarget();
                final JvmType referencedType = (JvmType) target.getFeature();
                List<JvmDeclaredType> enclosingTypes = getState().getFeatureScopeSession().getEnclosingTypes();
                if (SUPER.equals(featureName) && referencedType instanceof JvmGenericType
                        && ((JvmGenericType) referencedType).isInterface() && !enclosingTypes.isEmpty()) {
                    if (!Iterables.any(enclosingTypes.get(0).getSuperTypes(),
                            new Predicate<JvmTypeReference>() {
                                @Override
                                public boolean apply(JvmTypeReference input) {
                                    return input.getType() == referencedType;
                                }
                            })) {
                        String message = String.format(
                                "The enclosing type does not extend or implement the interface %s",
                                referencedType.getSimpleName());
                        AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                                IssueCodes.NO_ENCLOSING_INSTANCE_AVAILABLE, message, getExpression(),
                                XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                        result.accept(diagnostic);
                        return false;
                    }
                } else if (!enclosingTypes.contains(referencedType)) {
                    String message = String.format(
                            "No enclosing instance of the type %s is accessible in scope",
                            referencedType.getSimpleName());
                    AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                            IssueCodes.NO_ENCLOSING_INSTANCE_AVAILABLE, message, getExpression(),
                            XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                    result.accept(diagnostic);
                    return false;
                }
            } else if (getExpression() instanceof XFeatureCall && SUPER.equals(featureName)) {
                List<JvmDeclaredType> enclosingTypes = getState().getFeatureScopeSession().getEnclosingTypes();
                JvmDeclaredType declaringType = null;
                if (!enclosingTypes.isEmpty())
                    declaringType = enclosingTypes.get(0);
                if (declaringType instanceof JvmGenericType && ((JvmGenericType) declaringType).isInterface()) {
                    if (!getState().isIgnored(IssueCodes.UNQUALIFIED_SUPER_CALL)) {
                        AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
                                getSeverity(IssueCodes.UNQUALIFIED_SUPER_CALL),
                                IssueCodes.UNQUALIFIED_SUPER_CALL,
                                "Unqualified super reference is not allowed in interface context",
                                getExpression(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1,
                                null);
                        result.accept(diagnostic);
                        return false;
                    }
                } else if (declaringType != null && declaringType != feature && declaringType.isLocal()) {
                    XClosure closure = EcoreUtil2.getContainerOfType(featureCall, XClosure.class);
                    if (closure != null) {
                        EObject typeSource = getState().getReferenceOwner().getServices()
                                .getJvmModelAssociations().getPrimarySourceElement(declaringType);
                        if (typeSource != null && EcoreUtil.isAncestor(typeSource, closure)) {
                            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                                    IssueCodes.INVALID_SUPER_CALL,
                                    "Cannot call super of an anonymous class from a lambda expression",
                                    getExpression(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1,
                                    null);
                            result.accept(diagnostic);
                            return false;
                        }
                    }
                }
            }
        }
        if (feature instanceof XVariableDeclaration) {
            XVariableDeclaration casted = (XVariableDeclaration) feature;
            if (casted.isWriteable()) {
                String message = getState().getResolver().getInvalidWritableVariableAccessMessage(casted,
                        getFeatureCall(), getState().getResolvedTypes());
                if (message != null) {
                    AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                            IssueCodes.INVALID_MUTABLE_VARIABLE_ACCESS, message, getExpression(),
                            XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                    result.accept(diagnostic);
                    return false;
                }
            }
            if (EcoreUtil.isAncestor(casted, getFeatureCall())) {
                String message = String.format("The local variable %s may not have been initialized",
                        feature.getSimpleName());
                AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                        IssueCodes.ILLEGAL_FORWARD_REFERENCE, message, getExpression(),
                        XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                result.accept(diagnostic);
                return false;
            }
        }
        if (feature instanceof JvmOperation) {
            JvmOperation operation = (JvmOperation) feature;
            if (operation.isAbstract() && featureCall instanceof XMemberFeatureCall) {
                Severity severity = getSeverity(IssueCodes.ABSTRACT_METHOD_INVOCATION);
                if (severity != Severity.IGNORE) {
                    XMemberFeatureCall memberFeatureCall = (XMemberFeatureCall) featureCall;
                    XExpression target = memberFeatureCall.getMemberCallTarget();
                    if (target instanceof XAbstractFeatureCall && SUPER.getFirstSegment()
                            .equals(((XAbstractFeatureCall) target).getConcreteSyntaxFeatureName())) {
                        JvmIdentifiableElement targetFeature = ((XAbstractFeatureCall) target).getFeature();
                        String message = String.format(
                                "Cannot directly invoke the abstract method %s%s of the type %s",
                                operation.getSimpleName(), getFeatureParameterTypesAsString(operation),
                                targetFeature.getSimpleName());
                        AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(severity,
                                IssueCodes.ABSTRACT_METHOD_INVOCATION, message, memberFeatureCall,
                                XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
                        result.accept(diagnostic);
                        return false;
                    }
                }
            }
        }
        if (feature instanceof JvmMember) {
            JvmMember member = (JvmMember) feature;
            if (member.getVisibility() == JvmVisibility.PRIVATE) {
                LightweightTypeReference receiverType = getReceiverType();
                if (receiverType != null) {
                    if (receiverType.getType() != member.getDeclaringType()) {
                        List<JvmDeclaredType> enclosingTypes = getState().getFeatureScopeSession()
                                .getEnclosingTypes();
                        if (enclosingTypes.contains(member.getDeclaringType())) {
                            String message = String.format(
                                    "Cannot access the private %s %s%s in a subclass context",
                                    getFeatureTypeName(), member.getSimpleName(),
                                    getFeatureParameterTypesAsString());
                            String[] issueData = null;
                            // We can fix the issue by adding a type cast to the declaring type of the feature
                            issueData = new String[] { "subclass-context",
                                    member.getDeclaringType().getSimpleName() };
                            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                                    IssueCodes.FEATURE_NOT_VISIBLE, message, featureCall,
                                    XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, issueData);
                            result.accept(diagnostic);
                            return false;
                        }
                    }
                }
            }
        }
    }
    if (isGetClassOnTypeLiteral()) {
        if ("class".equals(description.getName().getFirstSegment())) {
            LightweightTypeReference receiverType = getSyntacticReceiverType();
            if (receiverType == null) {
                throw new IllegalStateException();
            }
            receiverType = receiverType.getTypeArguments().get(0);
            String message = String.format("The syntax for type literals is typeof(%s) or %s.",
                    receiverType.getHumanReadableName(), receiverType.getHumanReadableName());
            AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
                    IssueCodes.UNEXPECTED_INVOCATION_ON_TYPE_LITERAL, message, getExpression(),
                    XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
            result.accept(diagnostic);
            return false;
        }
    }
    return true;
}

From source file:gov.nih.nci.caarray.domain.array.ArrayDesign.java

/**
 * Check whether this is a array design that was previously imported but not parsed, but now can be imported and
 * parsed (due to a new parsing FileHandler being implemented for it, or because it was previously canceled from the
 * job queue). This will be the case if any of the design files associated with the array design meet this
 * condition.//  w w  w  .  j  av a2  s  . c  o m
 * 
 * @return true if the design can be re-imported and parsed, false otherwise.
 */
@Transient
public boolean isUnparsedAndReimportable() {
    return Iterables.any(getDesignFiles(), new Predicate<CaArrayFile>() {
        @Override
        public boolean apply(CaArrayFile file) {
            return (file.isUnparsedAndReimportable() || file.getFileStatus() == FileStatus.UPLOADED);
        }
    });
}

From source file:org.eclipse.sirius.ui.business.internal.viewpoint.ViewpointSelectionDialog.java

/**
 * Get missing dependencies from the current selection
 * /*  w w  w. jav a 2 s .  c o  m*/
 * @return missing dependencies
 */
private Map<String, Collection<String>> getMissingDependencies() {
    Set<Viewpoint> selected = Maps.filterValues(selection, Predicates.equalTo(Boolean.TRUE)).keySet();

    Multimap<String, String> result = HashMultimap.create();
    for (Viewpoint viewpoint : selected) {
        for (RepresentationExtensionDescription extension : new ViewpointQuery(viewpoint)
                .getAllRepresentationExtensionDescriptions()) {
            String extended = extension.getViewpointURI();
            final Pattern pattern = Pattern.compile(extended);

            // Is there at least one available selected viewpoint URI ?
            if (!Iterables.any(selected, new Predicate<Viewpoint>() {
                @Override
                public boolean apply(Viewpoint vp) {
                    Option<URI> uri = new ViewpointQuery(vp).getViewpointURI();
                    if (uri.some()) {
                        Matcher matcher = pattern.matcher(uri.get().toString());
                        return matcher.matches();
                    } else {
                        return false;
                    }
                }
            })) {
                result.put(viewpoint.getName(), extended.trim().replaceFirst("^viewpoint:/[^/]+/", "")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    }
    return result.asMap();
}