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.killbill.billing.beatrix.util.PaymentChecker.java

private PaymentTransaction getPurchaseTransaction(final Payment payment) {
    return Iterables.tryFind(payment.getTransactions(), new Predicate<PaymentTransaction>() {
        @Override/* w w w  . j a  v a 2 s.c  o m*/
        public boolean apply(final PaymentTransaction input) {
            return input.getTransactionType() == TransactionType.PURCHASE;
        }
    }).get();
}

From source file:org.eclipse.buildship.core.workspace.internal.ProjectNameUpdater.java

private static boolean isScheduledForRenaming(IProject duplicate, Set<OmniEclipseProject> allProjects) {
    if (!duplicate.isOpen()) {
        return false;
    }//w w  w .j  a v  a2s .  c o m

    Optional<OmniEclipseProject> duplicateEclipseProject = Iterables.tryFind(allProjects,
            Predicates.eclipseProjectMatchesProjectDir(duplicate.getLocation().toFile()));
    if (!duplicateEclipseProject.isPresent()) {
        return false;
    }

    String newName = checkProjectName(duplicateEclipseProject.get());
    return !newName.equals(duplicate.getName());
}

From source file:org.killbill.billing.catalog.override.DefaultPriceOverride.java

@Override
public DefaultPlan getOrCreateOverriddenPlan(final StandaloneCatalog standaloneCatalog, final Plan parentPlan,
        final DateTime catalogEffectiveDate, final List<PlanPhasePriceOverride> overrides,
        @Nullable final InternalCallContext context) throws CatalogApiException {

    final PlanPhasePriceOverride[] resolvedOverride = new PlanPhasePriceOverride[parentPlan
            .getAllPhases().length];/*from w w  w  .j  av a  2  s .  c  o  m*/
    int index = 0;
    for (final PlanPhase curPhase : parentPlan.getAllPhases()) {
        final PlanPhasePriceOverride curOverride = Iterables
                .tryFind(overrides, new Predicate<PlanPhasePriceOverride>() {
                    @Override
                    public boolean apply(final PlanPhasePriceOverride input) {
                        if (input.getPhaseName() != null) {
                            return input.getPhaseName().equals(curPhase.getName());
                        }
                        // If the phaseName was not passed, we infer by matching the phaseType. This obviously would not work in a case where
                        // a plan is defined with multiple phases of the same type.
                        final PlanPhaseSpecifier curPlanPhaseSpecifier = input.getPlanPhaseSpecifier();
                        if (curPlanPhaseSpecifier.getPhaseType().equals(curPhase.getPhaseType())) {
                            return true;
                        }
                        return false;
                    }
                }).orNull();
        resolvedOverride[index++] = curOverride != null
                ? new DefaultPlanPhasePriceOverride(curPhase.getName(), curOverride.getCurrency(),
                        curOverride.getFixedPrice(), curOverride.getRecurringPrice())
                : null;
    }

    for (int i = 0; i < resolvedOverride.length; i++) {
        final PlanPhasePriceOverride curOverride = resolvedOverride[i];
        if (curOverride != null) {
            final DefaultPlanPhase curPhase = (DefaultPlanPhase) parentPlan.getAllPhases()[i];

            if (curPhase.getFixed() == null && curOverride.getFixedPrice() != null) {
                final String error = String.format("There is no existing fixed price for the phase %s",
                        curPhase.getName());
                throw new CatalogApiException(ErrorCode.CAT_INVALID_INVALID_PRICE_OVERRIDE,
                        parentPlan.getName(), error);
            }

            if (curPhase.getRecurring() == null && curOverride.getRecurringPrice() != null) {
                final String error = String.format("There is no existing recurring price for the phase %s",
                        curPhase.getName());
                throw new CatalogApiException(ErrorCode.CAT_INVALID_INVALID_PRICE_OVERRIDE,
                        parentPlan.getName(), error);
            }
        }
    }

    final String planName;
    if (context != null) {
        final CatalogOverridePlanDefinitionModelDao overriddenPlan = overrideDao
                .getOrCreateOverridePlanDefinition(parentPlan.getName(), catalogEffectiveDate, resolvedOverride,
                        context);
        planName = new StringBuffer(parentPlan.getName()).append("-").append(overriddenPlan.getRecordId())
                .toString();
    } else {
        planName = new StringBuffer(parentPlan.getName()).append("-dryrun-")
                .append(DRY_RUN_PLAN_IDX.incrementAndGet()).toString();
    }
    final DefaultPlan result = new DefaultPlan(planName, (DefaultPlan) parentPlan, resolvedOverride);
    result.initialize(standaloneCatalog, standaloneCatalog.getCatalogURI());
    if (context == null) {
        overriddenPlanCache.addDryRunPlan(planName, result);
    }
    return result;
}

