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:org.obeonetwork.dsl.uml2.core.internal.dialogs.ConfirmDeletionDialog.java

private boolean isOrHasDescendant(Object element, final Predicate<Object> pred) {
    final boolean matches = pred.apply(element);
    if (matches) {
        return true;
    }/*from   w  w  w  .ja v a  2  s .  c  om*/
    return Iterables.any(Arrays.asList(contentProvider.getChildren(element)), new Predicate<Object>() {
        public boolean apply(Object input) {
            return isOrHasDescendant(input, pred);
        }
    });
}

From source file:gov.nih.nci.firebird.data.user.RegistrationCoordinatorRole.java

/**
 * Returns whether or not this registration coordinator is approved to manage the given investigator's
 * registrations.// w ww .j  a  v a 2  s.  com
 *
 * @param profile investigator profile to manage
 * @return whether or not this registration coordinator is approved to manage the given investigator's registrations
 */
@Transient
public boolean isApprovedToManageInvestigatorRegistrations(final InvestigatorProfile profile) {
    return Iterables.any(getManagedInvestigators(), new Predicate<ManagedInvestigator>() {
        @Override
        public boolean apply(ManagedInvestigator managedInvestigator) {
            return managedInvestigator.getInvestigatorProfile().equals(profile)
                    && managedInvestigator.isApproved() && !managedInvestigator.isSuspendedRegistrationAccess();
        }
    });
}

From source file:org.opentestsystem.authoring.testauth.publish.SharedPublisherHelper.java

private List<TestComputationRule> buildTestComputationRulesForLevelRules(
        final List<ScoringRule> scoringRuleList, final List<BlueprintElement> blueprintElementList) {
    final List<TestComputationRule> testComputationRuleList = Lists.newArrayList();
    if (Iterables.any(scoringRuleList, LEVEL_TYPE_FILTER)) {

        // construct each leaf node into a separate scoring rule
        final List<ScoringRule> levelScoringRules = Lists
                .newArrayList(Iterables.filter(scoringRuleList, LEVEL_TYPE_FILTER));
        for (final ScoringRule scoringRule : levelScoringRules) {
            final int i = 1;
            // winnow blueprintElement list down to matching levels only
            Iterables.removeIf(blueprintElementList,
                    Predicates.not(LEVEL_FILTER.getInstance(scoringRule.getBlueprintReferenceId())));
            // transform every leaf node bp element into a scoring rule mimicking this scoringRule
            testComputationRuleList.addAll(Lists.transform(blueprintElementList,
                    LEAF_NODE_LEVEL_SCORING_RULE_TRANSFORMER.getInstance(scoringRule, i)));
        }//from w w w  .j  a  va  2  s  .  c  o  m
    }
    return testComputationRuleList;
}

From source file:zotmc.collect.recipe.BasicRecipeView.java

@Override
public boolean replaceInput(Predicate<RecipeElement> filter, RecipeElement element) {
    eraseState();/*from   w  w w . ja  v a 2 s.  c  o m*/

    List<RecipeElement> inputs = getInputView();

    if (Iterables.any(inputs, filter)) {
        hasChange = true;

        IRecipe temp = recipe;
        recipe = explicit(recipe, Lists.transform(inputs, replaceFunction(filter, element)),
                recipe.getRecipeOutput());
        oldRecipe = temp;

        return true;
    }

    return false;
}

From source file:org.eclipse.incquery.viewers.tooling.ui.views.ViewersMultiSandboxViewComponent.java

private static Collection<IQuerySpecification<?>> getPatternsWithProperAnnotations(
        Collection<IQuerySpecification<?>> input) {
    List<IQuerySpecification<?>> res = Lists.newArrayList();
    for (IQuerySpecification<?> p : input) {
        if (Iterables.any(p.getAllAnnotations(), new ViewersAnnotatedPatternTester())) {
            res.add(p);//www.  j av a  2 s.c  om
        }
    }
    return res;
}

From source file:org.killbill.billing.payment.provider.ExternalPaymentProviderPlugin.java

private boolean isPropertySet(final Iterable<PluginProperty> properties, final String targetProperty) {
    return Iterables.any(properties, new Predicate<PluginProperty>() {
        @Override/*from  www  . j  av  a  2  s  .  co  m*/
        public boolean apply(final PluginProperty input) {
            return input.getKey().equals(targetProperty) && input.getValue().equals("true");
        }
    });
}

From source file:org.obm.push.mail.EmailViewPartsFetcherImpl.java

private boolean isCalendarOperation(Collection<MimePart> children) {
    return Iterables.any(children, new Predicate<MimePart>() {
        @Override//from www . ja v a 2 s .  co m
        public boolean apply(MimePart input) {
            return input.containsCalendarMethod();
        }
    });
}

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

