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

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

Introduction

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

Prototype

public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) 

Source Link

Document

Combines two iterators into a single iterator.

Usage

From source file:io.druid.sql.calcite.rel.DruidQuery.java

@Nullable
private static Grouping computeGrouping(final PartialDruidQuery partialQuery,
        final PlannerContext plannerContext, final RowSignature sourceRowSignature,
        final RexBuilder rexBuilder) {
    final Aggregate aggregate = partialQuery.getAggregate();
    final Project postProject = partialQuery.getPostProject();

    if (aggregate == null) {
        return null;
    }/*  w w w . j av a2  s. co m*/

    final List<DimensionExpression> dimensions = computeDimensions(partialQuery, plannerContext,
            sourceRowSignature);
    final List<Aggregation> aggregations = computeAggregations(partialQuery, plannerContext, sourceRowSignature,
            rexBuilder);

    final RowSignature aggregateRowSignature = RowSignature.from(
            ImmutableList.copyOf(
                    Iterators.concat(dimensions.stream().map(DimensionExpression::getOutputName).iterator(),
                            aggregations.stream().map(Aggregation::getOutputName).iterator())),
            aggregate.getRowType());

    final DimFilter havingFilter = computeHavingFilter(partialQuery, aggregateRowSignature, plannerContext);

    if (postProject == null) {
        return Grouping.create(dimensions, aggregations, havingFilter, aggregateRowSignature);
    } else {
        final List<String> rowOrder = new ArrayList<>();

        int outputNameCounter = 0;
        for (final RexNode postAggregatorRexNode : postProject.getChildExps()) {
            // Attempt to convert to PostAggregator.
            final DruidExpression postAggregatorExpression = Expressions.toDruidExpression(plannerContext,
                    aggregateRowSignature, postAggregatorRexNode);

            if (postAggregatorExpression == null) {
                throw new CannotBuildQueryException(postProject, postAggregatorRexNode);
            }

            if (postAggregatorDirectColumnIsOk(aggregateRowSignature, postAggregatorExpression,
                    postAggregatorRexNode)) {
                // Direct column access, without any type cast as far as Druid's runtime is concerned.
                // (There might be a SQL-level type cast that we don't care about)
                rowOrder.add(postAggregatorExpression.getDirectColumn());
            } else {
                final String postAggregatorName = "p" + outputNameCounter++;
                final PostAggregator postAggregator = new ExpressionPostAggregator(postAggregatorName,
                        postAggregatorExpression.getExpression(), null, plannerContext.getExprMacroTable());
                aggregations.add(Aggregation.create(postAggregator));
                rowOrder.add(postAggregator.getName());
            }
        }

        // Remove literal dimensions that did not appear in the projection. This is useful for queries
        // like "SELECT COUNT(*) FROM tbl GROUP BY 'dummy'" which some tools can generate, and for which we don't
        // actually want to include a dimension 'dummy'.
        final ImmutableBitSet postProjectBits = RelOptUtil.InputFinder.bits(postProject.getChildExps(), null);
        for (int i = dimensions.size() - 1; i >= 0; i--) {
            final DimensionExpression dimension = dimensions.get(i);
            if (Parser.parse(dimension.getDruidExpression().getExpression(), plannerContext.getExprMacroTable())
                    .isLiteral() && !postProjectBits.get(i)) {
                dimensions.remove(i);
            }
        }

        return Grouping.create(dimensions, aggregations, havingFilter,
                RowSignature.from(rowOrder, postProject.getRowType()));
    }
}

From source file:org.dswarm.graph.xml.read.PropertyGraphXMLReader.java

