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.android.build.gradle.model.ComponentNativeLibraryFactory.java

@NonNull
@Override/*from  w w  w.j ava2  s. c  o m*/
public Optional<NativeLibrary> create(@NonNull VariantScope scope, @NonNull String toolchainName,
        @NonNull final Abi abi) {
    BaseVariantData<? extends BaseVariantOutputData> variantData = scope.getVariantData();

    DefaultAndroidBinary androidBinary = (DefaultAndroidBinary) binaries.findByName(variantData.getName());

    if (androidBinary == null) {
        // Binaries are not created for test variants.
        return Optional.absent();
    }

    @SuppressWarnings("ConstantConditions")
    Optional<NativeLibraryBinarySpec> nativeBinary = Iterables.tryFind(androidBinary.getNativeBinaries(),
            new Predicate<NativeLibraryBinarySpec>() {
                @Override
                public boolean apply(NativeLibraryBinarySpec binary) {
                    return binary.getTargetPlatform().getName().equals(abi.getName());
                }
            });

    if (!nativeBinary.isPresent()) {
        // We don't have native binaries.
        return Optional.absent();
    }

    CoreNdkOptions ndkConfig = variantData.getVariantConfiguration().getNdkConfig();
    // The DSL currently do not support all options available in the model such as the
    // include dirs and the defines.  Therefore, just pass an empty collection for now.
    return Optional.<NativeLibrary>of(new NativeLibraryImpl(ndkConfig.getModuleName(), toolchainName,
            abi.getName(), Collections.<File>emptyList(), /*cIncludeDirs*/
            Collections.<File>emptyList(), /*cppIncludeDirs*/
            Collections.<File>emptyList(), /*cSystemIncludeDirs*/
            ndkHandler.getStlIncludes(ndkConfig.getStl(), abi), Collections.<String>emptyList(), /*cDefines*/
            Collections.<String>emptyList(), /*cppDefines*/
            BinaryToolHelper.getCCompiler(nativeBinary.get()).getArgs(),
            BinaryToolHelper.getCppCompiler(nativeBinary.get()).getArgs(),
            ImmutableList.of(variantData.getScope().getNdkDebuggableLibraryFolders(abi))));
}

From source file:org.ow2.petals.cloud.manager.core.puppet.InstallPackagesScriptBuilder.java

/**
 * Get packages to install from the software properties.
 * Node contains softwares which are links to upper level deployment script.
 *
 * @param node/* w  w  w. jav  a 2 s  .  co  m*/
 * @param context
 * @return
 */
protected List<String> getPackages(final Node node, final Context context) {
    checkNotNull(context.getDescriptor());
    checkNotNull(context.getDescriptor().getSoftwares());

    // have a look to all the software which link to a package type software in the descriptor.
    return Lists.newArrayList(Iterables.filter(node.getSoftwares(), new Predicate<String>() {
        public boolean apply(final String input) {
            return Iterables.tryFind(context.getDescriptor().getSoftwares(), new Predicate<Software>() {
                public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Software software) {
                    return input.equals(software.getName())
                            && software.getType().equals(Constants.PACKAGE_TYPE);
                }
            }).isPresent();
        }
    }));
}

From source file:org.ow2.petals.cloud.controllers.core.services.DeploymentService.java

