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:net.shibboleth.idp.saml.profile.impl.PopulateBindingAndEndpointContexts.java

/**
 * Check for an inbound request binding that is synchronous and handle appropriately.
 * //from   w  w  w.  j a  v a  2 s.  co  m
 * @param profileRequestContext profile request context
 * 
 * @return  true iff a synchronous binding was handled
 */
private boolean handleSynchronousRequest(@Nonnull final ProfileRequestContext profileRequestContext) {
    if (inboundMessage != null) {
        final SAMLBindingContext bindingCtx = profileRequestContext.getInboundMessageContext()
                .getSubcontext(SAMLBindingContext.class);
        if (bindingCtx != null && bindingCtx.getBindingUri() != null) {
            final Optional<BindingDescriptor> binding = Iterables.tryFind(bindingDescriptors,
                    new Predicate<BindingDescriptor>() {
                        public boolean apply(BindingDescriptor input) {
                            return input.getId().equals(bindingCtx.getBindingUri());
                        }
                    });
            if (binding.isPresent() && binding.get().isSynchronous()) {
                log.debug(
                        "{} Handling request via synchronous binding, preparing outbound binding context for {}",
                        getLogPrefix(), binding.get().getId());

                final SAMLBindingContext outboundCtx = bindingContextLookupStrategy
                        .apply(profileRequestContext);
                outboundCtx.setRelayState(
                        SAMLBindingSupport.getRelayState(profileRequestContext.getInboundMessageContext()));
                outboundCtx.setBindingDescriptor(binding.get());
                return true;
            }
        }
    }

    return false;
}

From source file:org.killbill.billing.payment.provider.MockPaymentProviderPlugin.java

private PaymentTransactionInfoPlugin getPaymentTransactionInfoPluginResult(final UUID kbPaymentId,
        final UUID kbTransactionId, final TransactionType type, @Nullable final BigDecimal amount,
        @Nullable final Currency currency, final Iterable<PluginProperty> pluginProperties)
        throws PaymentPluginApiException {
    if (makePluginWaitSomeMilliseconds.get() > 0) {
        try {//from  w ww  .  j av  a 2  s .  co m
            Thread.sleep(makePluginWaitSomeMilliseconds.get());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new PaymentPluginApiException("An Interruption occurred while the Thread was sleeping.", e);
        }
    }

    if (makeNextPaymentFailWithException.getAndSet(false)) {
        throw new PaymentPluginApiException("", "test error");
    }

    final PluginProperty paymentPluginStatusOverride = Iterables
            .tryFind(pluginProperties, new Predicate<PluginProperty>() {
                @Override
                public boolean apply(final PluginProperty input) {
                    return PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE.equals(input.getKey());
                }
            }).orNull();

    final PaymentPluginStatus status;
    if (paymentPluginStatusOverride != null && paymentPluginStatusOverride.getValue() != null) {
        status = PaymentPluginStatus.valueOf(paymentPluginStatusOverride.getValue().toString());
    } else if (makeAllPaymentsFailWithError.get() || makeNextPaymentFailWithError.getAndSet(false)) {
        status = PaymentPluginStatus.ERROR;
    } else if (makeNextPaymentFailWithCancellation.getAndSet(false)) {
        status = PaymentPluginStatus.CANCELED;
    } else if (makeNextPaymentPending.getAndSet(false)) {
        status = PaymentPluginStatus.PENDING;
    } else {
        status = PaymentPluginStatus.PROCESSED;
    }
    final String errorCode = status == PaymentPluginStatus.PROCESSED ? "" : GATEWAY_ERROR_CODE;
    final String error = status == PaymentPluginStatus.PROCESSED ? "" : GATEWAY_ERROR;

    InternalPaymentInfo info = payments.get(kbPaymentId.toString());
    if (info == null) {
        info = new InternalPaymentInfo();
        payments.put(kbPaymentId.toString(), info);
    }

    final BigDecimal overrideNextProcessedAmount = this.overrideNextProcessedAmount.getAndSet(null);
    final BigDecimal processedAmount = overrideNextProcessedAmount != null ? overrideNextProcessedAmount
            : amount;
    Currency processedCurrency = overrideNextProcessedCurrency.getAndSet(null);
    if (processedCurrency == null) {
        processedCurrency = currency;
    }

    final PaymentTransactionInfoPlugin result = new DefaultNoOpPaymentInfoPlugin(kbPaymentId, kbTransactionId,
            type, processedAmount, processedCurrency, clock.getUTCNow(), clock.getUTCNow(), status, errorCode,
            error);
    List<PaymentTransactionInfoPlugin> existingTransactions = paymentTransactions.get(kbPaymentId.toString());
    if (existingTransactions == null) {
        existingTransactions = new ArrayList<PaymentTransactionInfoPlugin>();
        paymentTransactions.put(kbPaymentId.toString(), existingTransactions);
    }

    final Iterator<PaymentTransactionInfoPlugin> iterator = existingTransactions.iterator();
    while (iterator.hasNext()) {
        final PaymentTransactionInfoPlugin existingTransaction = iterator.next();
        if (existingTransaction.getKbTransactionPaymentId().equals(kbTransactionId)) {
            info.addAmount(type, existingTransaction.getAmount().negate());
            iterator.remove();
        }
    }
    existingTransactions.add(result);
    info.addAmount(type, result.getAmount());

    return result;
}

