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

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

Introduction

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

Prototype

public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) 

Source Link

Document

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

Usage

From source file:org.netxilia.functions.LookupFunctions.java

/**
 * /*w  w  w  .j a  va 2s  . c  om*/
 * @param area
 * @param sheet
 * @param search
 * @param type
 * @return
 */
private CellData find(AreaReference area, ISheet sheet, IGenericValue search, int type) {
    // TODO use a binary search for sorted area
    PreviousValuePredicate<CellReference> predicate = getPredicate(sheet, search, type);
    try {
        SheetDimensions dim = sheet.getDimensions().getNonBlocking();
        CellReference cellRef = Iterators.find(area.iterator(dim.getRowCount(), dim.getColumnCount()),
                predicate);
        if (predicate.getPreviousValue() != null) {
            cellRef = predicate.getPreviousValue();
        }
        return sheet.receiveCell(cellRef).getNonBlocking();
    } catch (NoSuchElementException ex) {
        return null;
    } catch (NetxiliaResourceException e) {
        return null;
    } catch (NetxiliaBusinessException e) {
        return null;
    }

    // for (ICell cell : CollectionUtils.iterable(sheet.iterator(area))) {
    // if (cell != null && predicate.apply(cell.getValue()))
    // return cell;
    // }
    // return null;
}

From source file:org.apache.flink.cep.nfa.compiler.NFACompiler.java

/**
 * Used for migrating CEP graphs prior to 1.3. It removes the dummy start, adds the dummy end, and translates all
 * states to consuming ones by moving all TAKEs and IGNOREs to the next state. This method assumes each state
 * has at most one TAKE and one IGNORE and name of each state is unique. No PROCEED transition is allowed!
 *
 * @param oldStartState dummy start state of old graph
 * @param <T>           type of events
 * @return map of new states, where key is the name of a state and value is the state itself
 *///from  w ww.  j av  a2  s . co  m
@Internal
public static <T> Map<String, State<T>> migrateGraph(State<T> oldStartState) {
    State<T> oldFirst = oldStartState;
    State<T> oldSecond = oldStartState.getStateTransitions().iterator().next().getTargetState();

    StateTransition<T> oldFirstToSecondTake = Iterators.find(oldFirst.getStateTransitions().iterator(),
            new Predicate<StateTransition<T>>() {
                @Override
                public boolean apply(@Nullable StateTransition<T> input) {
                    return input != null && input.getAction() == StateTransitionAction.TAKE;
                }

            });

    StateTransition<T> oldFirstIgnore = Iterators.find(oldFirst.getStateTransitions().iterator(),
            new Predicate<StateTransition<T>>() {
                @Override
                public boolean apply(@Nullable StateTransition<T> input) {
                    return input != null && input.getAction() == StateTransitionAction.IGNORE;
                }

            }, null);

    StateTransition<T> oldSecondToThirdTake = Iterators.find(oldSecond.getStateTransitions().iterator(),
            new Predicate<StateTransition<T>>() {
                @Override
                public boolean apply(@Nullable StateTransition<T> input) {
                    return input != null && input.getAction() == StateTransitionAction.TAKE;
                }

            }, null);

    final Map<String, State<T>> convertedStates = new HashMap<>();
    State<T> newSecond;
    State<T> newFirst = new State<>(oldSecond.getName(), State.StateType.Start);
    convertedStates.put(newFirst.getName(), newFirst);
    while (oldSecondToThirdTake != null) {

        newSecond = new State<T>(oldSecondToThirdTake.getTargetState().getName(), State.StateType.Normal);
        convertedStates.put(newSecond.getName(), newSecond);
        newFirst.addTake(newSecond, oldFirstToSecondTake.getCondition());

        if (oldFirstIgnore != null) {
            newFirst.addIgnore(oldFirstIgnore.getCondition());
        }

        oldFirst = oldSecond;

        oldFirstToSecondTake = Iterators.find(oldFirst.getStateTransitions().iterator(),
                new Predicate<StateTransition<T>>() {
                    @Override
                    public boolean apply(@Nullable StateTransition<T> input) {
                        return input != null && input.getAction() == StateTransitionAction.TAKE;
                    }

                });

        oldFirstIgnore = Iterators.find(oldFirst.getStateTransitions().iterator(),
                new Predicate<StateTransition<T>>() {
                    @Override
                    public boolean apply(@Nullable StateTransition<T> input) {
                        return input != null && input.getAction() == StateTransitionAction.IGNORE;
                    }

                }, null);

        oldSecond = oldSecondToThirdTake.getTargetState();

        oldSecondToThirdTake = Iterators.find(oldSecond.getStateTransitions().iterator(),
                new Predicate<StateTransition<T>>() {
                    @Override
                    public boolean apply(@Nullable StateTransition<T> input) {
                        return input != null && input.getAction() == StateTransitionAction.TAKE;
                    }

                }, null);

        newFirst = newSecond;
    }

    final State<T> endingState = new State<>(ENDING_STATE_NAME, State.StateType.Final);

    newFirst.addTake(endingState, oldFirstToSecondTake.getCondition());

    if (oldFirstIgnore != null) {
        newFirst.addIgnore(oldFirstIgnore.getCondition());
    }

    convertedStates.put(endingState.getName(), endingState);

    return convertedStates;
}