From source file:org.jclouds.openstack.nova.v2_0.compute.predicates.GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.java

public org.jclouds.openstack.nova.v2_0.domain.Image findImage(final ZoneAndId zoneAndId) {
    return Iterables.tryFind(api.getImageApiForZone(zoneAndId.getZone()).listImagesInDetail(),
            new Predicate<org.jclouds.openstack.nova.v2_0.domain.Image>() {
                @Override/*from   w  w w.  j a v  a  2  s  .c  om*/
                public boolean apply(org.jclouds.openstack.nova.v2_0.domain.Image input) {
                    return input.getId().equals(zoneAndId.getId());
                }
            }).orNull();

}

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

public DefaultTier(Tier in, TierPriceOverride override, Currency currency) {
    this.limits = (DefaultLimit[]) in.getLimits();
    this.blocks = new DefaultTieredBlock[in.getTieredBlocks().length];

    for (int i = 0; i < in.getTieredBlocks().length; i++) {
        if (override != null && override.getTieredBlockPriceOverrides() != null) {
            final TieredBlock curTieredBlock = in.getTieredBlocks()[i];
            final TieredBlockPriceOverride overriddenTierBlock = Iterables.tryFind(
                    override.getTieredBlockPriceOverrides(), new Predicate<TieredBlockPriceOverride>() {
                        @Override
                        public boolean apply(final TieredBlockPriceOverride input) {
                            return (input != null
                                    && input.getUnitName().equals(curTieredBlock.getUnit().getName())
                                    && Double.compare(input.getSize(), curTieredBlock.getSize()) == 0
                                    && Double.compare(input.getMax(), curTieredBlock.getMax()) == 0);
                        }// w  w  w  .  j a v  a 2s.c om

                    }).orNull();
            blocks[i] = (overriddenTierBlock != null)
                    ? new DefaultTieredBlock(in.getTieredBlocks()[i], overriddenTierBlock, currency)
                    : (DefaultTieredBlock) in.getTieredBlocks()[i];
        } else {
            blocks[i] = (DefaultTieredBlock) in.getTieredBlocks()[i];
        }
    }
}

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

