Example usage for com.google.common.collect Iterables find

List of usage examples for com.google.common.collect Iterables find

Introduction

In this page you can find the example usage for com.google.common.collect Iterables find.

Prototype

public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:org.jclouds.vcloud.terremark.xml.KeyPairByNameHandler.java

@Override
public KeyPair getResult() {
    final String name = getRequest().getArgs().get(1).toString();
    try {/*from   w  ww.j  a v a  2s  .  c  o m*/
        return Iterables.find(handler.getResult(), new Predicate<KeyPair>() {

            @Override
            public boolean apply(KeyPair input) {
                return input.getName().equals(name);
            }

        });
    } catch (NoSuchElementException e) {
        logger.debug("keypair %s/%s not found in %s", getRequest().getArgs().get(0), name, handler.getResult());
        return null;
    }
}

From source file:org.jclouds.collect.FindResourceInSet.java

public T apply(final F from) {
    try {//from www  . j  a  va 2s .c o  m
        return Iterables.find(set.get(), new Predicate<T>() {

            @Override
            public boolean apply(T input) {
                return matches(from, input);
            }

        });
    } catch (NoSuchElementException e) {
        logger.warn("could not find a match in set for %s", from);
    }
    return null;
}

From source file:com.atlassian.jira.rest.client.api.domain.EntityHelper.java

public static <T extends NamedEntity> T findEntityByName(Iterable<T> entities, final String name) {
    try {//from   w ww .  ja v  a  2s .c o  m
        return Iterables.find(entities, HasNamePredicate.forName(name));
    } catch (NoSuchElementException ex) {
        throw new NoSuchElementException(
                String.format("Entity with name \"%s\" not found. Entities: %s", name, entities.toString()));
    }
}

From source file:com.bennavetta.vetinari.template.TemplateLoader.java

@Inject
public TemplateLoader(VetinariContext context, Set<TemplateEngine> templateEngines) {
    this.context = context;
    this.templateEngines = templateEngines;
    this.defaultTemplateEngine = Iterables.find(this.templateEngines,
            t -> t.getName().equals(this.context.getSiteConfig().getString("defaultTemplateEngine")));

    this.templateCache = CacheBuilder.newBuilder().build(new CacheLoader<String, Template>() {
        @Override/*from w w  w.ja  v  a  2  s .  c  om*/
        public Template load(String templateName) throws Exception {
            final Path templatePath = context.getTemplateRoot().resolve(templateName);
            final String extension = getFileExtension(templateName);
            final TemplateEngine engine = Iterables
                    .tryFind(templateEngines, t -> Iterables.contains(t.getFileExtensions(), extension))
                    .or(defaultTemplateEngine);
            log.debug("Compiling template from {} with {}", templatePath, engine);
            String source = new String(Files.readAllBytes(templatePath), context.getContentEncoding());
            log.trace("Read template source \"{}\"", source);
            return engine.compile(source);
        }
    });
}

From source file:org.openengsb.core.services.internal.TransformationHandler.java

/**
 * tries to find a method that method in the class {@code target} with the same name and the same number of
 * arguments. It's assumed that the arguments can then be transformed.
 *
 * @throws java.util.NoSuchElementException
 *          if no matching method can be found
 *//*from ww  w .  jav a2  s . c o m*/
protected static Method findTargetMethod(final Method sourceMethod, Class<?> target)
        throws NoSuchElementException {
    return Iterables.find(Arrays.asList(target.getMethods()), new Predicate<Method>() {
        @Override
        public boolean apply(Method element) {
            if (!sourceMethod.getName().equals(element.getName())) {
                return false;
            }
            if (sourceMethod.getParameterTypes().length != element.getParameterTypes().length) {
                return false;
            }
            return true;
        }
    });
}

From source file:com.freiheit.fuava.simplebatch.result.ComposedResult.java

/**
 * If there are no results, fail. If there is one successful result, return
 * success. Add warnings for any values that exceed.
 *///from  w w  w .j a v a 2s  .co  m