From source file:com.netxforge.netxstudio.data.index.BruteForceComponentLocator.java

@SuppressWarnings("unused")
private Component matchIdentifiersAdvanced(List<IComponentLocator.IdentifierDescriptor> identifiers,
        IComponentLocator.IdentifierDescriptor nodeIdentifier, List<Component> allComponentsMatchingMetrics) {

    // Identifiers which have matched, The Node Identifier = 1.
    final List<IComponentLocator.IdentifierDescriptor> localSuccessFullIdentifiers = Lists.newArrayList();
    localSuccessFullIdentifiers.add(nodeIdentifier);

    // All identifiers are valid (Excluding the Node identifier).
    boolean allIdentifiersValid = true;

    // At least one identifier has been verified.
    boolean atLeastOneIdentifierChecked = false;

    final List<Component> localSucssFullComponents = Lists.newArrayList();

    for (final IComponentLocator.IdentifierDescriptor idDescriptor : identifiers) {
        atLeastOneIdentifierChecked = true;

        if (idDescriptor.getKind().getObjectKind() == ObjectKindType.NODE) {
            // If no other identifiers, this should still work.
            continue; // skip node descriptor
        } else if (idDescriptor.getKind().getObjectKind() == ObjectKindType.RELATIONSHIP) {
            // TODO, predicate for relationships.
            continue;
        } else {/* w w  w  . j  ava 2 s .  c o m*/
            // match a component Identifier.
            Component c = Iterators.find(allComponentsMatchingMetrics.iterator(),
                    new MatchComponentPredicate(idDescriptor));
            if (c != null) {
                if (!localSucssFullComponents.contains(c)) {
                    localSucssFullComponents.add(c);
                }
                localSuccessFullIdentifiers.add(idDescriptor);
                if (DataActivator.DEBUG) {
                    DataActivator.TRACE.trace(DataActivator.TRACE_IMPORT_LOCATOR_OPTION,
                            "-- matching succeeded:" + idDescriptor.getIdentifier() + " , for component name="
                                    + c.getName());
                }
            } else {
                allIdentifiersValid = false;
                if (DataActivator.DEBUG) {
                    DataActivator.TRACE.trace(DataActivator.TRACE_IMPORT_LOCATOR_OPTION,
                            "-- matching failed:" + idDescriptor.getIdentifier());
                }
            }
        }
    }

    // update the global state.
    if (localSuccessFullIdentifiers.size() > successFullIdentifiers.size()) {
        successFullIdentifiers = localSuccessFullIdentifiers;
        successFullComponents = localSucssFullComponents;
    }

    Component result = null;

    // We checked at least one, and all are actually valid so get the first
    // matching entry. (There could be more).
    if (atLeastOneIdentifierChecked && allIdentifiersValid) {
        if (localSucssFullComponents.size() > 0) {
            result = localSucssFullComponents.get(0);
        }
        if (DataActivator.DEBUG) {
            DataActivator.TRACE.trace(DataActivator.TRACE_IMPORT_LOCATOR_OPTION,
                    "-- decision, all identifiers are valid from a set of " + localSucssFullComponents.size());
            if (result != null) {
                DataActivator.TRACE.trace(DataActivator.TRACE_IMPORT_LOCATOR_OPTION,
                        "-- result component name=" + result.getName());
            }
        }
    }

    return result;
}