public org.jclouds.openstack.nova.v1_1.domain.Image findImage(final ZoneAndId zoneAndId) {
    return Iterables.tryFind(client.getImageClientForZone(zoneAndId.getZone()).listImagesInDetail(),
            new Predicate<org.jclouds.openstack.nova.v1_1.domain.Image>() {
                @Override//from  w w w.j ava  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:org.apache.brooklyn.container.location.kubernetes.KubernetesClientRegistryImpl.java

@Override
public KubernetesClient getKubernetesClient(ConfigBag conf) {
    ConfigBuilder configBuilder = new ConfigBuilder();

    String configFile = conf.get(KubernetesLocationConfig.KUBECONFIG);
    if (Strings.isNonBlank(configFile)) {
        try {/*from   w  w  w. j  a  v a2s .  co m*/
            Path configPath = Paths.get(configFile);
            Path configFolder = configPath.normalize().getParent();
            Config kubeconfig = KubeConfigUtils.parseConfig(configPath.toFile());
            String currentContext = Optional.fromNullable(conf.get(KubernetesLocationConfig.KUBECONFIG_CONTEXT))
                    .or(kubeconfig.getCurrentContext());
            Optional<NamedContext> foundContext = Iterables.tryFind(kubeconfig.getContexts(),
                    c -> c.getName().equals(currentContext));
            if (!foundContext.isPresent()) {
                throw new IllegalStateException(String.format("Context %s not found", currentContext));
            }
            Context context = foundContext.get().getContext();
            LOG.debug("Context {} additional properties: {}", currentContext,
                    context.getAdditionalProperties());
            configBuilder.withNamespace(context.getNamespace());

            String user = context.getUser();
            Optional<NamedAuthInfo> foundAuthInfo = Iterables.tryFind(kubeconfig.getUsers(),
                    u -> u.getName().equals(user));
            if (!foundAuthInfo.isPresent()) {
                throw new IllegalStateException(String.format("Auth info %s not found", user));
            }
            AuthInfo auth = foundAuthInfo.get().getUser();
            LOG.debug("Auth info {} additional properties: {}", user, auth.getAdditionalProperties());
            configBuilder.withUsername(auth.getUsername());
            configBuilder.withPassword(auth.getPassword());
            if (auth.getToken() == null) {
                if (auth.getAuthProvider() != null) {
                    configBuilder.withOauthToken(auth.getAuthProvider().getConfig().get("id-token"));
                }
            } else {
                configBuilder.withOauthToken(auth.getToken());
            }
            configBuilder.withClientCertFile(getRelativeFile(auth.getClientCertificate(), configFolder));
            configBuilder.withClientCertData(auth.getClientCertificateData());
            configBuilder.withClientKeyFile(getRelativeFile(auth.getClientKey(), configFolder));
            configBuilder.withClientKeyData(auth.getClientKeyData());

            String clusterName = context.getCluster();
            Optional<NamedCluster> foundCluster = Iterables.tryFind(kubeconfig.getClusters(),
                    c -> c.getName().equals(clusterName));
            if (!foundCluster.isPresent()) {
                throw new IllegalStateException(String.format("Cluster %s not found", clusterName));
            }
            Cluster cluster = foundCluster.get().getCluster();
            configBuilder.withMasterUrl(cluster.getServer());
            configBuilder.withCaCertFile(getRelativeFile(cluster.getCertificateAuthority(), configFolder));
            configBuilder.withCaCertData(cluster.getCertificateAuthorityData());
            configBuilder.withApiVersion(Optional.fromNullable(cluster.getApiVersion()).or("v1"));
            configBuilder.withTrustCerts(Boolean.TRUE.equals(cluster.getInsecureSkipTlsVerify()));
            LOG.debug("Cluster {} server: {}", clusterName, cluster.getServer());
            LOG.debug("Cluster {} additional properties: {}", clusterName, cluster.getAdditionalProperties());
        } catch (IOException e) {
            Exceptions.propagate(e);
        }
    } else {
        String masterUrl = checkNotNull(conf.get(KubernetesLocationConfig.MASTER_URL),
                "master url must not be null");
        Boolean trustCerts = conf.get(KubernetesLocationConfig.TRUST_CERTS);

        URL url;
        try {
            url = new URL(masterUrl);
        } catch (MalformedURLException e) {
            throw Throwables.propagate(e);
        }

        configBuilder.withMasterUrl(masterUrl).withTrustCerts(trustCerts != null ? trustCerts : Boolean.FALSE);

        if (url.getProtocol().equals("https")) {
            KubernetesCerts certs = new KubernetesCerts(conf);
            if (certs.caCertData.isPresent())
                configBuilder.withCaCertData(toBase64Encoding(certs.caCertData.get()));
            if (certs.clientCertData.isPresent())
                configBuilder.withClientCertData(toBase64Encoding(certs.clientCertData.get()));
            if (certs.clientKeyData.isPresent())
                configBuilder.withClientKeyData(toBase64Encoding(certs.clientKeyData.get()));
            if (certs.clientKeyAlgo.isPresent())
                configBuilder.withClientKeyAlgo(certs.clientKeyAlgo.get());
            if (certs.clientKeyPassphrase.isPresent())
                configBuilder.withClientKeyPassphrase(certs.clientKeyPassphrase.get());
            // TODO Should we also set configBuilder.withTrustCerts(true) here?
        }

        String username = conf.get(KubernetesLocationConfig.ACCESS_IDENTITY);
        if (Strings.isNonBlank(username))
            configBuilder.withUsername(username);

        String password = conf.get(KubernetesLocationConfig.ACCESS_CREDENTIAL);
        if (Strings.isNonBlank(password))
            configBuilder.withPassword(password);

        String token = conf.get(KubernetesLocationConfig.OAUTH_TOKEN);
        if (Strings.isNonBlank(token))
            configBuilder.withOauthToken(token);
    }

    Duration clientTimeout = conf.get(KubernetesLocationConfig.CLIENT_TIMEOUT);
    if (clientTimeout.isPositive()) {
        configBuilder.withConnectionTimeout((int) clientTimeout.toMilliseconds());
        configBuilder.withRequestTimeout((int) clientTimeout.toMilliseconds());
    } else {
        throw new IllegalArgumentException(
                "Kubernetes client timeout should be a positive duration: " + clientTimeout.toString());
    }
    Duration actionTimeout = conf.get(KubernetesLocationConfig.ACTION_TIMEOUT);
    if (actionTimeout.isPositive()) {
        configBuilder.withRollingTimeout(actionTimeout.toMilliseconds());
        configBuilder.withScaleTimeout(actionTimeout.toMilliseconds());
    } else {
        throw new IllegalArgumentException(
                "Kubernetes action timeout should be a positive duration: " + actionTimeout.toString());
    }

    return new DefaultKubernetesClient(configBuilder.build());
}

From source file:com.codereligion.diff.internal.linewriter.IterableLineWriter.java

/**
 * Transforms the given iterable value into a sorted list or throws an {@link MissingComparatorException}
 * if none was found./*from w  w  w .  j  a  v  a2 s  .  c o  m*/
 *
 * @param path the path which describes the position of the given item's iterable in the object graph
 * @param value the property value to sort into a list
 * @return a new sorted list of the given iterable
 * @throws MissingComparatorException if no comparator could be found for the given iterable
 */
private List<Object> transformToSortedList(final String path, final Iterable<Object> value) {
    final List<Object> list = Lists.newArrayList(value);
    final Optional<Object> firstElement = Iterables.tryFind(list, Predicates.notNull());

    if (!firstElement.isPresent()) {
        return list;
    }

    final Comparator<Object> comparator = findComparatorOrThrowException(path, firstElement.get());
    Collections.sort(list, comparator);

    return list;
}

From source file:com.github.jeluard.guayaba.base.PartialFunctions.java

/**
 * Execute result of execution of first {@link PartialFunction} whose return type matches specified `outputType`.
 *
 * @param <I>//from w  ww . jav  a2s  . c o m
 * @param <O>
 * @param <P>
 * @param <PF>
 * @param partialFunctions
 * @param type
 * @param element
 * @return result of first matching {@link PartialFunction}
 */
public static <I, O, P extends O, PF extends PartialFunction<I, ? extends O>> Optional<PF> tryFindForOutput(
        final Iterable<PF> partialFunctions, final Class<? extends P> type, final I element) {
    Preconditions.checkNotNull(partialFunctions, "null partialFunctions");
    Preconditions.checkNotNull(element, "null element");

    return Iterables.tryFind(partialFunctions,
            Predicates.and(new DefinedPredicate(element), new AssignableOutputPredicate(type)));
}

From source file:de.hybris.platform.servicelayer.internal.model.impl.RecordAssert.java

private Optional<PropertyHolder> findHolder(final Iterable<PropertyHolder> holders, final String propertyName) {
    if (holders == null) {
        return Optional.<PropertyHolder>absent();
    }/* w  w  w.  ja va 2s . c  o m*/

    return Iterables.tryFind(holders, new Predicate<PropertyHolder>() {

        @Override
        public boolean apply(final PropertyHolder input) {
            return propertyName.equals(input.getName());
        }
    });
}