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:forge.util.storage.StorageBase.java

@Override
public T find(Predicate<T> condition) {
    return Iterables.tryFind(map.values(), condition).orNull();
}

From source file:com.bennavetta.vetinari.template.TemplateLoader.java

@Inject
public TemplateLoader(VetinariContext context, Set<TemplateEngine> templateEngines) {
    this.context = context;
    this.templateEngines = templateEngines;
    this.defaultTemplateEngine = Iterables.find(this.templateEngines,
            t -> t.getName().equals(this.context.getSiteConfig().getString("defaultTemplateEngine")));

    this.templateCache = CacheBuilder.newBuilder().build(new CacheLoader<String, Template>() {
        @Override//  w  w  w  .j ava  2 s  . co m
        public Template load(String templateName) throws Exception {
            final Path templatePath = context.getTemplateRoot().resolve(templateName);
            final String extension = getFileExtension(templateName);
            final TemplateEngine engine = Iterables
                    .tryFind(templateEngines, t -> Iterables.contains(t.getFileExtensions(), extension))
                    .or(defaultTemplateEngine);
            log.debug("Compiling template from {} with {}", templatePath, engine);
            String source = new String(Files.readAllBytes(templatePath), context.getContentEncoding());
            log.trace("Read template source \"{}\"", source);
            return engine.compile(source);
        }
    });
}

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

protected Nova getClient() throws CloudManagerException {
    Provider provider = checkNotNull(
            Iterables.tryFind(providerRegistryService.get(), new Predicate<Provider>() {
                public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Provider input) {
                    return input.getName().equals(account);
                }//  w  w  w.j  av  a 2 s  .  c  om
            }).orNull(), "Can not retrieve account %s from the registry", account);

    return Utils.getClient(provider, connector);
}

From source file:org.ow2.petals.cloud.manager.ec2.commands.BaseCommand.java

protected AmazonEC2 getClient() throws CloudManagerException {
    Provider provider = checkNotNull(
            Iterables.tryFind(providerRegistryService.get(), new Predicate<Provider>() {
                public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Provider input) {
                    return input.getName().equals(account);
                }/*from  www  .  j a  v a 2 s  . com*/
            }).orNull(), "Can not retrieve account %s from the registry", account);

    Credentials credentials = provider.getCredentials();
    AWSCredentials awsCredentials = new BasicAWSCredentials(credentials.getPublicKey(),
            credentials.getPrivateKey());
    AmazonEC2 ec2 = new AmazonEC2Client(awsCredentials);
    ec2.setEndpoint(provider.getEndpoint());
    // TODO in properties
    //ec2.setRegion(provider.getRegion());
    ec2.setRegion(Region.getRegion(Regions.DEFAULT_REGION));
    return ec2;
}

From source file:org.apache.druid.query.topn.NumericTopNMetricSpec.java

@Override
public void verifyPreconditions(List<AggregatorFactory> aggregatorSpecs,
        List<PostAggregator> postAggregatorSpecs) {
    Preconditions.checkNotNull(metric, "metric can't be null");
    Preconditions.checkNotNull(aggregatorSpecs, "aggregations cannot be null");
    Preconditions.checkArgument(aggregatorSpecs.size() > 0 || postAggregatorSpecs.size() > 0,
            "Must have at least one AggregatorFactory or PostAggregator");

    final AggregatorFactory aggregator = Iterables.tryFind(aggregatorSpecs, new Predicate<AggregatorFactory>() {
        @Override//from   w  w  w .  j  a  v a  2s.c o  m
        public boolean apply(AggregatorFactory input) {
            return input.getName().equals(metric);
        }
    }).orNull();

    final PostAggregator postAggregator = Iterables
            .tryFind(postAggregatorSpecs, new Predicate<PostAggregator>() {
                @Override
                public boolean apply(PostAggregator input) {
                    return input.getName().equals(metric);
                }
            }).orNull();

    Preconditions.checkArgument(aggregator != null || postAggregator != null,
            "Must have an AggregatorFactory or PostAggregator for metric[%s], gave[%s] and [%s]", metric,
            aggregatorSpecs, postAggregatorSpecs);
}

From source file:stormy.pythian.core.topology.AvailableComponentPool.java

public ComponentConfiguration getAvailableComponent() {
    return Iterables.tryFind(components, IS_AVAILABLE).orNull();
}

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

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

    connectServiceUpIsRunning();/*from w ww .j  av  a 2s. c o m*/

    // 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";
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    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"))
                    .enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(TOTAL_CONNECTIONS_RECEIVED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_connections_received")).enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(TOTAL_COMMANDS_PROCESSED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_commands_processed")).enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(EXPIRED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("expired_keys"))
                    .enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(EVICTED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("evicted_keys"))
                    .enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(KEYSPACE_HITS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_hits"))
                    .enabled(retrieveUsageMetrics))
            .poll(new SshPollConfig<Integer>(KEYSPACE_MISSES).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_misses"))
                    .enabled(retrieveUsageMetrics))
            .build();
}

From source file:org.apache.brooklyn.core.location.access.PortForwardManagerLocationResolver.java

@Override
public Location newLocationFromString(Map locationFlags, String spec, 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 {//from w ww  . j  a  v a  2s .  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:com.eucalyptus.config.ws.PropertiesRequestLoggingFilter.java

@Override
public Collection<String> apply(final Collection<String> parametersOrBody) {
    if (Iterables.tryFind(ACTION_NVPS, Predicates.in(parametersOrBody)).isPresent()) {
        final Optional<String> nameParameterAndValue = Iterables.tryFind(parametersOrBody,
                Strings.startsWith(NAME_PARAMETER));
        final Optional<String> valueParameterAndValue = Iterables.tryFind(parametersOrBody,
                Strings.startsWith(VALUE_PARAMETER));

        if (nameParameterAndValue.isPresent() && valueParameterAndValue.isPresent())
            try {
                final ConfigurableProperty entry = PropertyDirectory
                        .getPropertyEntry(Strings.trimPrefix(NAME_PARAMETER, nameParameterAndValue.get()));
                if (ConfigurableFieldType.KEYVALUEHIDDEN == entry.getWidgetType()) {
                    final ArrayList<String> parametersCopy = Lists.newArrayList(parametersOrBody);
                    parametersCopy.set(parametersCopy.indexOf(valueParameterAndValue.get()),
                            VALUE_PARAMETER_REDACTED);
                    return parametersCopy;
                }/* ww w.  jav a  2  s. c  o  m*/
            } catch (IllegalAccessException e) {
                // property not found
            }
    }

    return parametersOrBody;
}

From source file:org.eclipse.emf.compare.uml2.internal.provider.decorator.StereotypeReferenceChangeItemProviderDecorator.java

/**
 * Retrieves the {@link ReferenceChange} which is refined by the {@link StereotypeReferenceChange}.
 * // ww w  .  j  av a2s .  c o m
 * @param diff
 *            Input object. .
 * @return an {@link ReferenceChange} if the input is a {@link StereotypeReferenceChange} which is refined
 *         by an {@link ReferenceChange} or <code>null</code> otherwise.
 */
private ReferenceChange getReferenceChange(Object diff) {
    ReferenceChange referenceChange = null;
    if (diff instanceof StereotypeReferenceChange) {
        StereotypeReferenceChange stereotypeReferenceChange = (StereotypeReferenceChange) diff;
        Optional<Diff> element = Iterables.tryFind(stereotypeReferenceChange.getRefinedBy(),
                Predicates.instanceOf(ReferenceChange.class));
        if (element.isPresent()) {
            referenceChange = (ReferenceChange) element.get();
        }
    }
    return referenceChange;
}