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:org.robotstxt4j.model.RobotsTxt.java

public boolean isUserAgentAllowed(final UserAgent userAgent, final RelativePath path) {
    final Optional<DisallowDirective> found = Iterables.tryFind(disallowDirectives,
            new Predicate<DisallowDirective>() {
                @Override/*from  ww w.  ja va  2 s .  co  m*/
                public boolean apply(final DisallowDirective input) {
                    return input.disallows(userAgent, path);
                }
            });

    return !found.isPresent();
}

From source file:io.pelle.mango.client.web.modules.webhook.WebHookModule.java

public Optional<WebhookDefinition> getWebHookDefinitionById(final String id) {
    return Iterables.tryFind(WEBHOOK_DEFINITIONS, new Predicate<WebhookDefinition>() {
        @Override//from www.ja va 2s  . c o m
        public boolean apply(WebhookDefinition input) {
            return input.getId().equals(id);
        }
    });
}

From source file:org.jclouds.vcloud.director.v1_5.functions.URNToAdminHref.java

@Override
public URI apply(@Nullable Object from) {
    checkArgument(checkNotNull(from, "urn") instanceof String, "urn is a String argument");
    Entity entity = resolveEntityCache.getUnchecked(from.toString());
    Optional<Link> link = Iterables.tryFind(entity.getLinks(), typeContainsAdmin);
    checkArgument(link.isPresent(), "no admin link found for entity %s", entity);
    return link.get().getHref();
}

From source file:org.estatio.dom.communicationchannel.PostalAddresses.java

@Programmatic
public PostalAddress findByAddress(final CommunicationChannelOwner owner, final String address1,
        final String postalCode, final String city, final Country country) {

    final List<CommunicationChannelOwnerLink> links = communicationChannelOwnerLinks
            .findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.POSTAL_ADDRESS);
    final Iterable<PostalAddress> postalAddresses = Iterables.transform(links,
            CommunicationChannelOwnerLink.Functions.communicationChannel(PostalAddress.class));
    final Optional<PostalAddress> postalAddressIfFound = Iterables.tryFind(postalAddresses,
            PostalAddress.Predicates.equalTo(address1, postalCode, city, country));
    return postalAddressIfFound.orNull();
}

From source file:de.brands4friends.daleq.core.internal.types.CachingTableTypeRepository.java

private TableType doGet(final TableTypeReference tableRef) {
    final Optional<TableTypeResolver> resolver = Iterables.tryFind(resolvers,
            new Predicate<TableTypeResolver>() {
                @Override//from  w  w  w. j  a  v a2 s. c  o  m
                public boolean apply(@Nullable final TableTypeResolver resolver) {
                    if (resolver == null) {
                        return false;
                    }
                    return resolver.canResolve(tableRef);
                }
            });
    if (!resolver.isPresent()) {
        throw new DaleqBuildException("No TableTypeResolver registered for " + tableRef);
    }

    return resolver.get().resolve(tableRef);
}

From source file:clocker.docker.entity.microservice.MicroserviceDockerfileImpl.java

@Override
protected void doStart(Collection<? extends Location> locations) {
    Optional<Location> dockerLocation = Iterables.tryFind(getLocations(),
            Predicates.instanceOf(DockerLocation.class));

    if (!dockerLocation.isPresent()) {
        String locationName = DOCKER_LOCATION_PREFIX + getId();
        DockerInfrastructure dockerInfrastructure = addChild(EntitySpec.create(DockerInfrastructure.class)
                .configure(DockerInfrastructure.DOCKER_HOST_CLUSTER_MIN_SIZE, 1)
                .configure(DockerInfrastructure.SDN_ENABLE, false)
                .configure(DockerInfrastructure.LOCATION_NAME, locationName)
                .displayName("Docker Infrastructure"));

        Entities.start(dockerInfrastructure, locations);

        dockerLocation = Optional.of(getManagementContext().getLocationRegistry().resolve(locationName));
    }//w  w w. j av  a2s . c o  m

    Entities.start(vanillaDockerApplication, dockerLocation.asSet());
}

From source file:com.bennavetta.vetinari.build.internal.phase.TemplatePhase.java

