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.gradle.api.internal.plugins.DefaultPluginContainer.java

private Plugin doFindPlugin(String id) {
    for (final PluginManagerInternal.PluginWithId pluginWithId : pluginManager.pluginsForId(id)) {
        Plugin plugin = Iterables.tryFind(DefaultPluginContainer.this, new Predicate<Plugin>() {
            public boolean apply(Plugin plugin) {
                return pluginWithId.clazz.equals(plugin.getClass());
            }//ww w .  jav  a 2  s  .  com
        }).orNull();

        if (plugin != null) {
            return plugin;
        }
    }

    return null;
}

From source file:com.google.devtools.build.android.SplitConfigurationFilter.java

/**
 * Finds a mapping from filename suffixes to the split flags which could have spawned them.
 *
 * @param filenames The suffixes of the original apk filenames output by aapt, not including the
 *     underscore used to set it off from the base filename or the base filename itself.
 * @param splitFlags The split flags originally passed to aapt.
 * @return A map whose keys are the filenames from {@code filenames} and whose values are
 *     predictable filenames based on the split flags - that is, the commas present in the input
 *     have been replaced with underscores.
 * @throws UnrecognizedSplitException if any of the inputs are unused or could not be matched
 *//*from   ww w . j  a  v a 2s  . c  o m*/
static Map<String, String> mapFilenamesToSplitFlags(Iterable<String> filenames, Iterable<String> splitFlags)
        throws UnrecognizedSplitsException {
    TreeSet<SplitConfigurationFilter> filenameFilters = new TreeSet<>();
    for (String filename : filenames) {
        filenameFilters.add(SplitConfigurationFilter.fromFilenameSuffix(filename));
    }
    TreeSet<SplitConfigurationFilter> flagFilters = new TreeSet<>();
    for (String splitFlag : splitFlags) {
        flagFilters.add(SplitConfigurationFilter.fromSplitFlag(splitFlag));
    }
    ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
    List<String> unidentifiedFilenames = new ArrayList<>();
    for (SplitConfigurationFilter filenameFilter : filenameFilters) {
        Optional<SplitConfigurationFilter> matched = Iterables.tryFind(flagFilters,
                new MatchesFilterFromFilename(filenameFilter));
        if (matched.isPresent()) {
            result.put(filenameFilter.filename, matched.get().filename);
            flagFilters.remove(matched.get());
        } else {
            unidentifiedFilenames.add(filenameFilter.filename);
        }
    }
    if (!(unidentifiedFilenames.isEmpty() && flagFilters.isEmpty())) {
        ImmutableList.Builder<String> unidentifiedFlags = ImmutableList.builder();
        for (SplitConfigurationFilter flagFilter : flagFilters) {
            unidentifiedFlags.add(flagFilter.filename);
        }
        throw new UnrecognizedSplitsException(unidentifiedFlags.build(), unidentifiedFilenames, result.build());
    }
    return result.build();
}

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

@Override
public void start(Collection<? extends Location> locations) {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

    connectSensors();// w  w w. java2s. co  m

    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()) {
        setAttribute(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:org.killbill.billing.beatrix.util.RefundChecker.java

public PaymentTransaction checkRefund(final UUID paymentId, final CallContext context,
        ExpectedRefundCheck expected) throws PaymentApiException {

    final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(),
            context);//from   w w w . j av  a2s.com
    final PaymentTransaction refund = Iterables
            .tryFind(payment.getTransactions(), new Predicate<PaymentTransaction>() {
                @Override
                public boolean apply(final PaymentTransaction input) {
                    return input.getTransactionType() == TransactionType.REFUND;
                }
            }).orNull();

    Assert.assertNotNull(refund);

    final InvoicePayment refundInvoicePayment = getInvoicePaymentEntry(paymentId, InvoicePaymentType.REFUND,
            context);
    final InvoicePayment invoicePayment = getInvoicePaymentEntry(paymentId, InvoicePaymentType.ATTEMPT,
            context);

    Assert.assertEquals(refund.getPaymentId(), expected.getPaymentId());
    Assert.assertEquals(refund.getCurrency(), expected.getCurrency());
    Assert.assertEquals(refund.getAmount().compareTo(expected.getRefundAmount()), 0);

    Assert.assertEquals(refundInvoicePayment.getPaymentId(), paymentId);
    Assert.assertEquals(refundInvoicePayment.getLinkedInvoicePaymentId(), invoicePayment.getId());
    Assert.assertEquals(refundInvoicePayment.getPaymentCookieId(), refund.getExternalKey());
    Assert.assertEquals(refundInvoicePayment.getInvoiceId(), invoicePayment.getInvoiceId());
    Assert.assertEquals(refundInvoicePayment.getAmount().compareTo(expected.getRefundAmount().negate()), 0);
    Assert.assertEquals(refundInvoicePayment.getCurrency(), expected.getCurrency());

    return refund;
}

From source file:brooklyn.networking.sdn.SdnUtils.java

public static final VirtualNetwork createNetwork(final SdnProvider provider, final String networkId) {
    boolean createNetwork = false;
    Cidr subnetCidr = null;//from   w  ww .  j  a v a2 s .c o  m
    VirtualNetwork network = null;
    synchronized (provider.getNetworkMutex()) {
        subnetCidr = provider.getSubnetCidr(networkId);
        if (subnetCidr == null) {
            subnetCidr = provider.getNextSubnetCidr(networkId);
            createNetwork = true;
        }
    }
    if (createNetwork) {
        // Get a CIDR for the subnet from the availabkle pool and create a virtual network
        EntitySpec<VirtualNetwork> networkSpec = EntitySpec.create(VirtualNetwork.class)
                .configure(SdnAttributes.SDN_PROVIDER, provider).configure(VirtualNetwork.NETWORK_ID, networkId)
                .configure(VirtualNetwork.NETWORK_CIDR, subnetCidr);

        // Start and then add this virtual network as a child of SDN_NETWORKS
        network = provider.sensors().get(SdnProvider.SDN_NETWORKS).addChild(networkSpec);
        Entities.start(network, provider.getLocations());
        Entities.waitForServiceUp(network);
    } else {
        Task<Boolean> lookup = TaskBuilder.<Boolean>builder()
                .displayName("Waiting until virtual network is available").body(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        return Repeater.create().every(Duration.TEN_SECONDS).until(new Callable<Boolean>() {
                            public Boolean call() {
                                Optional<Entity> found = Iterables.tryFind(
                                        provider.sensors().get(SdnProvider.SDN_NETWORKS).getMembers(),
                                        EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID,
                                                networkId));
                                return found.isPresent();
                            }
                        }).limitTimeTo(Duration.ONE_MINUTE).run();
                    }
                }).build();
        Boolean result = DynamicTasks.queueIfPossible(lookup).orSubmitAndBlock().andWaitForSuccess();
        if (!result) {
            throw new IllegalStateException(
                    String.format("Cannot find virtual network entity for %s", networkId));
        }
        network = (VirtualNetwork) Iterables.find(provider.sensors().get(SdnProvider.SDN_NETWORKS).getMembers(),
                EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId));
    }

    // Rescan SDN network groups for containers
    DynamicGroup group = (DynamicGroup) Iterables.find(
            provider.sensors().get(SdnProvider.SDN_APPLICATIONS).getMembers(),
            EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId));
    group.rescanEntities();

    return network;
}

