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.jclouds.virtualbox.statements.InstallGuestAdditions.java

private List<Statement> getStatements(VmSpec vmSpecification, String vboxVersion) {
    List<Statement> statements = Lists.newArrayList();
    statements.add(call("installModuleAssistantIfNeeded"));
    String mountPoint = "/mnt";
    if (Iterables.tryFind(vmSpecification.getControllers(), new Predicate<StorageController>() {
        @Override/*w w w. j a va  2 s . c  om*/
        public boolean apply(StorageController input) {
            if (!input.getIsoImages().isEmpty()) {
                for (IsoImage iso : input.getIsoImages()) {
                    if (iso.getSourcePath().contains("VBoxGuestAdditions_")) {
                        return true;
                    }
                }
            }
            return false;
        }
    }).isPresent()) {
        statements.add(exec("mount -t iso9660 /dev/cdrom1 " + mountPoint));
    } else {
        String vboxGuestAdditionsIso = "VBoxGuestAdditions_" + vboxVersion + ".iso";
        URI download = URI.create(
                "http://download.virtualbox.org/virtualbox/" + vboxVersion + "/" + vboxGuestAdditionsIso);
        statements.add(call("setupPublicCurl"));
        statements.add(saveHttpResponseTo(download, "{tmp}{fs}", vboxGuestAdditionsIso));//
        statements.add(exec(String.format("mount -o loop {tmp}{fs}%s %s", vboxGuestAdditionsIso, mountPoint)));
    }
    statements.add(exec(String.format("%s%s", mountPoint, "/VBoxLinuxAdditions.run --nox11")));
    return statements;
}

From source file:org.apache.brooklyn.util.core.flags.MethodCoercions.java

/**
 * Tries to find a single-parameter method with a parameter compatible with (can be coerced to) the argument, and
 * invokes it./*from  ww  w .  j a v  a2 s .c  om*/
 *
 * @param instance the object to invoke the method on
 * @param methodName the name of the method to invoke
 * @param argument the argument to the method's parameter.
 * @return the result of the method call, or {@link org.apache.brooklyn.util.guava.Maybe#absent()} if method could not be matched.
 */
public static Maybe<?> tryFindAndInvokeSingleParameterMethod(final Object instance, final String methodName,
        final Object argument) {
    Class<?> clazz = instance.getClass();
    Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    Optional<Method> matchingMethod = Iterables.tryFind(methods,
            matchSingleParameterMethod(methodName, argument));
    if (matchingMethod.isPresent()) {
        Method method = matchingMethod.get();
        try {
            Type paramType = method.getGenericParameterTypes()[0];
            Object coercedArgument = TypeCoercions.coerce(argument, TypeToken.of(paramType));
            return Maybe.of(method.invoke(instance, coercedArgument));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw Exceptions.propagate(e);
        }
    } else {
        return Maybe.absent();
    }
}

From source file:org.ow2.play.governance.platform.user.service.PermissionCheck.java

@Override
public boolean checkGroup(String user, final String group) {
    User u = null;//w  w w . ja  va  2s.c om
    try {
        u = userService.getUser(user);
    } catch (UserException e) {
        // logger
        e.printStackTrace();
    }

    return u != null && u.groups != null && Iterables.tryFind(u.groups, new Predicate<Resource>() {
        public boolean apply(Resource input) {
            return input.uri != null && input.name != null && group.equals(input.uri + "#" + input.name);
        }
    }).isPresent();
}

From source file:org.apache.drill.exec.util.Utilities.java

/**
 * Return true if list of schema path has star column.
 * @param projected/* ww w .  j  a va 2 s.co m*/
 * @return
 */
public static boolean isStarQuery(Collection<SchemaPath> projected) {
    return Iterables
            .tryFind(Preconditions.checkNotNull(projected, COL_NULL_ERROR), new Predicate<SchemaPath>() {
                @Override
                public boolean apply(SchemaPath path) {
                    return Preconditions.checkNotNull(path).equals(SchemaPath.STAR_COLUMN);
                }
            }).isPresent();
}

From source file:org.ow2.petals.cloud.manager.core.actions.PuppetRunAction.java

/**
 * Get the puppet script content. ie generate it from node and context properties.
 * First look at the node, then if not found, search at the context level.
 *
 * @param node/*from   ww w  .  j  a v a2  s.c o m*/
 * @param context
 * @return
 * @throws CloudManagerException
 */
@Override
protected String getScriptContent(Node node, Context context) throws CloudManagerException {
    // get the script from the node properties
    Property script = Iterables.tryFind(node.getProperties(), new Predicate<Property>() {
        public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Property input) {
            return input.getName() != null && input.getName().equalsIgnoreCase(Constants.PUPPET_SCRIPT);
        }
        // search at the descriptor level if not found in node...
    }).or(Iterables.tryFind(context.getDescriptor().getProperties(), new Predicate<Property>() {
        public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Property input) {
            return input.getName() != null && input.getName().equalsIgnoreCase(Constants.PUPPET_SCRIPT);
        }
    })).orNull();

    if (script == null) {
        throw new CloudManagerException("Can not find puppet script content");
    }

    // get the script content or generate it...
    // First search for the type of script, ie generate, provided as content, in the classpath, as URL, ...

    checkNotNull(script.getType());
    // script type property can have several values which will define where to get the script template :

    // TODO : Later. For now, let's assume that the property value is the pattern name to retrieve from the classpath...
    // TODO : We can also get them from a pattern registry...
    String name = script.getValue();
    String path = "/org/ow2/petals/cloud/manager/puppet/" + name + ".template";

    return null;
}