@Override
public Optional<XMLStreamWriter> read(final OutputStream outputStream)
        throws DMPGraphException, XMLStreamException {

    try {//from   w ww  .  ja  v a  2s  . c o  m

        final boolean createdNewTx = tx.ensureRunningTx();

        PropertyGraphXMLReader.LOG.debug("start read XML TX (createdNewTx = '{}')", createdNewTx);
    } catch (final Exception e) {

        final String message = "couldn't acquire tx successfully";

        PropertyGraphXMLReader.LOG.error(message, e);
        PropertyGraphXMLReader.LOG.debug("couldn't finish read XML TX successfully");

        throw new DMPGraphException(message);
    }

    ResourceIterator<Node> recordNodesIter = null;

    try {

        final String prefixedURI = namespaceIndex.createPrefixedURI(recordClassURIString);
        final Label recordClassLabel = DynamicLabel.label(prefixedURI);

        // TODO: refactor this to #findNodes + something else, then counting over the iterator
        recordNodesIter = database.findNodes(recordClassLabel, GraphStatics.DATA_MODEL_PROPERTY,
                prefixedDataModel);

        if (recordNodesIter == null) {

            tx.succeedTx();

            PropertyGraphXMLReader.LOG.debug(
                    "there are no root nodes for '{}' in data model '{}'finished read XML TX successfully",
                    recordClassLabel, dataModelUri);

            return Optional.absent();
        }

        if (!recordNodesIter.hasNext()) {

            recordNodesIter.close();
            tx.succeedTx();

            PropertyGraphXMLReader.LOG.debug(
                    "there are no root nodes for '{}' in data model '{}'finished read XML TX successfully",
                    recordClassLabel, dataModelUri);

            return Optional.absent();
        }

        final Node firstRecord = recordNodesIter.next();
        final Iterator<Node> nodeIterator = Iterators.concat(Iterators.forArray(firstRecord), recordNodesIter);
        final boolean hasAtLeasTwoRecords = recordNodesIter.hasNext();

        // (XMLStreamWriter2)
        final XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(outputStream);

        writer.writeStartDocument(Charsets.UTF_8.toString(), XML_VERSION);

        boolean defaultNamespaceWritten = false;

        if (optionalRootAttributePath.isPresent()) {

            // open root attribute path tags

            for (final Attribute attribute : optionalRootAttributePath.get().getAttributes()) {

                final URI attributeURI = new URI(attribute.getUri());

                if (!defaultNamespaceWritten && attributeURI.hasNamespaceURI()) {

                    // set default namespace

                    writer.setDefaultNamespace(attributeURI.getNamespaceURI());

                    defaultNamespaceWritten = true;
                }

                XMLStreamWriterUtils.writeXMLElementTag(writer, attributeURI, namespacesPrefixesMap, nameMap,
                        isElementOpen);
                isElementOpen = true;
            }
        } else if (hasAtLeasTwoRecords) {

            // write default root
            final URI defaultRootURI = new URI(recordTagURI + "s");

            determineAndWriteXMLElementAndNamespace(defaultRootURI, writer);
        }

        if (!defaultNamespaceWritten && recordTagURI.hasNamespaceURI()) {

            // set default namespace
            setDefaultNamespace(writer);
        }

        final XMLRelationshipHandler relationshipHandler;

        if (originalDataTypeIsXML) {

            relationshipHandler = new CBDRelationshipXMLDataModelHandler(writer);
        } else {

            relationshipHandler = new CBDRelationshipHandler(writer);
        }

        // note: relationship handler knows this node handler
        //noinspection unused
        final CBDNodeHandler connectRelsAndNodeHandler = new CBDNodeHandler(relationshipHandler);
        final XMLNodeHandler startNodeHandler = new CBDStartNodeHandler(relationshipHandler);

        // iterate over the records
        while (nodeIterator.hasNext()) {

            final Node recordNode = nodeIterator.next();
            final String resourceUri = (String) recordNode.getProperty(GraphStatics.URI_PROPERTY, null);

            if (resourceUri == null) {

                LOG.debug("there is no resource URI at record node '{}'", recordNode.getId());

                continue;
            }

            determineAndWriteXMLElementAndNamespace(recordTagURI, writer);

            startNodeHandler.handleNode(recordNode);
            // close record
            writer.writeEndElement();
            isElementOpen = false;

            recordCount++;
        }

        recordNodesIter.close();
        tx.succeedTx();

        PropertyGraphXMLReader.LOG.debug("finished read XML TX successfully");

        if (optionalRootAttributePath.isPresent()) {

            // close root attribute path tags

            for (int i = 0; i < optionalRootAttributePath.get().getAttributes().size(); i++) {

                writer.writeEndElement();
            }
        } else if (hasAtLeasTwoRecords) {

            // close default root
            writer.writeEndElement();
        }

        // close document
        writer.writeEndDocument();

        return Optional.of(writer);
    } catch (final Exception e) {

        PropertyGraphXMLReader.LOG.error("couldn't finished read XML TX successfully", e);

        if (recordNodesIter != null) {

            recordNodesIter.close();
        }

        tx.failTx();
    }

    return Optional.absent();
}

