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:fr.javatronic.damapping.intellij.plugin.integration.psiparsing.impl.PsiParsingServiceImpl.java

private List<DAMethod> extractMethods(PsiClass psiClass, final PsiContext psiContext) {
    List<DAMethod> daMethods = from(Arrays.asList(psiClass.getChildren())).filter(PsiMethod.class)
            .transform(new Function<PsiMethod, DAMethod>() {
                @Nullable//from  w  w w  .j a  v a2 s .  c  o  m
                @Override
                public DAMethod apply(@Nullable PsiMethod psiMethod) {
                    if (psiMethod == null) {
                        return null;
                    }
                    return daMethodBuilder(psiMethod).withName(DANameFactory.from(psiMethod.getName()))
                            .withAnnotations(extractAnnotations(psiMethod.getModifierList(), psiContext))
                            .withModifiers(daModifierExtractor.extractModifiers(psiMethod))
                            .withParameters(extractParameters(psiMethod, psiContext))
                            .withReturnType(daTypeExtractor.forMethod(psiMethod, psiContext)).build();
                }

                private DAMethod.Builder daMethodBuilder(PsiMethod psiMethod) {
                    if (psiMethod.isConstructor()) {
                        return DAMethod.constructorBuilder();
                    }
                    return DAMethod.methodBuilder();
                }
            }).toImmutableList();
    if (!Iterables.any(daMethods, DAMethodConstructor.INSTANCE)) {
        return ImmutableList.copyOf(
                Iterables.concat(Collections.singletonList(instanceDefaultConstructor(psiClass)), daMethods));
    }
    return daMethods;
}

From source file:com.isotrol.impe3.core.modules.ModuleDefinition.java

/**
 * Return true if module required external deps.
 * @return true if module required external deps.
 *///from  ww  w.  ja va2 s . c  o  m
public final boolean hasRequiredExternalDependencies() {
    return Iterables.any(getExternalDependencies().values(), Dependency.IS_REQUIRED);
}

From source file:org.eclipse.sirius.diagram.business.api.query.DDiagramElementQuery.java

/**
 * Check if this {@link DDiagramElement} is directly collapsed.
 * //from  ww w.ja va  2s  .  c o  m
 * @return true if the given element is directly collapsed.
 */
public boolean isCollapsed() {
    return Iterables.any(element.getGraphicalFilters(),
            Predicates.and(Predicates.instanceOf(CollapseFilter.class),
                    Predicates.not(Predicates.instanceOf(IndirectlyCollapseFilter.class))));

}

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