public Result<A, B> compose(final Iterable<? extends Result<?, B>> results) {
    if (results == null || Iterables.isEmpty(results)) {
        return builder.withFailureMessage(
                "No intermediate results found. Intermediate input was " + intermediateValue).failed();
    }
    final Result<?, B> firstSuccess = Iterables.find(results, Result::isSuccess);
    for (final Result<?, B> r : results) {
        // add everything that was accumulated in the composed results
        builder.withFailureMessages(r.getFailureMessages()).withWarningMessages(r.getWarningMessages())
                .withThrowables(r.getThrowables());
    }
    if (firstSuccess == null) {
        return builder.failed();
    }
    return builder.withOutput(firstSuccess.getOutput()).success();
}

From source file:org.jclouds.trmk.vcloud_0_8.xml.KeyPairByNameHandler.java

@Override
public KeyPair getResult() {
    final String name = getRequest().getInvocation().getArgs().get(1).toString();
    try {/* w  w w  . j av  a  2s  . co m*/
        return Iterables.find(handler.getResult(), new Predicate<KeyPair>() {

            @Override
            public boolean apply(KeyPair input) {
                return input.getName().equals(name);
            }

        });
    } catch (NoSuchElementException e) {
        logger.debug("keypair %s/%s not found in %s", getRequest().getInvocation().getArgs().get(0), name,
                handler.getResult());
        return null;
    }
}

From source file:org.sonar.batch.debt.DebtModelProvider.java

private static CharacteristicDto characteristicById(final int id, List<CharacteristicDto> allCharacteristics) {
    return Iterables.find(allCharacteristics, new Predicate<CharacteristicDto>() {
        @Override/*from  w  ww  .j a v a  2s  .c  om*/
        public boolean apply(@Nullable CharacteristicDto input) {
            return input != null && id == input.getId();
        }
    });
}

From source file:org.midonet.client.resource.ResourceCollection.java

/**
 * Finds a resource by the given key and value for the resource model.
 *
 * @param key   attribute name (case insensitive)
 * @param value value to look for/*from  w  ww .j a v a  2 s.  c  o  m*/
 * @return First matched element
 */
@Deprecated // TODO: let client use find() method defined below.
public E findBy(final String key, final Object value) {
    final String keyGetter = ("get" + key).toLowerCase();
    // this extends forwarding list, therefore should be Iterable.
    @SuppressWarnings("unchecked")
    E result = Iterables.find((Iterable<E>) this, new Predicate<E>() {
        @Override
        public boolean apply(E input) {
            Method[] methods = input.getClass().getMethods();
            for (Method m : methods) { // O(n) but should be small.
                if (m.getName().toLowerCase().equals(keyGetter)) {
                    try {
                        //Getter method of the value should return
                        @SuppressWarnings("unchecked")
                        Object data = m.invoke(input, new Object[] {});
                        if (data == null) {
                            return data == value;
                        }
                        return data.equals(value);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
            throw new IllegalArgumentException(
                    "No matched entry found " + "for searching key=" + key + "value=" + value);
        }
    });
    return result;
}

From source file:org.eclipse.xtext.ui.refactoring.impl.ProjectUtil.java

/**
 * @return null if there is no such file or the file is not editable
 *///from w w w .  j  ava 2 s .co  m
public IFile findFileStorage(final URI uri, final boolean validateEdit) {
    Iterable<Pair<IStorage, IProject>> storages = mapper.getStorages(uri);
    try {
        Pair<IStorage, IProject> fileStorage = Iterables.find(storages,
                new Predicate<Pair<IStorage, IProject>>() {
                    @Override
                    public boolean apply(Pair<IStorage, IProject> input) {
                        IStorage storage = input.getFirst();
                        if (storage instanceof IFile) {
                            IFile file = (IFile) storage;
                            return file.isAccessible() && (!validateEdit || !file.isReadOnly()
                                    || workspace.validateEdit(new IFile[] { file }, null).isOK());
                        }
                        return false;
                    }
                });
        return (IFile) fileStorage.getFirst();
    } catch (NoSuchElementException e) {
        return null;
    }
}