From source file:com.google.errorprone.refaster.Choice.java

/**
 * Returns a choice of the options from this {@code Choice} or from {@code other}.
 *///from  www .  j  a  v  a2 s  .  c om
public Choice<T> or(final Choice<T> other) {
    checkNotNull(other);
    if (other == none()) {
        return this;
    } else {
        final Choice<T> thisChoice = this;
        return new Choice<T>() {
            @Override
            protected Iterator<T> iterator() {
                return Iterators.concat(thisChoice.iterator(), other.iterator());
            }

            @Override
            public String toString() {
                return String.format("%s.or(%s)", thisChoice, other);
            }
        };
    }
}

From source file:org.richfaces.component.AbstractTree.java

protected Iterator<UIComponent> findMatchingTreeNodeComponent(String nodeType, UIComponent parentComponent) {
    Iterator<UIComponent> children = parentComponent.getChildren().iterator();
    if (parentComponent != this) {
        children = Iterators.concat(children, this.getChildren().iterator());
    }/* ww  w.j  a  v  a  2  s  .  c  o m*/

    return Iterators.filter(children, new MatchingTreeNodePredicate(nodeType));
}

From source file:org.pshdl.model.impl.AbstractHDLArgument.java

@Override
public Iterator<IHDLObject> deepIterator() {
    return new Iterator<IHDLObject>() {

        private int pos = 0;
        private Iterator<? extends IHDLObject> current;

        @Override//from  ww w.jav  a  2 s .c om
        public boolean hasNext() {
            if ((current != null) && !current.hasNext()) {
                current = null;
            }
            while (current == null) {
                switch (pos++) {
                case 0:
                    if (expression != null) {
                        current = Iterators.concat(Iterators.forArray(expression), expression.deepIterator());
                    }
                    break;
                default:
                    return false;
                }
            }
            return (current != null) && current.hasNext();
        }

        @Override
        public IHDLObject next() {
            return current.next();
        }

        @Override
        public void remove() {
            throw new IllegalArgumentException("Not supported");
        }

    };
}

From source file:org.eclipse.emf.compare.match.eobject.ProximityEObjectMatcher.java

/**
 * Process the list of objects matching them. This method might not be able to process all the EObjects if
 * - for instance, their container has not been matched already. Every object which could not be matched
 * is returned in the list.//  ww w.java 2  s .  com
 * 
 * @param comparison
 *            the comparison being built.
 * @param todoList
 *            the list of objects to process.
 * @param createUnmatches
 *            whether elements which have no match should trigger the creation of a Match object (meaning
 *            we won't try to match them afterwards) or not.
 * @param monitor
 *            a monitor to track progress.
 * @return the list of EObjects which could not be processed for some reason.
 */
private Iterable<EObject> matchList(Comparison comparison, Iterable<EObject> todoList, boolean createUnmatches,
        Monitor monitor) {
    Set<EObject> remainingResult = Sets.newLinkedHashSet();
    List<EObject> requiredContainers = Lists.newArrayList();
    Iterator<EObject> todo = todoList.iterator();
    while (todo.hasNext()) {
        if (monitor.isCanceled()) {
            throw new ComparisonCanceledException();
        }
        EObject next = todo.next();
        /*
         * Let's first add every container which is in scope
         */
        EObject container = next.eContainer();
        while (container != null && isInScope(container)) {
            if (comparison.getMatch(container) == null) {
                requiredContainers.add(0, container);
            }
            container = container.eContainer();
        }
    }
    Iterator<EObject> containersAndTodo = Iterators.concat(requiredContainers.iterator(), todoList.iterator());
    while (containersAndTodo.hasNext()) {
        if (monitor.isCanceled()) {
            throw new ComparisonCanceledException();
        }
        EObject next = containersAndTodo.next();
        /*
         * At this point you need to be sure the element has not been matched in any other way before.
         */
        if (comparison.getMatch(next) == null) {
            if (!tryToMatch(comparison, next, createUnmatches)) {
                remainingResult.add(next);
            }
        }
    }
    return remainingResult;
}

