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

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

Introduction

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

Prototype

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

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

From source file:com.netxforge.netxstudio.common.model.StudioUtils.java

/**
 * Filter a collection of {@link Value}, omitting the values which have do
 * not occur in the target {@link Date} collection.
 * /*from w  w  w .ja v  a  2  s.c o  m*/
 * @param d
 * @return
 */
public static List<Value> valuesForTimestamps(Iterable<Value> unfiltered,
        final Collection<Date> timeStampDates) {

    Iterable<Value> filtered = Iterables.filter(unfiltered, new Predicate<Value>() {
        public boolean apply(final Value input) {
            final Date valueDate = NonModelUtils.fromXMLDate(input.getTimeStamp());
            return Iterables.any(timeStampDates, new Predicate<Date>() {
                public boolean apply(Date inputDate) {
                    return valueDate.compareTo(inputDate) == 0;
                }
            });
        }

    });

    return Lists.newArrayList(filtered);
}

From source file:org.eclipse.che.ide.ext.svn.server.SubversionApi.java

/**
 * Perform an "svn move" based on the request.
 *
 * @param request//from   w w  w .  j a v  a2s .c  om
 *         the request
 * @return the response
 * @throws IOException
 *         if there is a problem executing the command
 * @throws SubversionException
 *         if there is a Subversion issue
 */
public CLIOutputResponse move(final MoveRequest request) throws IOException, SubversionException {

    Predicate<String> sourcePredicate = new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return input.startsWith("file://");
        }
    };

    //for security reason we should forbid file protocol
    if (Iterables.any(request.getSource(), sourcePredicate) || request.getDestination().startsWith("file://")) {
        throw new SubversionException("Url is not acceptable");
    }

    final File projectPath = new File(request.getProjectPath());

    final List<String> cliArgs = defaultArgs();

    if (!Strings.isNullOrEmpty(request.getComment())) {
        addOption(cliArgs, "--message", "\"" + request.getComment() + "\"");
    }

    // Command Name
    cliArgs.add("move");

    final List<String> paths = new ArrayList<>();
    paths.addAll(request.getSource());
    paths.add(request.getDestination());

    final CommandLineResult result = runCommand(null, cliArgs, projectPath, paths);

    return DtoFactory.getInstance().createDto(CLIOutputResponse.class)
            .withCommand(result.getCommandLine().toString()).withOutput(result.getStdout())
            .withErrOutput(result.getStderr());
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.validation.EMFPatternLanguageValidator.java

private void reportMissingParameterTypeDeclaration(Variable parameter, Set<IInputKey> possibleTypes,
        IInputKey inferredType) {//from w  ww  . jav  a 2 s.  c om
    if (possibleTypes.isEmpty()) {
        return;
    } else if (possibleTypes.size() == 1 && !(possibleTypes.iterator().next() instanceof BottomTypeKey)) {
        String[] issueData = new String[] { calculateIssueData(inferredType) };
        warning("Type not defined for variable " + parameter.getName() + ", inferred type "
                + typeSystem.typeString(inferredType) + " is used instead.",
                PatternLanguagePackage.Literals.VARIABLE__NAME, IssueCodes.MISSING_PARAMETER_TYPE, issueData);
    } else {
        Set<IInputKey> orderedTypes = ImmutableSortedSet.<IInputKey>orderedBy((o1, o2) -> {
            if (o1 instanceof EClassTransitiveInstancesKey && !(o2 instanceof EClassTransitiveInstancesKey)) {
                return +1;
            } else if (o2 instanceof EClassTransitiveInstancesKey
                    && !(o1 instanceof EClassTransitiveInstancesKey)) {
                return -1;
            } else if (o1 instanceof EDataTypeInSlotsKey && !(o2 instanceof EDataTypeInSlotsKey)) {
                return +1;
            } else if (o2 instanceof EDataTypeInSlotsKey && !(o1 instanceof EDataTypeInSlotsKey)) {
                return +1;
            } else if (typeSystem.isConformant(o1, o2)) { //Common type group
                return +1;
            } else if (typeSystem.isConformant(o2, o1)) {
                return -1;
            }
            return 0;
        }).addAll(possibleTypes).build();
        Set<String> superClasses = (Iterables.any(possibleTypes,
                EClassTransitiveInstancesKey.class::isInstance)) ? ImmutableSet.of("EObject")
                        : ImmutableSet.of(IssueCodes.JAVA_TYPE_PREFIX + "java.lang.Object");
        Iterable<String> typeNames = Iterables.concat(Iterables
                .filter(Iterables.transform(orderedTypes, this::calculateIssueData), Predicates.notNull()),
                superClasses);
        String[] issueData = Iterables.toArray(typeNames, String.class);
        if (issueData.length > 0) {
            warning("Type not defined for variable " + parameter.getName() + ", inferred type "
                    + typeSystem.typeString(inferredType) + " is used instead.",
                    PatternLanguagePackage.Literals.VARIABLE__NAME, IssueCodes.MISSING_PARAMETER_TYPE,
                    issueData);
        }
    }
}

From source file:org.eclipse.emf.compare.uml2.internal.postprocessor.AbstractUMLChangeFactory.java

/**
 * It checks if the given difference concerns is related to a macroscopic CHANGE within a macroscopic
 * ADD/DELETE.//from w  w w . j  a va  2s .com
 * 
 * @param input
 *            The given difference.
 * @param comparison
 *            the related comparison.
 * @param discriminant
 *            The discriminant found for the given difference.
 * @return True if it is related to a CHANGE in an ADD/DELETE.
 */