private List<Item> computeItemHierarchy(final Collection<String> fileExtensions) {
    final Predicate<Viewpoint> isTopLevel = new Predicate<Viewpoint>() {
        public boolean apply(final Viewpoint vp) {
            boolean top = vp != null && vp.getCustomizes().isEmpty();
            boolean matchesSemancitModel = Iterables.any(fileExtensions, new Predicate<String>() {
                public boolean apply(String ext) {
                    return new ViewpointQuery(vp).handlesSemanticModelExtension(ext);
                }//from w w w  . j ava2  s . c om
            });
            return top && matchesSemancitModel;
        }
    };

    List<Item> roots = Lists.newArrayList(Iterables.transform(
            Iterables.filter(this.registry.getViewpoints(), isTopLevel), new Function<Viewpoint, Item>() {
                public Item apply(Viewpoint from) {
                    return new Item(null, from);
                }
            }));
    for (Item item : roots) {
        item.fillDescendants();
    }
    Collections.sort(roots, Ordering.natural().onResultOf(new Function<Item, String>() {
        public String apply(Item from) {
            return from.viewpoint.getName();
        }
    }));
    return roots;
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

/**
 * <p>/*from  w  w w . j a  v a2 s  .c  om*/
 * Create an Amazon IAM account and send the details by email.
 * </p>
 * <p>
 * Created elements:
 * </p>
 * <ul>
 * <li>password to login to the management console if none exists,</li>
 * <li>accesskey if none is active,</li>
 * <li></li>
 * </ul>
 *
 * @param userName valid email used as userName of the created account.
 */
public void createUser(@Nonnull final String userName, GetGroupResult groupDescriptor, String keyPairName)
        throws Exception {
    Preconditions.checkNotNull(userName, "Given userName can NOT be null");
    logger.info("Process user {}", userName);

    List<String> userAccountChanges = Lists.newArrayList();

    Map<String, String> templatesParams = Maps.newHashMap();
    templatesParams.put("awsCredentialsHome", "~/.aws");
    templatesParams.put("awsCommandLinesHome", "/opt/amazon-aws");

    User user;
    try {
        user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser();
    } catch (NoSuchEntityException e) {
        logger.debug("User {} does not exist, create it", userName, e);
        user = iam.createUser(new CreateUserRequest(userName)).getUser();
        userAccountChanges.add("Create user");
    }

    List<BodyPart> attachments = Lists.newArrayList();

    // AWS WEB MANAGEMENT CONSOLE LOGIN & PASSWORD
    try {
        LoginProfile loginProfile = iam.getLoginProfile(new GetLoginProfileRequest(user.getUserName()))
                .getLoginProfile();
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", "#your password has already been generated and sent to you#");

        logger.info("Login profile already exists {}", loginProfile);
    } catch (NoSuchEntityException e) {
        // manually add a number to ensure amazon policy is respected
        String password = RandomStringUtils.randomAlphanumeric(10) + random.nextInt(10);
        LoginProfile loginProfile = iam
                .createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password))
                .getLoginProfile();
        userAccountChanges.add("Create user.login");
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", password);
    }

    // ADD USER TO GROUP
    Group group = groupDescriptor.getGroup();
    List<User> groupMembers = groupDescriptor.getUsers();

    boolean isUserInGroup = Iterables.any(groupMembers, new Predicate<User>() {
        public boolean apply(User groupMember) {
            return userName.equals(groupMember.getUserName());
        }

        ;
    });

    if (!isUserInGroup) {
        logger.debug("Add user {} to group {}", user, group);
        iam.addUserToGroup(new AddUserToGroupRequest(group.getGroupName(), user.getUserName()));
        groupMembers.add(user);
        userAccountChanges.add("Add user to group");
    }

    // ACCESS KEY
    boolean activeAccessKeyExists = false;
    ListAccessKeysResult listAccessKeysResult = iam
            .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName()));
    for (AccessKeyMetadata accessKeyMetadata : listAccessKeysResult.getAccessKeyMetadata()) {
        StatusType status = StatusType.fromValue(accessKeyMetadata.getStatus());
        if (StatusType.Active.equals(status)) {
            logger.info("Access key {} ({}) is already active, don't create another one.",
                    accessKeyMetadata.getAccessKeyId(), accessKeyMetadata.getCreateDate());
            activeAccessKeyExists = true;
            templatesParams.put("accessKeyId", accessKeyMetadata.getAccessKeyId());
            templatesParams.put("accessKeySecretId",
                    "#accessKey has already been generated and the secretId has been sent to you#");

            break;
        }
    }

    if (!activeAccessKeyExists) {
        AccessKey accessKey = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()))
                .getAccessKey();
        userAccountChanges.add("Create user.accessKey");
        logger.debug("Created access key {}", accessKey);
        templatesParams.put("accessKeyId", accessKey.getAccessKeyId());
        templatesParams.put("accessKeySecretId", accessKey.getSecretAccessKey());

        // email attachment: aws-credentials.txt
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            templatesParams.put("attachedCredentialsFileName", awsCredentialsBodyPart.getFileName());
            String awsCredentials = FreemarkerUtils.generate(templatesParams,
                    "/fr/xebia/cloud/amazon/aws/iam/aws-credentials.txt.ftl");
            awsCredentialsBodyPart.setContent(awsCredentials, "text/plain");
            attachments.add(awsCredentialsBodyPart);
        }

    }

    // SSH KEY PAIR
    if (keyPairName == null) { // If keyPairName is null, generate it from the username
        if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) {
            keyPairName = userName.substring(0, userName.indexOf("@xebia."));
        } else {
            keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_");
        }
    }

    try {
        List<KeyPairInfo> keyPairInfos = ec2
                .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)).getKeyPairs();
        KeyPairInfo keyPairInfo = Iterables.getOnlyElement(keyPairInfos);
        logger.info("SSH key {} already exists. Don't overwrite it.", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyName", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyFingerprint", keyPairInfo.getKeyFingerprint());

        String sshKeyFileName = keyPairName + ".pem";
        URL sshKeyFileURL = Thread.currentThread().getContextClassLoader().getResource(sshKeyFileName);
        if (sshKeyFileURL != null) {
            logger.info("SSH Key file {} found.", sshKeyFileName);

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyFileName);
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(Resources.toString(sshKeyFileURL, Charsets.ISO_8859_1),
                    "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            logger.info("SSH Key file {} NOT found.", sshKeyFileName);
        }

    } catch (AmazonServiceException e) {
        if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) {
            // ssh key does not exist, create it
            KeyPair keyPair = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName)).getKeyPair();
            userAccountChanges.add("Create ssh key");

            logger.info("Created ssh key {}", keyPair);
            templatesParams.put("sshKeyName", keyPair.getKeyName());
            templatesParams.put("sshKeyFingerprint", keyPair.getKeyFingerprint());

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(keyPair.getKeyName() + ".pem");
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(keyPair.getKeyMaterial(), "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            throw e;
        }
    }

    // X509 SELF SIGNED CERTIFICATE
    Collection<SigningCertificate> certificates = iam
            .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName))
            .getCertificates();
    // filter active certificates
    certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() {
        @Override
        public boolean apply(SigningCertificate signingCertificate) {
            return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus()));
        }
    });

    if (certificates.isEmpty()) {
        java.security.KeyPair x509KeyPair = keyPairGenerator.generateKeyPair();
        X509Certificate x509Certificate = generateSelfSignedX509Certificate(userName, x509KeyPair);
        String x509CertificatePem = Pems.pem(x509Certificate);

        UploadSigningCertificateResult uploadSigningCertificateResult = iam.uploadSigningCertificate( //
                new UploadSigningCertificateRequest(x509CertificatePem).withUserName(user.getUserName()));
        SigningCertificate signingCertificate = uploadSigningCertificateResult.getCertificate();
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
        userAccountChanges.add("Create x509 certificate");

        logger.info("Created x509 certificate {}", signingCertificate);

        // email attachment: x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509PrivateKeyFileName", x509PrivateKeyBodyPart.getFileName());
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/x-x509-ca-cert");
            attachments.add(x509PrivateKeyBodyPart);
        }
        // email attachment: x509 certifiate pem
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509CertificateFileName", x509CertificateBodyPart.getFileName());
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/x-x509-ca-cert");
            attachments.add(x509CertificateBodyPart);
        }

    } else {
        SigningCertificate signingCertificate = Iterables.getFirst(certificates, null);
        logger.info("X509 certificate {} already exists", signingCertificate.getCertificateId());
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
    }

    sendEmail(templatesParams, attachments, userName);
}

From source file:dagger.internal.codegen.BindingFactory.java

private boolean multibindingRequiresProduction(Key key,
        Iterable<ContributionBinding> multibindingContributions) {
    if (MapType.isMap(key)) {
        MapType mapType = MapType.from(key);
        if (mapType.valuesAreTypeOf(Producer.class) || mapType.valuesAreTypeOf(Produced.class)) {
            return true;
        }//w w  w  .  jav  a2s .  c o m
    } else if (SetType.isSet(key) && SetType.from(key).elementsAreTypeOf(Produced.class)) {
        return true;
    }
    return Iterables.any(multibindingContributions,
            binding -> binding.bindingType().equals(BindingType.PRODUCTION));
}