@Override
public void validate(final Object obj, final Errors e) {
    final ItemSelectionAlgorithmParameter parameter = (ItemSelectionAlgorithmParameter) obj;

    if (parameter.getItemSelectionType() != null) {
        final Object[] errorArgs = new String[] { parameter.getItemSelectionType().name(),
                parameter.getParameterName() };

        switch (parameter.getItemSelectionType()) {
        case FLOAT:
        case INTEGER:
            // defaultValue validated via jsr-303
            rejectIfTooLong(e, DEFAULT_FIELD, MAX_PARSEABLE_LENGTH, errorArgs);

            final boolean isFloat = parameter.getItemSelectionType() == ItemSelectionType.FLOAT;
            rejectIfNotFloatOrIntegerParseable(e, DEFAULT_FIELD, isFloat, errorArgs);
            rejectIfNotFloatOrIntegerParseable(e, MINIMUM_FIELD, isFloat, errorArgs);
            rejectIfNotFloatOrIntegerParseable(e, MAXIMUM_FIELD, isFloat, errorArgs);
            if (!e.hasErrors()) {
                boolean compareDefaultToMinMax = true;
                if (StringUtils.isNotBlank(parameter.getMinimumValue())
                        && StringUtils.isNotBlank(parameter.getMaximumValue())) {
                    final BigDecimal minimumBigDecimal = new BigDecimal(parameter.getMinimumValue());
                    final BigDecimal maximumBigDecimal = new BigDecimal(parameter.getMaximumValue());
                    if (minimumBigDecimal.compareTo(maximumBigDecimal) > -1) {
                        rejectValue(e, MINIMUM_FIELD, getErrorMessageRoot() + MINIMUM_FIELD + MSG_LESS_THAN_MAX,
                                errorArgs);
                        compareDefaultToMinMax = false;
                    }/*from  ww  w.  j  av  a  2 s.c  o m*/
                }
                if (StringUtils.isNotBlank(parameter.getDefaultValue())) {
                    final BigDecimal defaultBigDecimal = new BigDecimal(parameter.getDefaultValue());
                    if (StringUtils.isNotBlank(parameter.getMinimumValue())) {
                        final BigDecimal minimumBigDecimal = new BigDecimal(parameter.getMinimumValue());
                        if (compareDefaultToMinMax && defaultBigDecimal.compareTo(minimumBigDecimal) < 0) {
                            rejectValue(e, DEFAULT_FIELD,
                                    getErrorMessageRoot() + DEFAULT_FIELD + MSG_WITHIN_MIN_MAX, errorArgs);
                        }
                    }
                    if (StringUtils.isNotBlank(parameter.getMaximumValue())) {
                        final BigDecimal maximumBigDecimal = new BigDecimal(parameter.getMaximumValue());
                        if (compareDefaultToMinMax && defaultBigDecimal.compareTo(maximumBigDecimal) > 0) {
                            rejectValue(e, DEFAULT_FIELD,
                                    getErrorMessageRoot() + DEFAULT_FIELD + MSG_WITHIN_MIN_MAX, errorArgs);
                        }
                    }
                }
            }
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            break;
        case BOOLEAN:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfNotBooleanParseable(e, DEFAULT_FIELD, errorArgs);
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            break;
        case LIST:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfCollectionEmpty(e, ITEM_LIST_FIELD, errorArgs);

            if (parameter.getItemSelectionList() != null) {
                if (Iterables.any(parameter.getItemSelectionList(), ITEM_SELECTION_PARAMETER_ELEMENT_BLANK)) {
                    rejectValue(e, ITEM_LIST_FIELD, getErrorMessageRoot() + ITEM_LIST_NAME_FIELD + MSG_REQUIRED,
                            errorArgs);
                }
                // check if defaultValue is one of values in selection list
                rejectIfNotInCollection(e, DEFAULT_FIELD, Lists.transform(parameter.getItemSelectionList(),
                        ITEM_SELECTION_PARAMETER_ELEMENT_TO_NAME_TRANSFORMER), errorArgs);

                // check if list has duplicate names and duplicate or out-of-range positions
                final Map<String, Collection<ItemSelectionParameterElement>> duplicates = Maps.filterEntries(
                        Multimaps.index(parameter.getItemSelectionList(),
                                ITEM_SELECTION_PARAMETER_ELEMENT_TO_NAME_TRANSFORMER).asMap(),
                        ITEM_SELECTION_PARAMETER_ELEMENT_DUPLICATE_FILTER);
                if (!duplicates.isEmpty()) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_NAME_FIELD + MSG_DUPLICATES,
                            duplicates.keySet().toString());
                }
                final Map<String, Collection<ItemSelectionParameterElement>> duplicatePositions = Maps
                        .filterEntries(
                                Multimaps
                                        .index(parameter.getItemSelectionList(),
                                                ITEM_SELECTION_PARAMETER_ELEMENT_TO_POSITION_TRANSFORMER)
                                        .asMap(),
                                ITEM_SELECTION_PARAMETER_ELEMENT_DUPLICATE_FILTER);
                if (!duplicatePositions.isEmpty()) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_POSITION_FIELD + MSG_DUPLICATES,
                            duplicatePositions.keySet().toString());
                }
                final List<String> outOfRange = Lists.newArrayList(Iterables.transform(
                        Iterables.filter(parameter.getItemSelectionList(),
                                PARAMETER_POSITION_OUT_OF_RANGE_FILTER
                                        .getInstance(parameter.getItemSelectionList().size())),
                        ITEM_SELECTION_PARAMETER_ELEMENT_TO_POSITION_TRANSFORMER));
                if (outOfRange.size() > 0) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_POSITION_FIELD + MSG_INVALID,
                            outOfRange.toString());
                }
            }
            break;
        case STRING:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            rejectIfTooLong(e, DEFAULT_FIELD, MAXIMUM_DEFAULT_STRING_LENGTH, errorArgs);
            break;
        default:
            rejectValue(e, ITEM_TYPE_FIELD, getErrorMessageRoot() + ITEM_TYPE_FIELD + MSG_INVALID, errorArgs);
            break;
        }
    }
}