private boolean isChangeOnAddOrDelete(Diff input, final Comparison comparison, final EObject discriminant) {
    boolean result = false;
    Match match = comparison.getMatch(discriminant);
    if (match != null && Iterables.any(match.getDifferences(), instanceOf(ResourceAttachmentChange.class))) {
        result = true;
    }
    if (!result) {
        final List<Diff> candidates = comparison.getDifferences(discriminant);
        for (Diff diff : candidates) {
            if (diff == input) {
                // ignore this one
            } else {
                DifferenceKind relatedExtensionKind = getRelatedExtensionKind(diff);
                if ((relatedExtensionKind == DifferenceKind.ADD
                        || relatedExtensionKind == DifferenceKind.DELETE)
                        && getDiscriminant(diff) == discriminant) {
                    result = true;
                    break;
                }
            }
        }
    }
    return result;
}

From source file:org.eclipse.incquery.tooling.core.project.ProjectGenerationHelper.java

/**
 * @param extensionMap/*  ww  w  .  jav a  2s.  co  m*/
 * @param extension
 * @param id
 * @return
 */
private static boolean isExtensionInMap(Multimap<String, IPluginExtension> extensionMap,
        final IPluginExtension extension, String id) {
    boolean extensionToCreateFound = false;
    if (extensionMap.containsKey(id)) {
        extensionToCreateFound = Iterables.any(extensionMap.get(id), new Predicate<IPluginExtension>() {
            @Override
            public boolean apply(IPluginExtension ex) {
                return ex.getPoint().equals(extension.getPoint());
            }
        });
    }
    return extensionToCreateFound;
}

From source file:org.geoserver.importer.Importer.java

public void run(ImportContext context, ImportFilter filter, ProgressMonitor monitor) throws IOException {
    context.setProgress(monitor);/*from   w w  w  .java 2 s .  c  o  m*/
    context.setState(ImportContext.State.RUNNING);

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Running import " + context.getId());
    }

    for (ImportTask task : context.getTasks()) {
        if (!filter.include(task)) {
            continue;
        }
        if (!task.readyForImport()) {
            continue;
        }

        if (context.progress().isCanceled()) {
            break;
        }
        run(task);
    }

    context.updated();
    contextStore.save(context);

    if (context.isArchive() && context.getState() == ImportContext.State.COMPLETE) {
        boolean canArchive = !Iterables.any(context.getTasks(), new Predicate<ImportTask>() {
            @Override
            public boolean apply(ImportTask input) {
                return input.isDirect();
            }
        });

        if (canArchive) {
            Directory directory = null;
            if (context.getData() instanceof Directory) {
                directory = (Directory) context.getData();
            } else if (context.getData() instanceof SpatialFile) {
                directory = new Directory(((SpatialFile) context.getData()).getFile().getParentFile());
            }
            if (directory != null) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine("Archiving directory " + directory.getFile().getAbsolutePath());
                }
                try {
                    directory.archive(getArchiveFile(context));
                } catch (Exception ioe) {
                    ioe.printStackTrace();
                    // this is not a critical operation, so don't make the whole thing fail
                    LOGGER.log(Level.WARNING, "Error archiving", ioe);
                }
            }
        }

    }
}

From source file:de.iteratec.iteraplan.model.user.PermissionHelper.java

/**
 * Some permissions are not actually contained in the map: child, children, parent, predecessors,
 * successors, generalisation, specialisations, parentcomponents and basecomponents are available,
 * if the permission for the BB itself is available
 * //from w ww  .j  a  v a  2s.  c  om
 * @param nameKey
 * @return the normalized key, additionally converted to lowercase.
 */
private static String normalizeKey(String nameKey) {
    Set<String> suffixes = new ImmutableSet.Builder<String>().add(".child").add(".children").add(".parent")
            .add(".predecessors").add(".successors").add(".generalisation").add(".specialisations")
            .add(".parentcomponents").add(".basecomponents").build();

    String normKey = nameKey.toLowerCase();
    if (Iterables.any(suffixes, new StringEndsWithPredicate(normKey))) {
        normKey = normKey.substring(0, normKey.lastIndexOf('.'));
    }
    return normKey;
}

From source file:org.pantsbuild.tools.junit.ConsoleRunner.java

private static boolean isTest(final Class<?> clazz) {
    // Must be a public concrete class to be a runnable junit Test.
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())
            || !Modifier.isPublic(clazz.getModifiers())) {
        return false;
    }/*from   w  w w  .  ja  v  a2  s . co m*/

    // The class must have some public constructor to be instantiated by the runner being used
    if (!Iterables.any(Arrays.asList(clazz.getConstructors()), IS_PUBLIC_CONSTRUCTOR)) {
        return false;
    }

    // Support junit 3.x Test hierarchy.
    if (junit.framework.Test.class.isAssignableFrom(clazz)) {
        return true;
    }

    // Support classes using junit 4.x custom runners.
    if (clazz.isAnnotationPresent(RunWith.class)) {
        return true;
    }

    // Support junit 4.x @Test annotated methods.
    return Iterables.any(Arrays.asList(clazz.getMethods()), IS_ANNOTATED_TEST_METHOD);
}

From source file:org.immutables.value.processor.meta.ValueType.java

private boolean useCollectionUtility(Predicate<ValueAttribute> predicate) {
    for (ValueType n : nested) {
        if (Iterables.any(n.getSettableAttributes(), predicate)) {
            return true;
        }// w w w  . j av  a 2  s.com
    }
    return Iterables.any(getSettableAttributes(), predicate);
}

From source file:org.trancecode.xproc.step.Step.java

public boolean hasLogDeclaredForPort(final String port) {
    return Iterables.any(logs, log -> log.port.equals(port));
}