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

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

Introduction

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

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:com.atlassian.jira.license.DefaultLicenseRoleManager.java

@Nonnull
@Override//from  w  ww. j  a v  a  2  s  . c  o  m
public Optional<LicenseRoleDefinition> getLicenseRoleDefinition(@Nonnull final LicenseRoleId licenseRoleId) {
    Assertions.notNull("licenseRoleId", licenseRoleId);

    return Iterables.tryFind(getDefinedLicenseRoles(), findId(licenseRoleId));
}

From source file:org.apache.drill.exec.store.easy.text.compliant.CompliantTextRecordReader.java

@Override
public boolean isStarQuery() {
    if (settings.isUseRepeatedVarChar()) {
        return super.isStarQuery() || Iterables.tryFind(getColumns(), new Predicate<SchemaPath>() {
            @Override/*from  www.  j  a va2s  . c o m*/
            public boolean apply(@Nullable SchemaPath path) {
                return path.equals(RepeatedVarCharOutput.COLUMNS);
            }
        }).isPresent();
    }
    return super.isStarQuery();
}

From source file:org.jclouds.cloudservers.compute.predicates.GetImageWhenStatusActivePredicateWithResult.java

private org.jclouds.cloudservers.domain.Image findImage(final int id) {
    return Iterables.tryFind(client.listImages(new ListOptions().withDetails()),
            new Predicate<org.jclouds.cloudservers.domain.Image>() {
                @Override//from   www  . ja v a2 s  . com
                public boolean apply(org.jclouds.cloudservers.domain.Image input) {
                    return input.getId() == id;
                }
            }).orNull();

}

From source file:org.isisaddons.wicket.gmap3.cpt.ui.CollectionOfEntitiesAsLocatables.java

private void buildGui() {

    final EntityCollectionModel model = getModel();
    final List<ObjectAdapter> adapterList = model.getObject();

    final Optional<ObjectAdapter> firstIfAny = Iterables.tryFind(adapterList, input -> {
        GLatLng latLng = asGLatLng((Locatable) input.getObject());
        return latLng != null;
    });/*from w  ww.j  av  a 2s  .  com*/

    final boolean visible = firstIfAny.isPresent();

    final GMap map = new GMap(ID_MAP, apiKey) {
        @Override
        protected void onComponentTag(final ComponentTag tag) {
            super.onComponentTag(tag);
            if (!visible) {
                final AttributeModifier modifier = new AttributeAppender("class", " " + INVISIBLE_CLASS);
                tag.addBehavior(modifier);
            }
        }
    };
    map.setStreetViewControlEnabled(true);
    map.setScaleControlEnabled(true);
    map.setPanControlEnabled(true);
    map.setDoubleClickZoomEnabled(true);

    if (firstIfAny.isPresent()) {

        // centre the map on the first object that has a location.
        final ObjectAdapter first = firstIfAny.get();
        map.setCenter(asGLatLng((Locatable) first.getObject()));
    }

    addOrReplace(map);

    addMarkers(map, adapterList);
}

From source file:org.ow2.petals.cloud.manager.openstack.OpenStackProviderManager.java

public Node createNode(final Provider provider, final Node node) throws CloudManagerException {
    logger.debug("Creating node on provider {} :{}", provider, node);

    Nova client = getClient(provider);//from   w  ww .  jav  a  2 s . c o  m
    checkNotNull(client, "Can not create client with the provider information");

    Images images = client.images().list(false).execute();
    Image image = Iterables.tryFind(images, new Predicate<Image>() {
        public boolean apply(com.woorea.openstack.nova.model.Image image) {
            return image.getName().toLowerCase().contains(node.getVm().getImage());
        }
    }).orNull();

    if (image == null) {
        throw new CloudManagerException("No valid image found");
    }

    final String flavorName = null;
    Flavors flavors = client.flavors().list(true).execute();
    if (flavors.getList().size() == 0) {
        throw new CloudManagerException("Can not find any flavor on the provider");

    }
    Flavor flavor = Iterables.tryFind(flavors, new Predicate<Flavor>() {
        public boolean apply(com.woorea.openstack.nova.model.Flavor flavor) {
            return flavor.getName().equals(flavorName);
        }
    }).or(flavors.getList().get(0));

    ServerForCreate create = new ServerForCreate();
    create.setName(node.getName());

    // TODO : Get key from context
    if (getProperty(node, "iaas.key") != null) {
        create.setKeyName((getProperty(node, "iaas.key")).getValue());
    } else {
        Property p = getProperty(provider.getProperties(), "iaas.key");
        if (p != null) {
            create.setKeyName(p.getValue());
        }
    }

    if (create.getKeyName() == null) {
        logger.warn("Attempting to create a node without a security key...");
    } else {
        logger.info("Key name " + create.getKeyName());
    }

    create.setFlavorRef(flavor.getId());
    create.setImageRef(image.getId());
    Map<String, String> meta = Maps.newHashMap();

    // add all the properties from the input node, will be used if needed...
    meta.putAll(hasMap(node.getProperties()));
    meta.putAll(hasMap(provider.getProperties()));
    create.setMetadata(meta);

    Server server = client.servers().boot(create).execute();

    if (logger.isInfoEnabled()) {
        logger.info("Openstack create server API call returned : " + server);
    }
    return Adapter.to(server);
}