public VirtualContainer deploy(Topology topology, DeploymentListener deploymentListener)
        throws ControllerException {
    String id = UUID.randomUUID().toString();

    deploymentListener.on(id, "deploy.start", null);

    if (id == null || topology == null) {
        throw new ControllerException("Can not deploy null things...");
    }/* ww  w  . ja v  a 2s  . co m*/

    if (topology.getRuntimes() == null || topology.getRuntimes().size() == 0) {
        throw new ControllerException("Topology can not be null nor empty");
    }

    deploymentListener.on(id, "master.lookup", null);

    // get nodes to deploy first
    // For now we just look at the master
    // TODO : Deployment rules to be plugged here
    final Optional<PetalsRuntime> master = Iterables.tryFind(topology.getRuntimes(),
            new Predicate<PetalsRuntime>() {
                public boolean apply(org.ow2.petals.cloud.controllers.api.runtime.PetalsRuntime input) {
                    return input.getMode() == PetalsRuntime.MODE.MASTER;
                }
            });

    Set<PetalsRuntime> remains = null;

    /*
    if (master.isPresent()) {
    deploymentListener.on(id, "master.found", null);
    // deploy the master first...
    // TODO : Create properties to be injected in the VM
            
    Properties props = new Properties();
    props.put("localcontainerid", master.get().getName());
    props.put("controllerEndpoint", "http://locahost");
    props.put("virtualContainerId", id);
    // TODO : Fill more data from runtime
            
    Node node = null;
    try {
        deploymentListener.on(id, "master.create", "%s", master.get().getName());
        node = providerManager.createNode(DEFAULT, props);
        listener.onCreateSuccess(node);
    } catch (Exception e) {
        listener.onCreateFailure(node);
    }
            
    deploymentListener.on(id, "master.start", "%s", master.get().getName());
    long time = 10;
    try {
        deploymentListener.on(id, "master.wait", "%s", master.get().getName());
        PetalsNodeUtils.waitNodeToStart(master.get(), time, TimeUnit.MINUTES);
    } catch (TimeoutException e) {
        listener.onDeployFailure(node);
        throw new CloudManagerException("Can not start the Petals node within " + time + TimeUnit.MINUTES);
    }
    listener.onDeploySuccess(node);
            
    remains = Sets.filter(Sets.newHashSet(topology.getRuntimes()), new Predicate<PetalsRuntime>() {
        public boolean apply(org.ow2.petals.controllers.manager.runtime.PetalsRuntime runtime) {
            return !runtime.getName().equals(master.get().getName());
        }
    });
            
    } else {
    deploymentListener.on(id, "!master.found", null);
    remains = Sets.newHashSet(topology.getRuntimes());
    }
            
    for(PetalsRuntime runtime : remains) {
            
    Properties props = new Properties();
    props.put("localcontainerid", master.get().getName());
    props.put("controllerEndpoint", "http://locahost");
    props.put("virtualContainerId", id);
    // TODO : Fill more data from runtime
            
    Node n = null;
    try {
        deploymentListener.on(id, "node.create", "%s", runtime.getName());
        n = providerManager.createNode(VMProperties.DEFAULT, env);
        listener.onCreateSuccess(n);
    } catch (Exception e) {
        listener.onCreateFailure(n);
    }
            
    deploymentListener.on(id, "node.start", "%s", runtime.getName());
            
    // TODO : Check that all nodes have been successfully started.
    // Note this can be done on the controller level
            
    }
    deploymentListener.on(id, "deploy.done", null);
    */
    return null;
}

From source file:xml.entity.mutableelement.InternalElement.java

@Override
@Nonnull/*from w w w  . j av  a  2  s  .  c  o m*/
public Element attribute(final String string) {
    final Optional<Element> matching = Iterables.tryFind(children(), Elements.byName("@" + string));
    if (matching.isPresent()) {
        return matching.get();
    } else {
        final Attribute child = new Attribute(string, null, this.factory);
        children.add(child);
        return child;
    }
}

From source file:com.opoopress.website.DocProcessor.java