From source file:com.htmlhifive.pitalium.core.rules.AssertionView.java

/**
 * Actual?ScreenshotResult????//from  w  w  w . j  a v a  2 s .c o  m
 * 
 * @param screenshotId ID
 * @param expectedId ?ID
 * @param currents ??
 * @param expects ?
 * @param validateResult ??
 * @return ????{@link ScreenshotResult}
 */
private ScreenshotResult compareTargetResults(String screenshotId, String expectedId,
        List<TargetResult> currents, List<TargetResult> expects, ValidateResult validateResult) {
    boolean assertFail = !validateResult.isValid();

    List<TargetResult> processes = new ArrayList<TargetResult>(currents.size());
    for (final TargetResult current : currents) {
        // Target element's area was nothing
        IndexDomSelector selector = current.getTarget().getSelector();
        if (selector != null && validateResult.noAreaElementSelectors.contains(selector)) {
            processes.add(new TargetResult(ExecResult.FAILURE, current.getTarget(), current.getExcludes(),
                    current.isMoveTarget(), current.getHiddenElementSelectors()));
            LOG.debug("[Comparison skipped] ({})", current.getTarget());
            continue;
        }

        TargetResult expected;
        try {
            expected = Iterators.find(expects.iterator(), new Predicate<TargetResult>() {
                @Override
                public boolean apply(TargetResult input) {
                    return current.getTarget().areaEquals(input.getTarget());
                }
            });
        } catch (NoSuchElementException e) {
            LOG.error("[Comparison failed] No element found for target ({}).", current.getTarget());
            processes.add(new TargetResult(null, current.getTarget(), current.getExcludes(),
                    current.isMoveTarget(), current.getHiddenElementSelectors()));
            assertFail = true;

            continue;
        }

        // ?
        LOG.debug("[Comparison start] ({})", current);
        ImageRectanglePair currentImage = prepareScreenshotImageForCompare(current);
        ImageRectanglePair expectedImage = prepareScreenshotImageForCompare(expected);
        DiffPoints compareResult = ImageUtils.compare(currentImage.image, currentImage.rectangle,
                expectedImage.image, expectedImage.rectangle, current.getOptions());
        assertFail |= compareResult.isFailed();
        if (compareResult.isFailed()) {
            LOG.error("[Comparison failed] ({})", current);
        } else {
            LOG.debug("[Comparison success] ({})", current);
        }

        processes.add(new TargetResult(compareResult.isSucceeded() ? ExecResult.SUCCESS : ExecResult.FAILURE,
                current.getTarget(), current.getExcludes(), current.isMoveTarget(),
                current.getHiddenElementSelectors()));

        // ?Fail????????
        if (compareResult.isFailed()) {
            LOG.debug("[Create diff image] ({})", current);
            BufferedImage diffImage = ImageUtils.getDiffImage(expectedImage.image, currentImage.image,
                    compareResult);

            // Metadata????
            ScreenAreaResult target = current.getTarget();
            PersistMetadata metadata;
            if (target.getSelector() == null) {
                metadata = new PersistMetadata(currentId, className, methodName, screenshotId, null,
                        target.getRectangle(), capabilities);
            } else {
                metadata = new PersistMetadata(currentId, className, methodName, screenshotId,
                        target.getSelector(), null, capabilities);
            }
            TestResultManager.getInstance().getPersister().saveDiffImage(metadata, diffImage);
        }
    }

    for (DomSelector selector : validateResult.noElementSelectors) {
        processes.add(new TargetResult(null, new ScreenAreaResult(null, null, new ScreenArea(selector)), null,
                null, null));
    }

    return new ScreenshotResult(screenshotId, assertFail ? ExecResult.FAILURE : ExecResult.SUCCESS, expectedId,
            processes, className, methodName, capabilities.asMap(), null);
}