private TemplateEngine getTemplateEngine(Page page, Site site) {
    TemplateEngine templateEngine = null;
    // Use the second file extension, if any. The first is for the renderer.
    final String templateExtension = getFileExtension(getNameWithoutExtension(page.getPath().toString()));
    Optional<TemplateEngine> templateEngineFromExtension = Iterables.tryFind(templateEngines,
            t -> Iterables.contains(t.getFileExtensions(), templateExtension));
    if (templateEngineFromExtension.isPresent()) {
        templateEngine = templateEngineFromExtension.get();
    } else if (page.getMetadata().hasPath("templateEngine")) {
        final String templateEngineName = page.getMetadata().getString("templateEngine");
        templateEngine = Iterables.find(templateEngines, t -> templateEngineName.equals(t.getName()));
    } else {//  www  . ja  v  a 2  s .  co m
        templateEngine = Iterables.find(templateEngines,
                t -> site.getDefaultTemplateEngine().equals(t.getName()));
    }
    return templateEngine;
}

From source file:org.killbill.billing.util.nodes.NodeInfoMapper.java

public NodeCommandMetadata deserializeNodeCommand(final String nodeCommand, final String type)
        throws IOException {

    final SystemNodeCommandType systemType = Iterables.tryFind(
            ImmutableList.copyOf(SystemNodeCommandType.values()), new Predicate<SystemNodeCommandType>() {
                @Override//www . j  ava2  s . c o  m
                public boolean apply(final SystemNodeCommandType input) {
                    return input.name().equals(type);
                }
            }).orNull();

    return (systemType != null) ? mapper.readValue(nodeCommand, systemType.getCommandMetadataClass())
            : mapper.readValue(nodeCommand, DefaultNodeCommandMetadata.class);
}

From source file:brooklyn.location.access.PortForwardManagerLocationResolver.java

@Override
public Location newLocationFromString(Map locationFlags, String spec,
        brooklyn.location.LocationRegistry registry) {
    ConfigBag config = extractConfig(locationFlags, spec, registry);
    Map globalProperties = registry.getProperties();
    String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
    String scope = config.get(PortForwardManager.SCOPE);

    Optional<Location> result = Iterables.tryFind(managementContext.getLocationManager().getLocations(),
            Predicates.and(Predicates.instanceOf(PortForwardManager.class),
                    LocationPredicates.configEqualTo(PortForwardManager.SCOPE, scope)));

    if (result.isPresent()) {
        return result.get();
    } else {/*w w  w  . ja v a 2 s .c o m*/
        PortForwardManager loc = managementContext.getLocationManager()
                .createLocation(LocationSpec.create(PortForwardManagerImpl.class)
                        .configure(config.getAllConfig()).configure(LocationConfigUtils
                                .finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));

        if (LOG.isDebugEnabled())
            LOG.debug("Created " + loc + " for scope " + scope);
        return loc;
    }
}

From source file:brooklyn.entity.nosql.redis.RedisStoreImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();

    connectServiceUpIsRunning();/*from ww  w  .  j a  v a 2s .com*/

    // Find an SshMachineLocation for the UPTIME feed
    Optional<Location> location = Iterables.tryFind(getLocations(),
            Predicates.instanceOf(SshMachineLocation.class));
    if (!location.isPresent())
        throw new IllegalStateException("Could not find SshMachineLocation in list of locations");
    SshMachineLocation machine = (SshMachineLocation) location.get();
    String statsCommand = getDriver().getRunDir() + "/bin/redis-cli -p " + getRedisPort() + " info stats";

    sshFeed = SshFeed.builder().entity(this).machine(machine).period(5, TimeUnit.SECONDS)
            .poll(new SshPollConfig<Integer>(UPTIME)
                    .command(getDriver().getRunDir() + "/bin/redis-cli -p " + getRedisPort() + " info server")
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("uptime_in_seconds")))
            .poll(new SshPollConfig<Integer>(TOTAL_CONNECTIONS_RECEIVED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_connections_received")))
            .poll(new SshPollConfig<Integer>(TOTAL_COMMANDS_PROCESSED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_commands_processed")))
            .poll(new SshPollConfig<Integer>(EXPIRED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("expired_keys")))
            .poll(new SshPollConfig<Integer>(EVICTED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("evicted_keys")))
            .poll(new SshPollConfig<Integer>(KEYSPACE_HITS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_hits")))
            .poll(new SshPollConfig<Integer>(KEYSPACE_MISSES).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_misses")))
            .build();
}