From source file:org.ow2.play.governance.platform.user.service.PermissionCheck.java

@Override
public boolean checkResource(final String user, final String resource) {

    Set<String> groups = getGroupsForResource(resource);
    Optional<String> ok = Iterables.tryFind(groups, new Predicate<String>() {
        public boolean apply(String group) {
            return checkGroup(user, group);
        };//from  w  ww . j  ava  2 s . co  m
    });
    return ok.isPresent();
}

From source file:com.nirima.jenkins.repo.util.HudsonWalker.java

/**
 * visit project chain, from current through parents.
 * @param visitor// ww w. j  a v  a2s .  c  om
 * @param run
 */
public static void traverseChain(HudsonVisitor visitor, Run run) {
    if (run == null)
        return;

    traverse(visitor, run);

    RepositoryAction repositoryAction = run.getAction(RepositoryAction.class);

    if (repositoryAction != null) {
        if (repositoryAction instanceof ProjectRepositoryAction) {
            final ProjectRepositoryAction projectRepositoryAction = (ProjectRepositoryAction) repositoryAction;

            AbstractProject item = (AbstractProject) Hudson.getInstance()
                    .getItem(projectRepositoryAction.getProjectName());

            Optional<Run> r = Iterables.tryFind(item.getBuilds(), new Predicate<Run>() {
                public boolean apply(Run run) {
                    return run.getNumber() == projectRepositoryAction.getBuildNumber();
                }
            });

            if (r.isPresent())
                traverseChain(visitor, r.get());
        }
    }

}

From source file:pt.ist.maidSyncher.domain.activeCollab.ACMilestone.java

public static ACMilestone findMilestone(final pt.ist.maidSyncher.domain.activeCollab.ACProject acProject,
        final String milestoneName) {
    return (ACMilestone) Iterables.tryFind(MaidRoot.getInstance().getAcObjectsSet(), new Predicate<ACObject>() {
        @Override//from w  ww .  j  av  a  2s  . co  m
        public boolean apply(ACObject input) {
            if (input == null)
                return false;
            if (input instanceof ACMilestone) {
                ACMilestone acMilestone = (ACMilestone) input;
                return ObjectUtils.equals(acMilestone.getProject(), acProject)
                        && (StringUtils.equalsIgnoreCase(acMilestone.getName(), milestoneName));
            }
            return false;
        }
    }).orNull();

}

From source file:org.gradle.internal.component.AmbiguousConfigurationSelectionException.java

static void formatConfiguration(StringBuilder sb, AttributeContainer fromConfigurationAttributes,
        AttributesSchema consumerSchema, List<ConfigurationMetadata> matches, Set<String> requestedAttributes,
        int maxConfLength, final String conf) {
    Optional<ConfigurationMetadata> match = Iterables.tryFind(matches, new Predicate<ConfigurationMetadata>() {
        @Override//from w w  w.j av  a 2s .co  m
        public boolean apply(ConfigurationMetadata input) {
            return conf.equals(input.getName());
        }
    });
    if (match.isPresent()) {
        AttributeContainer producerAttributes = match.get().getAttributes();
        Set<Attribute<?>> targetAttributes = producerAttributes.keySet();
        Set<String> targetAttributeNames = Sets
                .newTreeSet(Iterables.transform(targetAttributes, ATTRIBUTE_NAME));
        Set<Attribute<?>> allAttributes = Sets.union(fromConfigurationAttributes.keySet(),
                producerAttributes.keySet());
        Set<String> commonAttributes = Sets.intersection(requestedAttributes, targetAttributeNames);
        Set<String> consumerOnlyAttributes = Sets.difference(requestedAttributes, targetAttributeNames);
        sb.append("   ").append("- Configuration '").append(StringUtils.rightPad(conf + "'", maxConfLength + 1))
                .append(" :");
        List<Attribute<?>> sortedAttributes = Ordering.usingToString().sortedCopy(allAttributes);
        List<String> values = new ArrayList<String>(sortedAttributes.size());
        formatAttributes(sb, fromConfigurationAttributes, consumerSchema, producerAttributes, commonAttributes,
                consumerOnlyAttributes, sortedAttributes, values);
    }
}

From source file:org.killbill.billing.payment.core.sm.RetryablePaymentStateContext.java

public PaymentTransaction getCurrentTransaction() {
    if (result == null || result.getTransactions() == null) {
        return null;
    }//from   www.  j  a  v  a  2  s .  com
    return Iterables.tryFind(result.getTransactions(), new Predicate<PaymentTransaction>() {
        @Override
        public boolean apply(final PaymentTransaction input) {
            return ((DefaultPaymentTransaction) input).getAttemptId().equals(attemptId);
        }
    }).orNull();
}