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.icgc.dcc.submission.dictionary.model.Field.java

/**
 * FIXME: https://jira.oicr.on.ca/browse/DCC-2087
 *//*w  ww.j a  v a  2  s  .  c  o  m*/
@JsonIgnore
public Optional<Restriction> getRestriction(final RestrictionType type) {
    return Iterables.tryFind(this.restrictions, new Predicate<Restriction>() {

        @Override
        public boolean apply(Restriction input) {
            return input.getType() == type;
        }

    });
}

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

@Override
public InetAddress attachNetwork(String containerId, final String networkId) {
    final SdnProvider provider = getAttribute(SDN_PROVIDER);
    boolean createNetwork = false;
    Cidr subnetCidr = null;/*from   w  ww .j a v  a  2s.c  o  m*/
    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(VirtualNetwork.NETWORK_ID, networkId)
                .configure(VirtualNetwork.NETWORK_CIDR, subnetCidr);

        // Start and then add this virtual network as a child of SDN_NETWORKS
        VirtualNetwork network = provider.getAttribute(SdnProvider.SDN_NETWORKS).addChild(networkSpec);
        Entities.manage(network);
        Entities.start(network,
                Collections.singleton(
                        ((DockerInfrastructure) provider.getAttribute(SdnProvider.DOCKER_INFRASTRUCTURE))
                                .getDynamicLocation()));
        Entities.waitForServiceUp(network);
    } else {
        Task<Boolean> lookup = TaskBuilder.<Boolean>builder().name("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.getAttribute(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));
        }
    }

    InetAddress address = getDriver().attachNetwork(containerId, networkId);
    LOG.info("Attached container ID {} to {}: {}",
            new Object[] { containerId, networkId, address.getHostAddress() });

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

    return address;
}

From source file:com.thinkbiganalytics.feedmgr.service.template.InMemoryFeedManagerTemplateService.java

public RegisteredTemplate getRegisteredTemplateByName(final String templateName) {

    return Iterables.tryFind(registeredTemplates.values(), new Predicate<RegisteredTemplate>() {
        @Override//ww w. j a v  a2s  . c om
        public boolean apply(RegisteredTemplate registeredTemplate) {
            return registeredTemplate.getTemplateName().equalsIgnoreCase(templateName);
        }
    }).orNull();
}

From source file:com.thinkbiganalytics.feedmgr.service.category.InMemoryFeedManagerCategoryService.java

@Override
public FeedCategory getCategoryById(final String id) {
    return Iterables.tryFind(categories.values(), new Predicate<FeedCategory>() {
        @Override//from  www .j ava2  s.co  m
        public boolean apply(FeedCategory feedCategory) {
            return feedCategory.getId().equalsIgnoreCase(id);
        }
    }).orNull();
}

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

protected UUID getOrCreatePaymentMethod(final Account account,
        @Nullable final PaymentMethodJson paymentMethodJson, final Iterable<PluginProperty> pluginProperties,
        final CallContext callContext) throws PaymentApiException {

    // No info about payment method was passed, we default to null payment Method ID (which is allowed to be overridden in payment control plugins)
    if (paymentMethodJson == null || paymentMethodJson.getPluginName() == null) {
        return null;
    }/* w  w w  . ja v a2  s .  c  o m*/

    // Get all payment methods for account
    final List<PaymentMethod> accountPaymentMethods = paymentApi.getAccountPaymentMethods(account.getId(),
            false, ImmutableList.<PluginProperty>of(), callContext);

    // If we were specified a paymentMethod id and we find it, we return it
    if (paymentMethodJson.getPaymentMethodId() != null) {
        final UUID match = UUID.fromString(paymentMethodJson.getPaymentMethodId());
        if (Iterables.any(accountPaymentMethods, new Predicate<PaymentMethod>() {
            @Override
            public boolean apply(final PaymentMethod input) {
                return input.getId().equals(match);
            }
        })) {
            return match;
        }
        throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, match);
    }

    // If we were specified a paymentMethod externalKey and we find it, we return it
    if (paymentMethodJson.getExternalKey() != null) {
        final PaymentMethod match = Iterables.tryFind(accountPaymentMethods, new Predicate<PaymentMethod>() {
            @Override
            public boolean apply(final PaymentMethod input) {
                return input.getExternalKey().equals(paymentMethodJson.getExternalKey());
            }
        }).orNull();
        if (match != null) {
            return match.getId();
        }
    }

    // Only set as default if this is the first paymentMethod on the account
    final boolean isDefault = accountPaymentMethods.isEmpty();
    final PaymentMethod paymentData = paymentMethodJson.toPaymentMethod(account.getId().toString());
    return paymentApi.addPaymentMethod(account, paymentMethodJson.getExternalKey(),
            paymentMethodJson.getPluginName(), isDefault, paymentData.getPluginDetail(), pluginProperties,
            callContext);
}

From source file:org.killbill.billing.payment.core.janitor.AttemptCompletionTask.java

