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.ow2.petals.cloud.manager.commands.iaas.CreateVMCommand.java

private ProviderManager getManager(final String iaas) {
    return Iterables.tryFind(providerManagers, new Predicate<ProviderManager>() {
        public boolean apply(ProviderManager input) {
            return iaas.equalsIgnoreCase(input.getProviderName());
        }//  www .j  a  va 2  s.c o m
    }).orNull();
}

From source file:com.qcadoo.mes.basic.shift.ShiftTimetableExceptions.java

public Optional<DateRange> findDateRangeFor(final TimetableExceptionType type, final Date date) {
    // TODO MAKU optimize if needed (sorted dates + break if subsequent date range doesn't start after given date?).
    // But for now this might be an overhead so I'm leaving it out.
    return Iterables.tryFind(exceptions.get(type), new Predicate<DateRange>() {

        @Override//from w  w  w. j a va 2  s .  c  om
        public boolean apply(final DateRange dateRange) {
            return dateRange.contains(date);
        }
    });
}

From source file:org.apache.brooklyn.entity.nosql.etcd.EtcdClusterImpl.java

@Override
public void start(Collection<? extends Location> locs) {
    addLocations(locs);/*from  ww  w . j  a v  a  2  s . com*/
    List<Location> locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locs, this));

    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

    connectSensors();

    super.start(locations);

    Optional<Entity> anyNode = Iterables.tryFind(getMembers(),
            Predicates.and(Predicates.instanceOf(EtcdNode.class),
                    EntityPredicates.attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, true),
                    EntityPredicates.attributeEqualTo(Startable.SERVICE_UP, true)));
    if (config().get(Cluster.INITIAL_SIZE) == 0 || anyNode.isPresent()) {
        sensors().set(Startable.SERVICE_UP, true);
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } else {
        log.warn("No Etcd nodes are found on the cluster: {}. Initialization Failed", getId());
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
    }
}

From source file:com.axemblr.provisionr.commands.CreatePoolCommand.java

@Override
protected Object doExecute() throws Exception {
    checkArgument(size > 0, "size should be a positive integer");

    Optional<Provisionr> service = Iterables.tryFind(services, ProvisionrPredicates.withId(id));
    if (service.isPresent()) {
        final Pool pool = createPoolFromArgumentsAndServiceDefaults(service.get());

        final String processInstanceId = service.get().startPoolManagementProcess(key, pool);
        return String.format("Pool management process started (id: %s)", processInstanceId);
    } else {/*from w  w  w  .j  av a2s. c  o  m*/
        throw new NoSuchElementException("No provisioning service found with id: " + id);
    }
}

From source file:org.killbill.billing.catalog.DefaultPlanPhase.java

public DefaultPlanPhase(final DefaultPlan parentPlan, final DefaultPlanPhase in,
        @Nullable final PlanPhasePriceOverride override) {
    this.type = in.getPhaseType();
    this.duration = (DefaultDuration) in.getDuration();
    this.fixed = override != null && override.getFixedPrice() != null
            ? new DefaultFixed((DefaultFixed) in.getFixed(), override)
            : (DefaultFixed) in.getFixed();
    this.recurring = override != null && override.getRecurringPrice() != null
            ? new DefaultRecurring((DefaultRecurring) in.getRecurring(), override)
            : (DefaultRecurring) in.getRecurring();
    this.usages = new DefaultUsage[in.getUsages().length];
    for (int i = 0; i < in.getUsages().length; i++) {
        final Usage curUsage = in.getUsages()[i];
        if (override != null && override.getUsagePriceOverrides() != null) {
            final UsagePriceOverride usagePriceOverride = Iterables
                    .tryFind(override.getUsagePriceOverrides(), new Predicate<UsagePriceOverride>() {
                        @Override
                        public boolean apply(final UsagePriceOverride input) {
                            return input != null && input.getName().equals(curUsage.getName());
                        }/*  ww w  .  j  a  va 2 s.  c  o  m*/
                    }).orNull();
            usages[i] = (usagePriceOverride != null)
                    ? new DefaultUsage(in.getUsages()[i], usagePriceOverride, override.getCurrency())
                    : (DefaultUsage) curUsage;
        } else {
            usages[i] = (DefaultUsage) curUsage;
        }
    }
    this.plan = parentPlan;
}

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

public void tryObtainAndCheck(Map<?, ?> flags, Predicate<? super ConfigBag> test) {
    try {/*  w w w.j a v  a 2s. co  m*/
        obtain(flags);
    } catch (Exception e) {
        boolean found = Iterables.tryFind(Throwables.getCausalChain(e), Predicates.<Throwable>equalTo(e))
                .isPresent();
        if (!found && e instanceof CompoundRuntimeException) {
            for (Throwable cause : ((CompoundRuntimeException) e).getAllCauses()) {
                found = Iterables.tryFind(Throwables.getCausalChain(cause), Predicates.<Throwable>equalTo(e))
                        .isPresent();
                if (found)
                    break;
            }
        }
        if (found) {
            test.apply(lastConfigBag);
        } else {
            throw Exceptions.propagate(e);
        }
    }
}

From source file:com.arcbees.vcs.AbstractVcsApi.java