From source file:org.zanata.webtrans.server.rpc.UpdateTransUnitHandler.java

@Override
public UpdateTransUnitResult execute(UpdateTransUnit action, ExecutionContext context) throws ActionException {

    Optional<TransUnitUpdateRequest> hasReviewUpdate = Iterables.tryFind(action.getUpdateRequests(),
            new Predicate<TransUnitUpdateRequest>() {
                @Override/*from  w  w w .  j a  v  a2  s  .c om*/
                public boolean apply(TransUnitUpdateRequest input) {
                    return input.getNewContentState().isReviewed();
                }
            });
    if (hasReviewUpdate.isPresent()) {
        securityServiceImpl.checkWorkspaceAction(action.getWorkspaceId(),
                SecurityService.TranslationAction.REVIEW);
    } else {
        securityServiceImpl.checkWorkspaceAction(action.getWorkspaceId(),
                SecurityService.TranslationAction.MODIFY);
    }

    return doTranslation(action.getWorkspaceId().getLocaleId(), action.getUpdateRequests(),
            action.getEditorClientId(), action.getUpdateType());
}

From source file:brooklyn.entity.nosql.mongodb.sharding.MongoDBRouterClusterImpl.java

protected void setAnyRouter() {
    setAttribute(MongoDBRouterCluster.ANY_ROUTER, Iterables
            .tryFind(getRouters(), EntityPredicates.attributeEqualTo(Startable.SERVICE_UP, true)).orNull());

    setAttribute(MongoDBRouterCluster.ANY_RUNNING_ROUTER, Iterables
            .tryFind(getRouters(), EntityPredicates.attributeEqualTo(MongoDBRouter.RUNNING, true)).orNull());
}

From source file:com.payu.ratel.client.RemoteAutowireCandidateResolver.java

private static Optional<Annotation> getAnnotationWithType(DependencyDescriptor descriptor, final Class clazz) {
    return Iterables.tryFind(Arrays.asList(descriptor.getAnnotations()), new Predicate<Annotation>() {
        @Override// w w  w  .j a  va  2s .  c om
        public boolean apply(Annotation input) {
            return clazz.getName().equals(input.annotationType().getName());
        }
    });
}

From source file:org.apache.provisionr.commands.DestroyPoolCommand.java

@Override
protected Object doExecute() {
    checkNotNull(businessKey, "pool business key is mandatory");

    ProcessInstance instance = processEngine.getRuntimeService().createProcessInstanceQuery()
            .processInstanceBusinessKey(businessKey).singleResult();
    checkNotNull(instance, "no pool found with key " + businessKey);

    String providerId = (String) processEngine.getRuntimeService().getVariable(instance.getId(),
            CoreProcessVariables.PROVIDER);
    checkNotNull(providerId, "the process instance has no provider ID");

    Optional<Provisionr> service = Iterables.tryFind(services, ProvisionrPredicates.withId(providerId));

    if (service.isPresent()) {
        service.get().destroyPool(businessKey);
    } else {//from ww  w.j  av  a2 s  .  c o m
        throw new NoSuchElementException("No provisioning service found with id: " + providerId);
    }

    return null;
}

From source file:org.eclipse.osee.orcs.rest.internal.AttributeResource.java

@GET
@Produces(MediaType.TEXT_PLAIN)/*from  ww  w  .  j a  v a2 s  . com*/
public String getAsText() throws OseeCoreException {
    IOseeBranch branch = TokenFactory.createBranch(branchUuid, "");
    QueryFactory factory = OrcsApplication.getOrcsApi().getQueryFactory(null);
    QueryBuilder queryBuilder = factory.fromBranch(branch).andGuid(artifactUuid);
    if (transactionId > 0) {
        queryBuilder.fromTransaction(transactionId);
    }
    ArtifactReadable exactlyOne = queryBuilder.getResults().getExactlyOne();

    Optional<? extends AttributeReadable<Object>> item = Iterables.tryFind(exactlyOne.getAttributes(),
            new Predicate<AttributeReadable<Object>>() {
                @Override
                public boolean apply(AttributeReadable<Object> attribute) {
                    return attribute.getLocalId() == attrId;
                }
            });

    String toReturn = "";
    if (item.isPresent()) {
        Object value = item.get().getValue();
        if (value != null) {
            toReturn = value.toString();
        }
    }
    return toReturn;
}