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.plugin.catalog.test.models.PlanRulesModel.java

private <T> T find(final Iterable<T> all, @Nullable final String name, final String what,
        final Predicate<T> predicate) {
    if (name == null) {
        return null;
    }/*from ww w  . j a  v a2s .co m*/
    final T result = Iterables.tryFind(all, predicate).orNull();
    if (result == null) {
        throw new IllegalStateException(String.format("%s : cannot find entry %s", what, name));
    }
    return result;
}

From source file:brooklyn.storage.softlayer.SoftLayerRestClient.java

public Maybe<String> findVpcIdFromNetworkId(final String networkId) {
    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "listNetworks");
    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params)
            .addHeader("Accept", "application/json").build();

    request = getQuerySigner().filter(request);

    HttpToolResponse response = HttpUtil.invoke(request);
    JsonElement networks = json(response);
    LOG.debug("LIST NETWORKS\n" + pretty(networks));
    //get the first network object
    Optional<JsonElement> matchingNetwork = Iterables.tryFind(networks.getAsJsonObject()
            .get("listnetworksresponse").getAsJsonObject().get("network").getAsJsonArray(),
            new Predicate<JsonElement>() {
                @Override//from w w w  .  j  a  v a  2  s. co m
                public boolean apply(JsonElement jsonElement) {
                    JsonObject matchingNetwork = jsonElement.getAsJsonObject();
                    return matchingNetwork.get("id").getAsString().equals(networkId);
                }
            });
    return Maybe.of(matchingNetwork.get().getAsJsonObject().get("vpcid").getAsString());
}

From source file:com.kolich.curacao.components.ComponentTable.java

private final Object instantiate(final ImmutableSet<Class<?>> allComponents,
        final Map<Class<?>, Object> componentMap, final Class<?> component, final Set<Class<?>> depStack)
        throws Exception {
    // Locate a single constructor worthy of injecting with ~other~
    // components, if any.  May be null.
    final Constructor<?> ctor = getInjectableConstructor(component);
    Object instance = null;/*from  w w  w  .  ja v a 2  s  . co m*/
    if (ctor == null) {
        // Class.newInstance() is evil, so we do the ~right~ thing
        // here to instantiate a new instance of the component
        // using the preferred getConstructor() idiom.
        instance = component.getConstructor().newInstance();
    } else {
        final Class<?>[] types = ctor.getParameterTypes();
        // Construct an array of Object's outright to avoid system array
        // copying from a List/Collection to a vanilla array later.
        final Object[] params = new Object[types.length];
        for (int i = 0, l = types.length; i < l; i++) {
            final Class<?> type = types[i];
            // <https://github.com/markkolich/curacao/issues/7>
            // If the dependency stack contains the type we're tasked with
            // instantiating, but the component map already contains an
            // instance with this type, then it's ~not~ a real circular
            // dependency -- we already have what we need to fulfill the
            // request.
            if (depStack.contains(type) && !componentMap.containsKey(type)) {
                // Circular dependency detected, A -> B, but B -> A.
                // Or, A -> B -> C, but C -> A.  Can't do that, sorry!
                throw new CuracaoException("CIRCULAR DEPENDENCY DETECTED! " + "While trying to instantiate @"
                        + COMPONENT_ANNOTATION_SN + ": " + component.getCanonicalName() + " it depends "
                        + "on the other components (" + depStack + ")");
            } else if (componentMap.containsKey(type)) {
                // The component mapping table already contained an instance
                // of the component type we're after.  Simply grab it and
                // add it to the constructor parameter list.
                params[i] = componentMap.get(type);
            } else if (type.isInterface()) {
                // Interfaces are handled differently.  The logic here
                // involves finding some component, if any, that implements
                // the discovered interface type.  If one is found, we attempt
                // to instantiate it, if it hasn't been instantiated already.
                final Class<?> found = Iterables.tryFind(allComponents, Predicates.assignableFrom(type))
                        .orNull();
                if (found != null) {
                    // We found some component that implements the discovered
                    // interface.  Let's try to instantiate it.  Add the
                    // ~interface~ class type ot the dependency stack.
                    depStack.add(type);
                    final Object recursiveInstance =
                            // Recursion!
                            instantiate(allComponents, componentMap, found, depStack);
                    // Add the freshly instantiated component instance to the
                    // new component mapping table as we go.
                    componentMap.put(found, recursiveInstance);
                    // Add the freshly instantiated component instance to the
                    // list of component constructor arguments/parameters.
                    params[i] = recursiveInstance;
                } else {
                    // Found no component that implements the given interface.
                    params[i] = null;
                }
            } else {
                // The component mapping table does not contain a
                // component for the given class.  We might need to
                // instantiate a fresh one and then inject, checking
                // carefully for circular dependencies.
                depStack.add(component);
                final Object recursiveInstance =
                        // Recursion!
                        instantiate(allComponents, componentMap, type, depStack);
                // Add the freshly instantiated component instance to the
                // new component mapping table as we go.
                componentMap.put(type, recursiveInstance);
                // Add the freshly instantiated component instance to the
                // list of component constructor arguments/parameters.
                params[i] = recursiveInstance;
            }
        }
        instance = ctor.newInstance(params);
    }
    // The freshly freshly instantiated component instance may implement
    // a set of interfaces, and therefore, can be used to inject other
    // components that have specified it using only the interface and not
    // a concrete implementation.  As such, add each implemented interface
    // to the component map pointing directly to the concrete implementation
    // instance.
    for (final Class<?> interfacz : instance.getClass().getInterfaces()) {
        // If the component is decorated with 'CuracaoComponent' don't
        // bother trying to add said interfaces to the underlying component
        // map (they're special, internal to the toolkit, unrelated to
        // user defined interfaces).
        if (!interfacz.isAssignableFrom(CuracaoComponent.class)) {
            componentMap.put(interfacz, instance);
        }
    }
    return instance;
}