From source file:org.eclipse.emf.compare.uml2.rcp.ui.internal.accessor.UMLStereotypeApplicationChangeFeatureAccessor.java

/**
 * When computing the insertion index of a stereotype in the list of applied stereotypes, we need to
 * ignore all stereotypes that feature unresolved Diffs.
 * //  w ww .  j  av  a 2 s . c  om
 * @param candidates
 *            The sequence in which we need to compute an insertion index.
 * @param diff
 *            The diff we are computing an insertion index for.
 * @param <E>
 *            Type of the list's content.
 * @return The list of elements that should be ignored when computing the insertion index for a new
 *         element in {@code candidates}.
 */
private static <E> Iterable<E> computeIgnoredElements(Iterable<E> candidates,
        final StereotypeApplicationChange diff) {
    return Iterables.filter(candidates, new Predicate<Object>() {
        public boolean apply(final Object element) {
            if (element instanceof EObject) {
                final Comparison comparison = diff.getMatch().getComparison();
                final Match match = comparison.getMatch((EObject) element);
                if (match != null) {
                    return Iterables.any(match.getDifferences(),
                            and(instanceOf(StereotypeApplicationChange.class),
                                    hasState(DifferenceState.UNRESOLVED)));
                }
            }
            return false;
        }
    });
}

From source file:nextmethod.web.razor.editor.internal.BackgroundThread.java