@Override
public void postRead(Site site) {
    Collection collection = site.getCollections().get("doc");
    List<? extends Page> pages = collection.getPages();

    List<Map<String, Object>> versions = site.getConfig().get("doc_versions");

    log.info("Processing doc versions...");
    System.out.println("================");
    System.out.println(versions);
    System.out.println("----------------");

    if (versions == null || versions.isEmpty()) {
        throw new IllegalArgumentException("doc versions not defined in configuration.");
    }/*from   w  w w  .j  av a  2s  . c  om*/

    for (Map<String, Object> version : versions) {
        String ver = (String) version.get("version");
        //            String path = (String) version.get("path");
        String urlPrefix = (String) version.get("url_prefix");
        List<Map<String, Object>> items = site.getConfig().get("doc_items_" + ver);

        if (items == null || items.isEmpty()) {
            throw new IllegalArgumentException("doc items not found: doc_items_" + ver);
        }

        version.put("items", items);

        for (Map<String, Object> item : items) {
            //                String title = (String) item.get("title");
            List<String> docs = (List<String>) item.get("docs");
            List<Page> docPages = Lists.newArrayList();
            item.put("pages", docPages);

            for (String doc : docs) {
                final String docUrl = urlPrefix + doc;
                Page page = Iterables.tryFind(pages, new Predicate<Page>() {
                    @Override
                    public boolean apply(Page input) {
                        return docUrl.equals(input.getUrl());
                    }
                }).orNull();

                if (page == null) {
                    throw new IllegalStateException("doc url not found: " + docUrl);
                }
                docPages.add(page);
                log.info("Find page for: {} => {}", docUrl, page.getTitle());
                page.set("version", version);
            }
        }
    }
}

From source file:org.opendaylight.protocol.bgp.openconfig.impl.moduleconfig.RibInstanceFunction.java

@Override
public ListenableFuture<T> apply(final String instanceName) {
    final ListenableFuture<Optional<Service>> readFuture = configModuleOp
            .readConfigService(new ServiceKey(RibInstance.class), rTx);
    return Futures.transform(readFuture, new Function<Optional<Service>, T>() {
        @Override/* w w  w  . jav  a 2s .  c o  m*/
        public T apply(final Optional<Service> maybeService) {
            if (maybeService.isPresent()) {
                final Optional<Instance> maybeInstance = Iterables.tryFind(maybeService.get().getInstance(),
                        new Predicate<Instance>() {
                            @Override
                            public boolean apply(final Instance instance) {
                                final String moduleName = OpenConfigUtil.getModuleName(instance.getProvider());
                                if (moduleName.equals(instanceName)) {
                                    return true;
                                }
                                return false;
                            }
                        });
                if (maybeInstance.isPresent()) {
                    return function.apply(maybeInstance.get().getName());
                }
            }
            return null;
        }

    });
}

From source file:org.incode.module.commchannel.dom.impl.emailaddress.EmailAddressRepository.java

@Programmatic
public EmailAddress findByEmailAddress(final Object owner, final String emailAddress) {

    final List<CommunicationChannelOwnerLink> links = linkRepository
            .findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.EMAIL_ADDRESS);
    final Iterable<EmailAddress> emailAddresses = Iterables.transform(links,
            CommunicationChannelOwnerLink.Functions.communicationChannel(EmailAddress.class));
    final Optional<EmailAddress> emailAddressIfFound = Iterables.tryFind(emailAddresses,
            input -> Objects.equals(emailAddress, input.getEmailAddress()));
    return emailAddressIfFound.orNull();
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsProviderAndApiLoader.java

public static Optional<ApiMetadata> getApi(String id) {
    if (LazyServiceLoader.INSTANCE.apis.containsKey(id)) {
        return Optional.of(LazyServiceLoader.INSTANCE.apis.get(id));
    }/*from w  w  w .j  ava  2s.  c om*/
    return Iterables.tryFind(ApiRegistry.fromRegistry(), ApiPredicates.id(id));
}

From source file:gg.uhc.uhc.modules.team.TeamModule.java

public Optional<Team> findFirstEmptyTeam() {
    return Iterables.tryFind(teams.values(), Predicates.not(FunctionalUtil.TEAMS_WITH_PLAYERS));
}

From source file:org.killbill.billing.invoice.tree.ItemsInterval.java

public Item getCancelledItemIfExists(final UUID linkedId) {
    return Iterables.tryFind(items, new Predicate<Item>() {
        @Override//from   w w w .  j  av  a2  s  . c  o m
        public boolean apply(final Item input) {
            return input.getAction() == ItemAction.ADD && input.getId().equals(linkedId);
        }
    }).orNull();
}