protected PullRequest findPullRequestForBranch(final String branchName, PullRequests pullRequests) {
    return (PullRequest) Iterables.tryFind(pullRequests.getPullRequests(), new Predicate<PullRequest>() {
        @Override/*w w w .ja  va  2s  .  c o m*/
        public boolean apply(PullRequest pullRequest) {
            PullRequestTarget source = pullRequest.getSource();
            Branch branch = source.getBranch();
            String pullRequestBranchName = branch.getName();

            return pullRequestBranchName.equals(branchName);
        }
    }).orNull();
}

From source file:org.jclouds.openstack.nova.v1_1.compute.NovaImageExtension.java

private org.jclouds.openstack.nova.v1_1.domain.Image findImage(final ZoneAndId zoneAndId) {
    return Iterables.tryFind(novaClient.getImageClientForZone(zoneAndId.getZone()).listImagesInDetail(),
            new Predicate<org.jclouds.openstack.nova.v1_1.domain.Image>() {
                @Override//  www  .ja  va  2  s. c o  m
                public boolean apply(org.jclouds.openstack.nova.v1_1.domain.Image input) {
                    return input.getId().equals(zoneAndId.getId());
                }
            }).orNull();

}

From source file:com.eucalyptus.compute.common.internal.network.NetworkGroups.java

public static void createDefault(final OwnerFullName ownerFullName) throws MetadataException {
    try (final TransactionResource tx = Entities.transactionFor(Vpc.class)) {
        if (Iterables.tryFind(Entities.query(Vpc.exampleDefault(ownerFullName.getAccountNumber())),
                Predicates.alwaysTrue()).isPresent()) {
            return; // skip default security group creation when there is a default VPC
        }/*ww  w  . j a va  2  s  .c o m*/
    }

    try {
        try {
            NetworkGroup net = Transactions.find(NetworkGroup.named(
                    AccountFullName.getInstance(ownerFullName.getAccountNumber()), DEFAULT_NETWORK_NAME));
            if (net == null) {
                create(ownerFullName, DEFAULT_NETWORK_NAME, "default group");
            }
        } catch (NoSuchElementException | TransactionException ex) {
            try {
                create(ownerFullName, DEFAULT_NETWORK_NAME, "default group");
            } catch (ConstraintViolationException ex1) {
            }
        }
    } catch (DuplicateMetadataException ex) {
    }
}

From source file:org.apache.brooklyn.entity.nosql.couchbase.CouchbaseSyncGatewaySshDriver.java

@Override
public void launch() {
    Entity cbNode = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER);
    Entities.waitForServiceUp(cbNode, Duration.ONE_HOUR);
    DependentConfiguration.waitInTaskForAttributeReady(cbNode, CouchbaseCluster.IS_CLUSTER_INITIALIZED,
            Predicates.equalTo(true));// www  . j ava 2s .  co m
    // Even once the bucket has published its API URL, it can still take a couple of seconds for it to become available
    Time.sleep(10 * 1000);
    if (cbNode instanceof CouchbaseCluster) {
        // in_cluster now applies even to a node in a cluster of size 1
        Optional<Entity> cbClusterNode = Iterables.tryFind(cbNode.getAttribute(CouchbaseCluster.GROUP_MEMBERS),
                Predicates.and(Predicates.instanceOf(CouchbaseNode.class),
                        EntityPredicates.attributeEqualTo(CouchbaseNode.IS_IN_CLUSTER, Boolean.TRUE)));

        if (!cbClusterNode.isPresent()) {
            throw new IllegalArgumentException(
                    format("The cluster %s does not contain any suitable Couchbase nodes to connect to..",
                            cbNode.getId()));
        }

        cbNode = cbClusterNode.get();
    }
    String hostname = cbNode.getAttribute(CouchbaseNode.HOSTNAME);
    String webPort = cbNode.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT).toString();

    String username = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME);
    String password = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD);

    String bucketName = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_BUCKET);
    String pool = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_POOL);
    String pretty = entity.getConfig(CouchbaseSyncGateway.PRETTY) ? "-pretty" : "";
    String verbose = entity.getConfig(CouchbaseSyncGateway.VERBOSE) ? "-verbose" : "";

    String adminRestApiPort = entity.getConfig(CouchbaseSyncGateway.ADMIN_REST_API_PORT).iterator().next()
            .toString();
    String syncRestApiPort = entity.getConfig(CouchbaseSyncGateway.SYNC_REST_API_PORT).iterator().next()
            .toString();

    String serverWebAdminUrl = format("http://%s:%s@%s:%s", username, password, hostname, webPort);
    String options = format(
            "-url %s -bucket %s -adminInterface 0.0.0.0:%s -interface 0.0.0.0:%s -pool %s %s %s",
            serverWebAdminUrl, bucketName, adminRestApiPort, syncRestApiPort, pool, pretty, verbose);

    newScript(ImmutableMap.of("usePidFile", true), LAUNCHING).body
            .append(format("/opt/couchbase-sync-gateway/bin/sync_gateway %s ", options)
                    + "> out.log 2> err.log < /dev/null &")
            .failOnNonZeroResultCode().execute();
}