From source file:pt.ist.maidSyncher.domain.github.GHRepository.java

protected static GHRepository findById(final long id) {
    checkArgument(id > 0);/*from  ww  w .  ja  va2s  .  c  o m*/
    Optional<GHRepository> optionalGHRepository = Iterables
            .tryFind(MaidRoot.getInstance().getGhRepositoriesSet(), new Predicate<GHRepository>() {
                @Override
                public boolean apply(GHRepository ghRepository) {
                    if (ghRepository == null)
                        return false;
                    return ghRepository.getId() == id;
                }
            });
    return optionalGHRepository.isPresent() ? optionalGHRepository.get() : null;
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraDatacenterImpl.java

@Override
public void update() {
    synchronized (mutex) {
        // Update our seeds, as necessary
        seedTracker.refreshSeeds();//from w w  w  . ja  v  a  2  s. co  m

        // Choose the first available cluster member to set host and port (and compute one-up)
        Optional<Entity> upNode = Iterables.tryFind(getMembers(),
                EntityPredicates.attributeEqualTo(SERVICE_UP, Boolean.TRUE));

        if (upNode.isPresent()) {
            sensors().set(HOSTNAME, upNode.get().getAttribute(Attributes.HOSTNAME));
            sensors().set(THRIFT_PORT, upNode.get().getAttribute(CassandraNode.THRIFT_PORT));

            List<String> currentNodes = getAttribute(CASSANDRA_CLUSTER_NODES);
            Set<String> oldNodes = (currentNodes != null) ? ImmutableSet.copyOf(currentNodes)
                    : ImmutableSet.<String>of();
            Set<String> newNodes = MutableSet.<String>of();
            for (Entity member : getMembers()) {
                if (member instanceof CassandraNode && Boolean.TRUE.equals(member.getAttribute(SERVICE_UP))) {
                    String hostname = member.getAttribute(Attributes.HOSTNAME);
                    Integer thriftPort = member.getAttribute(CassandraNode.THRIFT_PORT);
                    if (hostname != null && thriftPort != null) {
                        newNodes.add(HostAndPort.fromParts(hostname, thriftPort).toString());
                    }
                }
            }
            if (Sets.symmetricDifference(oldNodes, newNodes).size() > 0) {
                sensors().set(CASSANDRA_CLUSTER_NODES, MutableList.copyOf(newNodes));
            }
        } else {
            sensors().set(HOSTNAME, null);
            sensors().set(THRIFT_PORT, null);
            sensors().set(CASSANDRA_CLUSTER_NODES, Collections.<String>emptyList());
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyList(this, CASSANDRA_CLUSTER_NODES);
    }
}

From source file:org.killbill.billing.subscription.api.svcs.DefaultSubscriptionInternalApi.java

@Override
public SubscriptionBaseBundle createBundleForAccount(final UUID accountId, final String bundleKey,
        final InternalCallContext context) throws SubscriptionBaseApiException {

    final List<SubscriptionBaseBundle> existingBundles = dao.getSubscriptionBundlesForKey(bundleKey, context);

    ////from  w ww .j a  v a2 s. co  m
    // Because the creation of the SubscriptionBundle is not atomic (with creation of Subscription/SubscriptionEvent), we verify if we were left
    // with an empty SubscriptionBaseBundle form a past failing operation (See #684). We only allow reuse if such SubscriptionBaseBundle is fully
    // empty (and don't allow use case where all Subscription are cancelled, which is the condition for that key to be re-used)
    // Such condition should have been checked upstream (to decide whether that key is valid or not)
    //
    final SubscriptionBaseBundle existingBundleForAccount = Iterables
            .tryFind(existingBundles, new Predicate<SubscriptionBaseBundle>() {
                @Override
                public boolean apply(final SubscriptionBaseBundle input) {
                    return input.getAccountId().equals(accountId);
                }
            }).orNull();

    // If Bundle already exists, and there is 0 Subscription, we reuse
    if (existingBundleForAccount != null) {
        try {
            final Map<UUID, List<SubscriptionBase>> accountSubscriptions = dao
                    .getSubscriptionsForAccount(context);
            final List<SubscriptionBase> subscriptions = accountSubscriptions
                    .get(existingBundleForAccount.getId());
            if (subscriptions == null || subscriptions.size() == 0) {
                return existingBundleForAccount;
            }
        } catch (final CatalogApiException e) {
            throw new SubscriptionBaseApiException(e);
        }
    }

    final DateTime now = clock.getUTCNow();
    final DateTime originalCreatedDate = !existingBundles.isEmpty() ? existingBundles.get(0).getCreatedDate()
            : now;
    final DefaultSubscriptionBaseBundle bundle = new DefaultSubscriptionBaseBundle(bundleKey, accountId, now,
            originalCreatedDate, now, now);

    if (null != bundleKey && bundleKey.length() > 255) {
        throw new SubscriptionBaseApiException(ErrorCode.EXTERNAL_KEY_LIMIT_EXCEEDED);
    }
    return dao.createSubscriptionBundle(bundle, context);
}

From source file:org.jclouds.vcloud.director.v1_5.compute.strategy.VCloudDirectorComputeServiceAdapter.java

private VirtualHardwareSection updateVirtualHardwareSection(VirtualHardwareSection virtualHardwareSection,
        Predicate<ResourceAllocationSettingData> predicate,
        Function<ResourceAllocationSettingData, ResourceAllocationSettingData> modifier) {
    Set<? extends ResourceAllocationSettingData> oldItems = virtualHardwareSection.getItems();
    Set<ResourceAllocationSettingData> newItems = Sets.newLinkedHashSet(oldItems);
    Optional<? extends ResourceAllocationSettingData> oldResourceAllocationSettingData = Iterables
            .tryFind(oldItems, predicate);
    if (oldResourceAllocationSettingData.isPresent()) {
        ResourceAllocationSettingData newResourceAllocationSettingData = modifier
                .apply(oldResourceAllocationSettingData.get());
        newItems.remove(oldResourceAllocationSettingData.get());
        newItems.add(newResourceAllocationSettingData);
        return virtualHardwareSection.toBuilder().items(newItems).build();
    } else {/* ww  w. j a v  a  2s .c om*/
        logger.warn("Unable to find hardware section matching %s; cannot apply %s", predicate, modifier);
        return virtualHardwareSection;
    }
}

From source file:clocker.mesos.entity.MesosClusterImpl.java

@Override
public MesosSlave getMesosSlave(String hostname) {
    Collection<Entity> slaves = sensors().get(MESOS_SLAVES).getMembers();
    Optional<Entity> found = Iterables.tryFind(slaves,
            Predicates.or(EntityPredicates.attributeEqualTo(MesosSlave.HOSTNAME, hostname),
                    EntityPredicates.attributeEqualTo(MesosSlave.ADDRESS, hostname)));
    if (found.isPresent()) {
        return (MesosSlave) found.get();
    } else {//  w  ww .  ja  v a  2  s . co  m
        throw new IllegalStateException("Cannot find slave for host: " + hostname);
    }
}

From source file:org.killbill.billing.jaxrs.resources.JaxRsResourceBase.java

public static UUID getInvoiceId(final List<InvoicePayment> invoicePayments, final Payment payment) {
    final InvoicePayment invoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {
        @Override/* ww  w  .  j a  v  a2  s  .  c  om*/
        public boolean apply(final InvoicePayment input) {
            return input.getPaymentId().equals(payment.getId())
                    && input.getType() == InvoicePaymentType.ATTEMPT;
        }
    }).orNull();
    return invoicePayment != null ? invoicePayment.getInvoiceId() : null;
}

From source file:org.jclouds.vcloud.director.v1_5.compute.strategy.VCloudDirectorComputeServiceAdapter.java

private Reference tryFindNetworkInVDC(Vdc vdc, String networkName) {
    Optional<Reference> referenceOptional = Iterables.tryFind(vdc.getAvailableNetworks(),
            ReferencePredicates.nameEquals(networkName));
    if (!referenceOptional.isPresent()) {
        throw new IllegalStateException(
                "Can't find a network named: " + networkName + "in vDC " + vdc.getName());
    }// ww  w .  jav  a  2 s . c  om
    return referenceOptional.get();
}

From source file:brooklyn.entity.container.docker.DockerHostImpl.java

public void scanContainers() {
    // TODO remember that _half started_ containers left behind are not to be re-used
    // TODO add cleanup for these?
    getDynamicLocation().getLock().lock();
    try {/*from   www  .j a  v  a2s.  c o m*/
        String output = runDockerCommand("ps");
        List<String> ps = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().splitToList(output);
        if (ps.size() > 1) {
            for (int i = 1; i < ps.size(); i++) {
                String line = ps.get(i);
                String id = Strings.getFirstWord(line);
                Optional<Entity> container = Iterables.tryFind(getDockerContainerCluster().getMembers(),
                        Predicates.compose(StringPredicates.startsWith(id),
                                EntityFunctions.attribute(DockerContainer.CONTAINER_ID)));
                if (container.isPresent())
                    continue;

                // Build a DockerContainer without a locations, as it may not be SSHable
                String containerId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Id}} " + id));
                String imageId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Image}} " + id));
                String imageName = Strings
                        .getFirstWord(runDockerCommand("inspect --format {{.Config.Image}} " + id));
                EntitySpec<DockerContainer> containerSpec = EntitySpec
                        .create(config().get(DOCKER_CONTAINER_SPEC))
                        .configure(SoftwareProcess.ENTITY_STARTED, Boolean.TRUE)
                        .configure(DockerContainer.DOCKER_HOST, this)
                        .configure(DockerContainer.DOCKER_INFRASTRUCTURE, getInfrastructure())
                        .configure(DockerContainer.DOCKER_IMAGE_ID, imageId)
                        .configure(DockerAttributes.DOCKER_IMAGE_NAME, imageName)
                        .configure(DockerContainer.LOCATION_FLAGS, MutableMap.of("container", getMachine()));

                // Create, manage and start the container
                DockerContainer added = getDockerContainerCluster().addChild(containerSpec);
                Entities.manage(added);
                getDockerContainerCluster().addMember(added);
                ((EntityLocal) added).setAttribute(DockerContainer.CONTAINER_ID, containerId);
                added.start(ImmutableList.of(getDynamicLocation().getMachine()));
            }
        }
    } finally {
        getDynamicLocation().getLock().unlock();
    }
}