From source file:org.apache.jackrabbit.oak.query.UnionQueryImpl.java

@Override
public Iterator<ResultRowImpl> getRows() {
    prepare();/*from   w w  w . j a  v a  2  s  . c o  m*/
    if (explain) {
        String plan = getPlan();
        columns = new ColumnImpl[] { new ColumnImpl("explain", "plan", "plan") };
        ResultRowImpl r = new ResultRowImpl(this, Tree.EMPTY_ARRAY,
                new PropertyValue[] { PropertyValues.newString(plan) }, null, null);
        return Arrays.asList(r).iterator();
    }
    if (LOG.isDebugEnabled()) {
        if (isInternal) {
            LOG.trace("query union plan {}", getPlan());
        } else {
            LOG.debug("query union plan {}", getPlan());
        }
    }
    boolean distinct = !unionAll;
    Comparator<ResultRowImpl> orderBy = ResultRowImpl.getComparator(orderings);

    Iterator<ResultRowImpl> it;
    final Iterator<ResultRowImpl> leftRows = left.getRows();
    final Iterator<ResultRowImpl> rightRows = right.getRows();
    Iterator<ResultRowImpl> leftIter = leftRows;
    Iterator<ResultRowImpl> rightIter = rightRows;

    // if measure retrieve the backing delegate iterator instead
    if (measure) {
        leftIter = ((MeasuringIterator) leftRows).getDelegate();
        rightIter = ((MeasuringIterator) rightRows).getDelegate();
    }
    // Since sorted by index use a merge iterator
    if (isSortedByIndex()) {
        it = FilterIterators.newCombinedFilter(
                Iterators.mergeSorted(ImmutableList.of(leftIter, rightIter), orderBy), distinct, limit, offset,
                null, settings);
    } else {
        it = FilterIterators.newCombinedFilter(Iterators.concat(leftIter, rightIter), distinct, limit, offset,
                orderBy, settings);
    }

    if (measure) {
        // return the measuring iterator for the union
        it = new MeasuringIterator(this, it) {
            MeasuringIterator left = (MeasuringIterator) leftRows;
            MeasuringIterator right = (MeasuringIterator) rightRows;

            @Override
            protected void setColumns(ColumnImpl[] cols) {
                columns = cols;
                left.setColumns(cols);
                right.setColumns(cols);
            }

            @Override
            protected Map<String, Long> getSelectorScanCount() {
                // Merge the 2 maps from the left and right queries to get the selector counts
                Map<String, Long> leftSelectorScan = left.getSelectorScanCount();
                Map<String, Long> rightSelectorScan = right.getSelectorScanCount();
                Map<String, Long> unionScan = Maps.newHashMap(leftSelectorScan);
                for (String key : rightSelectorScan.keySet()) {
                    if (unionScan.containsKey(key)) {
                        unionScan.put(key, rightSelectorScan.get(key) + unionScan.get(key));
                    } else {
                        unionScan.put(key, rightSelectorScan.get(key));
                    }
                }
                return unionScan;
            }

            @Override
            protected long getReadCount() {
                return left.getReadCount() + right.getReadCount();
            }
        };
    }

    return it;
}

From source file:org.apache.druid.sql.calcite.rel.DruidQuery.java