private void workerLoop() {
    final boolean isEditorTracing = Debug.isDebugArgPresent(DebugArgs.EditorTracing);
    final String fileNameOnly = Filesystem.getFileName(fileName);

    Stopwatch sw = null;/*from   ww  w .j a v  a2 s .  co m*/
    if (isEditorTracing) {
        sw = Stopwatch.createUnstarted();
    }

    try {
        RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadStart(fileNameOnly));
        ensureOnThread();
        while (!shutdownToken.isCancellationRequested()) {
            // Grab the parcel of work to do
            final WorkParcel parcel = main.getParcel();
            if (!parcel.getChanges().isEmpty()) {
                RazorEditorTrace.traceLine(RazorResources().traceChangesArrived(fileNameOnly,
                        String.valueOf(parcel.getChanges().size())));
                try {
                    DocumentParseCompleteEventArgs args = null;
                    try (CancellationTokenSource linkedCancel = CancellationTokenSource
                            .createLinkedTokenSource(shutdownToken, parcel.getCancelToken())) {
                        if (parcel != null && !linkedCancel.isCancellationRequested()) {
                            // Collect ALL changes
                            if (isEditorTracing && previouslyDiscarded != null
                                    && !previouslyDiscarded.isEmpty()) {
                                RazorEditorTrace.traceLine(RazorResources().traceCollectedDiscardedChanges(
                                        fileNameOnly, String.valueOf(parcel.getChanges().size())));
                            }
                            final Iterable<TextChange> allChanges = Iterables
                                    .concat(previouslyDiscarded != null ? previouslyDiscarded
                                            : Collections.<TextChange>emptyList(), parcel.getChanges());

                            final TextChange finalChange = Iterables.getLast(allChanges, null);
                            if (finalChange != null) {
                                if (isEditorTracing) {
                                    assert sw != null;
                                    sw.reset().start();
                                }

                                //noinspection ConstantConditions
                                final GeneratorResults results = parseChange(finalChange.getNewBuffer(),
                                        linkedCancel.getToken());

                                if (isEditorTracing) {
                                    assert sw != null;
                                    sw.stop();
                                }

                                RazorEditorTrace.traceLine(RazorResources().traceParseComplete(fileNameOnly,
                                        sw != null ? sw.toString() : "?"));

                                if (results != null && !linkedCancel.isCancellationRequested()) {
                                    // Clear discarded changes list
                                    previouslyDiscarded = Lists.newArrayList();
                                    // Take the current tree and check for differences
                                    if (isEditorTracing) {
                                        sw.reset().start();
                                    }
                                    final boolean treeStructureChanged = currentParseTree == null
                                            || BackgroundParser.treesAreDifferent(currentParseTree,
                                                    results.getDocument(), allChanges, parcel.getCancelToken());

                                    if (isEditorTracing) {
                                        sw.stop();
                                    }

                                    currentParseTree = results.getDocument();
                                    RazorEditorTrace.traceLine(RazorResources().traceTreesCompared(fileNameOnly,
                                            sw != null ? sw.toString() : "?",
                                            String.valueOf(treeStructureChanged)));

                                    // Build Arguments
                                    args = new DocumentParseCompleteEventArgs(treeStructureChanged, results,
                                            finalChange);
                                } else {
                                    // Parse completed but we were cancelled in the mean time. Add these to the discarded changes set
                                    RazorEditorTrace.traceLine(RazorResources().traceChangesDiscarded(
                                            fileNameOnly, String.valueOf(Iterables.size(allChanges))));
                                    previouslyDiscarded = Lists.newArrayList(allChanges);
                                }

                                if (Debug.isDebugArgPresent(DebugArgs.CheckTree) && args != null) {
                                    // Rewind the buffer and sanity check the line mappings
                                    finalChange.getNewBuffer().setPosition(0);
                                    final String buffer = TextExtensions.readToEnd(finalChange.getNewBuffer());
                                    final int lineCount = Iterables
                                            .size(Splitter.on(CharMatcher.anyOf("\r\n")).split(buffer));
                                    Debug.doAssert(!Iterables.any(
                                            args.getGeneratorResults().getDesignTimeLineMappingEntries(),
                                            input -> input != null
                                                    && input.getValue().getStartLine() > lineCount),
                                            "Found a design-time line mapping referring to a line outside the source file!");

                                    Debug.doAssert(
                                            !Iterables.any(args.getGeneratorResults().getDocument().flatten(),
                                                    input -> input != null
                                                            && input.getStart().getLineIndex() > lineCount),
                                            "Found a span with a line number outside the source file");
                                }
                            }
                        }
                    }
                    if (args != null) {
                        main.returnParcel(args);
                    }
                } catch (OperationCanceledException ignored) {

                }
            } else {
                RazorEditorTrace.traceLine(RazorResources().traceNoChangesArrived(fileName),
                        parcel.getChanges().size());
                Thread.yield();
            }
        }
    } catch (OperationCanceledException ignored) {
    } finally {
        RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadShutdown(fileNameOnly));
        // Clean up main thread resources
        main.close();
    }
}

From source file:com.android.tools.idea.avdmanager.ConfigureDeviceOptionsStep.java

/**
 * Initialize our state to match the device we've been given as a starting point
 *//*from  ww w .  ja v a2s  .  com*/