From source file:org.jclouds.virtualbox.util.MachineController.java

private void waitVBoxServiceIsActive(final String vmName) {
    machineUtils.sharedLockMachineAndApplyToSession(vmName, new Function<ISession, Void>() {

        @Override/*from  w ww  . j  a  v  a2 s .  com*/
        public Void apply(ISession session) {
            checkState(
                    retry(new AdditionsStatusPredicate(session), 10, 2, SECONDS)
                            .apply(AdditionsRunLevelType.Userland),
                    "timed out waiting for additionsRunLevelType to be %s", AdditionsRunLevelType.Userland);
            checkState(retry(new FacilitiesPredicate(session), 15, 3, SECONDS).apply(4),
                    "timed out waiting for 4 running facilities");
            Optional<IAdditionsFacility> vboxServiceFacility = Optional.absent();
            while (!vboxServiceFacility.isPresent()) {
                List<IAdditionsFacility> facilities = session.getConsole().getGuest().getFacilities();
                vboxServiceFacility = Iterables.tryFind(facilities, new Predicate<IAdditionsFacility>() {
                    @Override
                    public boolean apply(IAdditionsFacility additionsFacility) {
                        return additionsFacility.getType().equals(AdditionsFacilityType.VBoxService)
                                && additionsFacility.getStatus().equals(AdditionsFacilityStatus.Active);
                    }
                });
            }
            logger.debug("<< virtualbox service ready on vm(%s)", vmName);
            return null;
        }
    });
}

From source file:org.apache.brooklyn.entity.group.AbstractGroupImpl.java

/**
 * Returns {@code true} if the group was changed as a result of the call.
 *///from  w ww.ja v  a 2  s . c  o  m
@Override
public boolean removeMember(final Entity member) {
    synchronized (members) {
        member.removeGroup((Group) getProxyIfAvailable());
        boolean changed = (member != null && members.remove(member));
        if (changed) {
            log.debug("Group {} lost member {}", this, member);
            // TODO ideally the following are all synched
            sensors().set(GROUP_SIZE, getCurrentSize());
            sensors().set(GROUP_MEMBERS, getMembers());
            if (member.equals(getAttribute(FIRST))) {
                // TODO should we elect a new FIRST ?  as is the *next* will become first.  could we do away with FIRST altogether?
                sensors().set(FIRST, null);
            }
            // emit after the above so listeners can use getMembers() and getCurrentSize()
            sensors().emit(MEMBER_REMOVED, member);

            if (Boolean.TRUE.equals(getConfig(MEMBER_DELEGATE_CHILDREN))) {
                Optional<Entity> result = Iterables.tryFind(getChildren(), new Predicate<Entity>() {
                    @Override
                    public boolean apply(Entity input) {
                        Entity delegate = input.getConfig(DelegateEntity.DELEGATE_ENTITY);
                        if (delegate == null)
                            return false;
                        return delegate.equals(member);
                    }
                });
                if (result.isPresent()) {
                    Entity child = result.get();
                    removeChild(child);
                    Entities.unmanage(child);
                }
            }

            getManagementSupport().getEntityChangeListener().onMembersChanged();
        }

        return changed;
    }
}