@Nullable
private static Grouping computeGrouping(final PartialDruidQuery partialQuery,
        final PlannerContext plannerContext, final RowSignature sourceRowSignature, final RexBuilder rexBuilder,
        final boolean finalizeAggregations) {
    final Aggregate aggregate = partialQuery.getAggregate();
    final Project aggregateProject = partialQuery.getAggregateProject();

    if (aggregate == null) {
        return null;
    }/*from w ww .j  av  a2  s .co  m*/

    final List<DimensionExpression> dimensions = computeDimensions(partialQuery, plannerContext,
            sourceRowSignature);
    final List<Aggregation> aggregations = computeAggregations(partialQuery, plannerContext, sourceRowSignature,
            rexBuilder, finalizeAggregations);

    final RowSignature aggregateRowSignature = RowSignature.from(
            ImmutableList.copyOf(
                    Iterators.concat(dimensions.stream().map(DimensionExpression::getOutputName).iterator(),
                            aggregations.stream().map(Aggregation::getOutputName).iterator())),
            aggregate.getRowType());

    final DimFilter havingFilter = computeHavingFilter(partialQuery, aggregateRowSignature, plannerContext);

    if (aggregateProject == null) {
        return Grouping.create(dimensions, aggregations, havingFilter, aggregateRowSignature);
    } else {
        final ProjectRowOrderAndPostAggregations projectRowOrderAndPostAggregations = computePostAggregations(
                plannerContext, aggregateRowSignature, aggregateProject, "p");
        projectRowOrderAndPostAggregations.postAggregations
                .forEach(postAggregator -> aggregations.add(Aggregation.create(postAggregator)));

        // Remove literal dimensions that did not appear in the projection. This is useful for queries
        // like "SELECT COUNT(*) FROM tbl GROUP BY 'dummy'" which some tools can generate, and for which we don't
        // actually want to include a dimension 'dummy'.
        final ImmutableBitSet aggregateProjectBits = RelOptUtil.InputFinder
                .bits(aggregateProject.getChildExps(), null);
        for (int i = dimensions.size() - 1; i >= 0; i--) {
            final DimensionExpression dimension = dimensions.get(i);
            if (Parser.parse(dimension.getDruidExpression().getExpression(), plannerContext.getExprMacroTable())
                    .isLiteral() && !aggregateProjectBits.get(i)) {
                dimensions.remove(i);
            }
        }

        return Grouping.create(dimensions, aggregations, havingFilter,
                RowSignature.from(projectRowOrderAndPostAggregations.rowOrder, aggregateProject.getRowType()));
    }
}

From source file:org.richfaces.component.util.SelectUtils.java

/**
 * Gathers all select items from specified component's children
 *
 * @param context Faces context/*  w w w.  j a  v a2 s .c om*/
 * @param component UIComponent with UISelectItem or UISelectItems children
 * @return list of {@link SelectItem} taken from f:selectItem and f:selectItems
 */
public static Iterator<SelectItem> getSelectItems(FacesContext context, UIComponent component) {
    Iterator<UIComponent> children = component.getChildren().iterator();
    if (component instanceof SelectItemsInterface) {
        Iterator<UIComponent> self = Iterators.singletonIterator(component);
        children = Iterators.concat(self, children);
    }
    Iterator<SelectItem> iterator = new SelectItemsIterator(context, children);
    return iterator;
}

From source file:org.fcrepo.kernel.impl.FedoraResourceImpl.java

@Override
public void delete() {
    try {//from   ww  w  .  j a  v  a2  s. c o m
        final Iterator<Property> references = node.getReferences();
        final Iterator<Property> weakReferences = node.getWeakReferences();
        final Iterator<Property> inboundProperties = Iterators.concat(references, weakReferences);

        while (inboundProperties.hasNext()) {
            final Property prop = inboundProperties.next();
            final List<Value> newVals = new ArrayList<>();
            final Iterator<Value> propIt = property2values.apply(prop);
            while (propIt.hasNext()) {
                final Value v = propIt.next();
                if (!node.equals(getSession().getNodeByIdentifier(v.getString()))) {
                    newVals.add(v);
                    LOGGER.trace("Keeping multivalue reference property when deleting node");
                }
            }
            if (newVals.size() == 0) {
                prop.remove();
            } else {
                prop.setValue(newVals.toArray(new Value[newVals.size()]));
            }
        }

        final Node parent;

        if (getNode().getDepth() > 0) {
            parent = getNode().getParent();
        } else {
            parent = null;
        }
        final String name = getNode().getName();

        node.remove();

        if (parent != null) {
            createTombstone(parent, name);
        }

    } catch (final RepositoryException e) {
        throw new RepositoryRuntimeException(e);
    }
}