private void initFromDevice() {
    assert myTemplateDevice != null;
    if (myForceCreation) {
        String name = myTemplateDevice.getDisplayName() + " (Edited)";
        myState.put(DEVICE_NAME_KEY, getUniqueId(name));
    } else {
        myState.put(DEVICE_NAME_KEY, myTemplateDevice.getDisplayName());
    }

    String tagId = myTemplateDevice.getTagId();
    if (tagId != null) {
        for (IdDisplay tag : ALL_TAGS) {
            if (tag.getId().equals(tagId)) {
                myState.put(TAG_ID_KEY, tag);
                break;
            }
        }
    }

    for (Map.Entry<String, String> entry : myTemplateDevice.getBootProps().entrySet()) {
        myBuilder.addBootProp(entry.getKey(), entry.getValue());
    }

    Hardware defaultHardware = myTemplateDevice.getDefaultHardware();
    Screen screen = defaultHardware.getScreen();
    myState.put(DIAGONAL_SCREENSIZE_KEY, screen.getDiagonalLength());
    myState.put(RESOLUTION_WIDTH_KEY, screen.getXDimension());
    myState.put(RESOLUTION_HEIGHT_KEY, screen.getYDimension());
    myState.put(RAM_STORAGE_KEY, AvdWizardConstants.getDefaultRam(defaultHardware));

    myState.put(HAS_HARDWARE_BUTTONS_KEY, defaultHardware.getButtonType() == ButtonType.HARD);
    myState.put(HAS_HARDWARE_KEYBOARD_KEY, defaultHardware.getKeyboard() != Keyboard.NOKEY);
    myState.put(NAVIGATION_KEY, defaultHardware.getNav());

    final List<State> states = myTemplateDevice.getAllStates();
    myState.put(SUPPORTS_PORTRAIT_KEY, Iterables.any(states, new Predicate<State>() {
        @Override
        public boolean apply(State input) {
            return input.getOrientation().equals(ScreenOrientation.PORTRAIT);
        }
    }));
    myState.put(SUPPORTS_LANDSCAPE_KEY, Iterables.any(states, new Predicate<State>() {
        @Override
        public boolean apply(State input) {
            return input.getOrientation().equals(ScreenOrientation.LANDSCAPE);
        }
    }));

    myState.put(HAS_FRONT_CAMERA_KEY, defaultHardware.getCamera(CameraLocation.FRONT) != null);
    myState.put(HAS_BACK_CAMERA_KEY, defaultHardware.getCamera(CameraLocation.BACK) != null);

    myState.put(HAS_ACCELEROMETER_KEY, defaultHardware.getSensors().contains(Sensor.ACCELEROMETER));
    myState.put(HAS_GYROSCOPE_KEY, defaultHardware.getSensors().contains(Sensor.GYROSCOPE));
    myState.put(HAS_GPS_KEY, defaultHardware.getSensors().contains(Sensor.GPS));
    myState.put(HAS_PROXIMITY_SENSOR_KEY, defaultHardware.getSensors().contains(Sensor.PROXIMITY_SENSOR));
    File skinFile = AvdEditWizard.resolveSkinPath(defaultHardware.getSkinFile(), null);
    if (skinFile != null) {
        myState.put(CUSTOM_SKIN_FILE_KEY, skinFile);
    } else {
        myState.put(CUSTOM_SKIN_FILE_KEY, NO_SKIN);
    }
}

From source file:nextmethod.web.razor.parser.TokenizerBackedParser.java

@SafeVarargs
protected final boolean nextIs(@Nonnull final TSymbolType... types) {
    final List<TSymbolType> tSymbolTypes = Lists.newArrayList(types);
    return nextIs(input1 -> input1 != null
            && Iterables.any(tSymbolTypes, input -> input != null && input == input1.getType()));
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.util.RequestQuery.java

private boolean isSequenceMessageCreation(Predicate<Object> expectedMessageCreationToolMappingTypes) {
    boolean result = false;
    if (!isNoteAttachmentCreationRequest() && request instanceof CreateConnectionRequest) {
        CreateConnectionRequest createRequest = (CreateConnectionRequest) request;
        if (!(request instanceof CreateUnspecifiedTypeConnectionRequest)
                && createRequest.getNewObject() instanceof MessageCreationTool) {
            if (expectedMessageCreationToolMappingTypes != null) {
                MessageCreationTool messageCreationTool = (MessageCreationTool) createRequest.getNewObject();
                result = Iterables.any(messageCreationTool.getEdgeMappings(),
                        expectedMessageCreationToolMappingTypes);
            } else {
                result = true;/*from w  w  w .ja  v a  2  s  .com*/
            }
        }
    }
    return result;
}

From source file:com.twitter.common.thrift.callers.RetryingCaller.java

private boolean isRetryable(final Class<? extends Throwable> exceptionClass) {
    if (retryableExceptions.contains(exceptionClass)) {
        return true;
    }/* www . j  a  v  a2 s .  c om*/
    return Iterables.any(retryableExceptions, new Predicate<Class<? extends Exception>>() {
        @Override
        public boolean apply(Class<? extends Exception> retryableExceptionClass) {
            return retryableExceptionClass.isAssignableFrom(exceptionClass);
        }
    });
}