From source file:com.offbytwo.jenkins.model.JobWithDetails.java

public Build getBuildByNumber(final int buildNumber) {

    Predicate<Build> isMatchingBuildNumber = new Predicate<Build>() {

        @Override//from w w  w.  ja  va2  s . c o m
        public boolean apply(Build input) {
            return input.getNumber() == buildNumber;
        }
    };

    Optional<Build> optionalBuild = Iterables.tryFind(builds, isMatchingBuildNumber);
    //TODO: Check if we could use Build#NO...instead of Null?
    return optionalBuild.orNull() == null ? null : buildWithClient(optionalBuild.orNull());
}

From source file:bear.core.Bear.java

public Stage findStage(GlobalContext $) {
    final String stageName = $.var(this.stage);
    final Optional<Stage> optional = Iterables.tryFind($.var(stages).stages, new Predicate<Stage>() {
        public boolean apply(Stage s) {
            return s.name.equals(stageName);
        }/*from  w ww.  j a  va  2s .c o  m*/
    });

    if (!optional.isPresent()) {
        throw new RuntimeException("stage not found: '" + stageName + "'");
    }

    Stage stage = optional.get();
    stage.global = global;

    return stage;
}

From source file:org.killbill.billing.tenant.api.user.DefaultTenantUserApi.java

private boolean isSingleValueKey(final String key) {
    return Iterables.tryFind(ImmutableList.copyOf(TenantKey.values()), new Predicate<TenantKey>() {
        @Override/*from w ww  . j a v a2 s  .com*/
        public boolean apply(final TenantKey input) {
            return input.isSingleValue() && key.startsWith(input.toString());
        }
    }).orNull() != null;
}

From source file:org.opentestsystem.authoring.testauth.validation.AbstractDomainValidator.java

protected void validateParameterValue(final String parameterValue, final String parametersFieldName,
        final ItemSelectionAlgorithmParameter algorithmParameter, final Errors errors) {
    final Object[] errorArgs = new Object[] { algorithmParameter.getItemSelectionType().name(), parameterValue,
            algorithmParameter.getMinimumValue(), algorithmParameter.getMaximumValue() };

    if (StringUtils.isEmpty(parameterValue)) {
        rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_REQUIRED);
    } else {/*w w w. j  ava 2  s .co m*/
        switch (algorithmParameter.getItemSelectionType()) {
        case FLOAT:
        case INTEGER:
            if (parameterValue.length() > MAX_PARSEABLE_LENGTH) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_LENGTH_MAX,
                        MAX_PARSEABLE_LENGTH);
            } else {
                rejectIfNotWithinNumericConstraints(parameterValue, parametersFieldName, errors,
                        algorithmParameter, errorArgs);
            }
            break;
        case BOOLEAN:
            if (!Boolean.TRUE.toString().equals(parameterValue)
                    && !Boolean.FALSE.toString().equals(parameterValue)) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_INVALID, errorArgs);
            }
            break;
        case LIST:
            if (!Iterables.tryFind(algorithmParameter.getItemSelectionList(),
                    ITEM_SELECTION_VALUE_FILTER.getInstance(parameterValue)).isPresent()) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_INVALID_SELECTION);
            }
            break;
        case STRING:
            if (parameterValue.length() > MAX_STRING_LENGTH) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_LENGTH_MAX,
                        MAX_STRING_LENGTH);
            }
            break;
        default:
            rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_TYPE_NOT_RECOGNIZED);
            break;
        }
    }
}

From source file:org.killbill.billing.invoice.api.svcs.DefaultInvoiceInternalApi.java

private InvoicePayment getInvoicePayment(final UUID paymentId, final InvoicePaymentType type,
        final InternalTenantContext context) throws InvoiceApiException {

    final List<InvoicePaymentModelDao> invoicePayments = dao.getInvoicePaymentsByPaymentId(paymentId, context);
    final InvoicePaymentModelDao resultOrNull = Iterables
            .tryFind(invoicePayments, new Predicate<InvoicePaymentModelDao>() {
                @Override/* w  w w.j a va  2  s . c o  m*/
                public boolean apply(final InvoicePaymentModelDao input) {
                    return input.getType() == type && input.getSuccess();
                }
            }).orNull();
    return resultOrNull != null ? new DefaultInvoicePayment(resultOrNull) : null;
}