From source file:org.eclipse.recommenders.internal.privacy.rcp.jobs.ApprovalDialogJob.java

@Override
public boolean shouldRun() {
    return Iterables.tryFind(getDetectedPermission(), new ContainInstallPredicate()).isPresent();
}

From source file:org.obm.provisioning.processing.impl.users.sieve.SieveScriptUpdater.java

private void doUpdate() {
    List<SieveScript> scripts = this.sieveClient.listscripts();
    Optional<SieveScript> maybeActiveScript = Iterables.tryFind(scripts, new Predicate<SieveScript>() {

        @Override/*from   w w w  . ja v a  2  s  .co  m*/
        public boolean apply(SieveScript script) {
            return script.isActive();
        }
    });
    if (maybeActiveScript.isPresent()) {
        SieveScript script = maybeActiveScript.get();
        String oldContent = sieveClient.getScriptContent(script.getName());
        Optional<String> maybeNewContent = sieveBuilder.buildFromOldContent(oldContent);
        if (maybeNewContent.isPresent()) {
            this.sieveClient.putscript(script.getName(), maybeNewContent.get());
        } else {
            this.sieveClient.activate("");
            this.sieveClient.deletescript(script.getName());
        }
    } else {
        Optional<String> maybeContent = sieveBuilder.build();
        if (maybeContent.isPresent()) {
            String scriptName = SieveUtils.getSieveScriptName(obmUser);
            this.sieveClient.putscript(scriptName, maybeContent.get());
            this.sieveClient.activate(scriptName);
        }
    }
}

From source file:com.eucalyptus.auth.ws.EuareRequestLoggingFilter.java

private boolean isAction(final Collection<String> parametersOrBody, final Iterable<String> actionNvps) {
    return Iterables.tryFind(actionNvps, Predicates.in(parametersOrBody)).isPresent();
}

From source file:org.jclouds.aliyun.ecs.compute.strategy.CleanupResources.java

/**
 * @param regionAndId//from  www.  j  a v  a2s.  c  o  m
 * @return whether the node and its resources have been deleted
 */
public boolean cleanupNode(final RegionAndId regionAndId) {
    String instanceId = regionAndId.id();
    InstanceStatus instanceStatus = Iterables
            .tryFind(api.instanceApi().listInstanceStatus(regionAndId.regionId()).concat(),
                    new InstanceStatusPredicate(instanceId))
            .orNull();
    if (instanceStatus == null)
        return true;
    if (InstanceStatus.Status.STOPPED != instanceStatus.status()) {
        logger.debug(">> powering off %s ...", RegionAndId.slashEncodeRegionAndId(regionAndId));
        api.instanceApi().powerOff(instanceId);
        instanceSuspendedPredicate.apply(RegionAndId.slashEncodeRegionAndId(regionAndId));
    }
    logger.debug(">> destroying %s ...", RegionAndId.slashEncodeRegionAndId(regionAndId));
    api.instanceApi().delete(instanceId);
    return instanceTerminatedPredicate.apply(RegionAndId.slashEncodeRegionAndId(regionAndId));
}

From source file:com.netflix.hystrix.contrib.javanica.cache.CacheInvocationParameter.java

private Annotation cacheKeyAnnotation() {
    return Iterables.tryFind(annotations, new Predicate<Annotation>() {
        @Override/*from  w  w w . j a  v  a2  s . c  o  m*/
        public boolean apply(Annotation input) {
            return input.annotationType().equals(CacheKey.class);
        }
    }).orNull();
}