@Override
public void doIteration(final PaymentAttemptModelDao attempt) {
    final InternalTenantContext tenantContext = internalCallContextFactory
            .createInternalTenantContext(attempt.getAccountId(), attempt.getId(), ObjectType.PAYMENT_ATTEMPT);
    final CallContext callContext = createCallContext("AttemptCompletionJanitorTask", tenantContext);
    final InternalCallContext internalCallContext = internalCallContextFactory
            .createInternalCallContext(attempt.getAccountId(), callContext);

    final List<PaymentTransactionModelDao> transactions = paymentDao
            .getPaymentTransactionsByExternalKey(attempt.getTransactionExternalKey(), tenantContext);
    final PaymentTransactionModelDao transaction = Iterables
            .tryFind(transactions, new Predicate<PaymentTransactionModelDao>() {
                @Override//from  w  w  w  . ja v  a  2 s.c o m
                public boolean apply(final PaymentTransactionModelDao input) {
                    return input.getAttemptId().equals(attempt.getId())
                            && input.getTransactionStatus() == TransactionStatus.SUCCESS;
                }
            }).orNull();

    if (transaction == null) {
        log.info("Janitor AttemptCompletionTask moving attempt " + attempt.getId() + " -> ABORTED");
        paymentDao.updatePaymentAttempt(attempt.getId(), attempt.getTransactionId(), "ABORTED",
                internalCallContext);
        return;
    }

    try {
        log.info("Janitor AttemptCompletionTask completing attempt " + attempt.getId() + " -> SUCCESS");

        final Account account = accountInternalApi.getAccountById(attempt.getAccountId(), tenantContext);
        final boolean isApiPayment = true; // unclear
        final RetryablePaymentStateContext paymentStateContext = new RetryablePaymentStateContext(
                attempt.toPaymentControlPluginNames(), isApiPayment, transaction.getPaymentId(),
                attempt.getPaymentExternalKey(), transaction.getTransactionExternalKey(),
                transaction.getTransactionType(), account, attempt.getPaymentMethodId(),
                transaction.getAmount(), transaction.getCurrency(),
                PluginPropertySerializer.deserialize(attempt.getPluginProperties()), internalCallContext,
                callContext);

        paymentStateContext.setAttemptId(attempt.getId()); // Normally set by leavingState Callback
        paymentStateContext.setPaymentTransactionModelDao(transaction); // Normally set by raw state machine
        //
        // Will rerun the state machine with special callbacks to only make the onCompletion call
        // to the PaymentControlPluginApi plugin and transition the state.
        //
        pluginControlledPaymentAutomatonRunner.completeRun(paymentStateContext);
    } catch (AccountApiException e) {
        log.warn("Janitor AttemptCompletionTask failed to complete payment attempt " + attempt.getId(), e);
    } catch (PluginPropertySerializerException e) {
        log.warn("Janitor AttemptCompletionTask failed to complete payment attempt " + attempt.getId(), e);
    } catch (PaymentApiException e) {
        log.warn("Janitor AttemptCompletionTask failed to complete payment attempt " + attempt.getId(), e);
    }
}

From source file:org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveStatementBase.java

protected final <T> T firstSubstatementOfType(final Class<T> type) {
    final Optional<? extends EffectiveStatement<?, ?>> possible = Iterables.tryFind(substatements,
            Predicates.instanceOf(type));
    return possible.isPresent() ? type.cast(possible.get()) : null;
}

From source file:com.thinkbiganalytics.feedmgr.rest.model.FeedCategory.java

@JsonIgnore
public void addRelatedFeed(final FeedSummary feed) {
    if (feeds != null) {
        List<FeedSummary> arr = Lists.newArrayList(feeds);
        FeedSummary match = Iterables.tryFind(arr, new Predicate<FeedSummary>() {
            @Override/*w ww  . j  a v a  2s . c o m*/
            public boolean apply(FeedSummary metadata) {
                return feed.getFeedName().equalsIgnoreCase(metadata.getFeedName());
            }
        }).orNull();
        if (match != null) {
            feeds.remove(match);
        }
    }
    getFeeds().add(feed);
    relatedFeeds = getFeeds().size();

}

From source file:info.magnolia.ui.dialog.formdialog.FormPresenterImpl.java

@Override
public void presentView(FormViewReduced formView, FormDefinition formDefinition, Item item, FormItem parent) {
    this.formView = formView;
    this.formDefinition = formDefinition;
    this.itemDatasource = item;

    localeToFormSections.clear();/*from   www  .j  av a2  s .co  m*/
    // FormBuilder still expects the FormView object to build, so we have to cast here but ideally that should be refactored
    formBuilder.buildForm((FormView) this.formView, this.formDefinition, item, parent);

    // We should expand locale-awareness onto all the UI contexts.
    if (uiContext instanceof SubAppContext) {
        this.activeLocale = ((SubAppContext) uiContext).getAuthoringLocale();
        formView.setListener(new FormView.Listener() {
            @Override
            public void localeChanged(Locale newLocale) {
                if (newLocale != null
                        && !ObjectUtils.equals(((SubAppContext) uiContext).getAuthoringLocale(), newLocale)) {
                    setLocale(newLocale);
                }
            }
        });

        localeToFormSections.put(this.activeLocale,
                Maps.toMap(formDefinition.getTabs(), new Function<TabDefinition, FormSection>() {
                    @Nullable
                    @Override
                    public FormSection apply(final TabDefinition tabDefinition) {
                        return Iterables.tryFind(FormPresenterImpl.this.formView.getFormSections(),
                                new FormSectionNameMatches(tabDefinition.getName())).orNull();
                    }
                }));
    }
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiPropertyUtil.java

/**
 * Return a property matching a given processor name and property name
 *
 * @param processorName the processor name to match
 * @param propertyName  the name of hte {@link NifiProperty#getKey()}
 * @param properties    a list of properties to inspect
 * @return the first property matching the processorName nad propertyName
 *///  www .j a va2 s  .  c  o m
public static NifiProperty getProperty(final String processorName, final String propertyName,
        List<NifiProperty> properties) {
    NifiProperty property = Iterables.tryFind(properties, new Predicate<NifiProperty>() {
        @Override
        public boolean apply(NifiProperty property) {
            return property.getProcessorName().equalsIgnoreCase(processorName)
                    && property.getKey().equalsIgnoreCase(propertyName);
        }
    }).orNull();
    return property;
}