org.apache.tinkerpop.gremlin.process.traversal.Traverser Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.Traverser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SqlgLocalStepBarrier.java    From sqlg with MIT License 6 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() throws NoSuchElementException {
    if (this.first) {
        this.first = false;
        while (this.starts.hasNext()) {
            this.localTraversal.addStart(this.starts.next());
        }
        while (this.localTraversal.hasNext()) {
            this.results.add(this.localTraversal.nextTraverser());
        }
        this.results.sort((o1, o2) -> {
            SqlgTraverser x = (SqlgTraverser) o1;
            SqlgTraverser y = (SqlgTraverser) o2;
            return Long.compare(x.getStartElementIndex(), y.getStartElementIndex());
        });
        this.resultIterator = this.results.iterator();
    }
    if (this.resultIterator.hasNext()) {
        return this.resultIterator.next();
    } else {
        throw FastNoSuchElementException.instance();
    }
}
 
Example #2
Source File: TraversalSerializersV2d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traverser deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    long bulk = 1;
    Object v = null;

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals(GraphSONTokens.BULK)) {
            jsonParser.nextToken();
            bulk = deserializationContext.readValue(jsonParser, Long.class);
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.VALUE)) {
            jsonParser.nextToken();
            v = deserializationContext.readValue(jsonParser, Object.class);
        }
    }

    return new DefaultRemoteTraverser<>(v, bulk);
}
 
Example #3
Source File: GroupStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<K, V> projectTraverser(final Traverser.Admin<S> traverser) {
    final Map<K, V> map = new HashMap<>(1);
    this.valueTraversal.reset();
    this.valueTraversal.addStart(traverser);

    // reset the barrierStep as there are now ProfileStep instances present and the timers won't start right
    // without specific configuration through wrapping both the Barrier and ProfileStep in ProfiledBarrier
    if (resetBarrierForProfiling) {
        barrierStep = determineBarrierStep(valueTraversal);

        // the barrier only needs to be reset once
        resetBarrierForProfiling = false;
    }

    if (null == this.barrierStep) {
        if (this.valueTraversal.hasNext())
            map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.valueTraversal.next());
    } else if (this.barrierStep.hasNextBarrier())
        map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.barrierStep.nextBarrier());
    return map;
}
 
Example #4
Source File: Scoping.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the object with the specified key for the current traverser and throws an exception if the key cannot
 * be found.
 *
 * @throws KeyNotFoundException if the key does not exist
 */
public default <S> S getScopeValue(final Pop pop, final Object key, final Traverser.Admin<?> traverser) throws KeyNotFoundException {
    final Object object = traverser.get();
    if (object instanceof Map && ((Map) object).containsKey(key))
        return (S) ((Map) object).get(key);

    if (key instanceof String) {
        final String k = (String) key;
        if (traverser.getSideEffects().exists(k))
            return traverser.getSideEffects().get(k);

        final Path path = traverser.path();
        if (path.hasLabel(k))
            return null == pop ? path.get(k) : path.get(pop, k);
    }

    throw new KeyNotFoundException(key, this);
}
 
Example #5
Source File: MathStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Double map(final Traverser.Admin<S> traverser) {
    final Expression localExpression = new Expression(this.expression.getExpression());
    for (final String var : this.expression.getVariables()) {
        final Object o = var.equals(CURRENT) ?
                TraversalUtil.applyNullable(traverser, this.traversalRing.next()) :
                TraversalUtil.applyNullable((S) this.getNullableScopeValue(Pop.last, var, traverser), this.traversalRing.next());

        // it's possible for ElementValueTraversal to return null or something that is possibly not a Number.
        // worth a check to try to return a nice error message. The TraversalRing<S, Number> is a bit optimistic
        // given type erasure. It could easily end up otherwise.
        if (!(o instanceof Number))
            throw new IllegalStateException(String.format(
                    "The variable %s for math() step must resolve to a Number - it is instead of type %s with value %s",
                    var, Objects.isNull(o) ? "null" : o.getClass().getName(), o));

        localExpression.setVariable(var, ((Number) o).doubleValue());
    }
    this.traversalRing.reset();
    return localExpression.evaluate();
}
 
Example #6
Source File: GraphStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() {
    while (true) {
        if (this.iterator.hasNext()) {
            return this.isStart ? this.getTraversal().getTraverserGenerator().generate(this.iterator.next(), (Step) this, 1l) : this.head.split(this.iterator.next(), this);
        } else {
            if (this.isStart) {
                if (this.done)
                    throw FastNoSuchElementException.instance();
                else {
                    this.done = true;
                    this.iterator = null == this.iteratorSupplier ? EmptyIterator.instance() : this.iteratorSupplier.get();
                }
            } else {
                this.head = this.starts.next();
                this.iterator = null == this.iteratorSupplier ? EmptyIterator.instance() : this.iteratorSupplier.get();
            }
        }
    }
}
 
Example #7
Source File: SqlgAbstractStep.java    From sqlg with MIT License 6 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    if (null != this.nextEnd) {
        try {
            return this.prepareTraversalForNextStep(this.nextEnd);
        } finally {
            this.nextEnd = null;
        }
    } else {
        while (true) {
            if (Thread.interrupted()) throw new TraversalInterruptedException();
            final Traverser.Admin<E> traverser = this.processNextStart();
            if (null != traverser.get() && 0 != traverser.bulk())
                return this.prepareTraversalForNextStep(traverser);
        }
    }
}
 
Example #8
Source File: SqlgTraverser.java    From sqlg with MIT License 6 votes vote down vote up
@Override
public void merge(final Traverser.Admin<?> other) {
    if (this.requiresOneBulk) {
        //O_Traverser
        if (!other.getTags().isEmpty()) {
            if (this.tags == null) this.tags = new HashSet<>();
            this.tags.addAll(other.getTags());
        }

        //skip the B_O_Traverser
        //B_O_Traverser
        //this.bulk = this.bulk + other.bulk();

        //B_O_S_SE_SL_Traverser
        if (null != this.sack && null != this.sideEffects.getSackMerger())
            this.sack = this.sideEffects.getSackMerger().apply(this.sack, other.sack());
    } else {
        super.merge(other);
    }

}
 
Example #9
Source File: IndexedTraverserSetTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemove() {
    final IndexedTraverserSet<String, String> ts = makeTraverserSet();

    final List<Traverser.Admin<String>> testTraversers = new ArrayList<>(ts.get("test"));
    assertEquals(1, testTraversers.size());
    assertEquals(10, testTraversers.get(0).bulk());

    ts.remove();

    assertThat(ts.get("test"), nullValue());

    final List<Traverser.Admin<String>> nopeTraversers = new ArrayList<>(ts.get("nope"));
    assertEquals(1, nopeTraversers.size());
    assertEquals(1, nopeTraversers.get(0).bulk());
}
 
Example #10
Source File: GroupSideEffectStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void sideEffect(final Traverser.Admin<S> traverser) {
    final Map<K, V> map = new HashMap<>(1);
    this.valueTraversal.reset();
    this.valueTraversal.addStart(traverser);

    // reset the barrierStep as there are now ProfileStep instances present and the timers won't start right
    // without specific configuration through wrapping both the Barrier and ProfileStep in ProfiledBarrier
    if (resetBarrierForProfiling) {
        barrierStep = determineBarrierStep(valueTraversal);

        // the barrier only needs to be reset once
        resetBarrierForProfiling = false;
    }

    if (null == this.barrierStep) {
        if (this.valueTraversal.hasNext())
            map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.valueTraversal.next());
    } else if (this.barrierStep.hasNextBarrier())
        map.put(TraversalUtil.applyNullable(traverser, this.keyTraversal), (V) this.barrierStep.nextBarrier());
    if (!map.isEmpty())
        this.getTraversal().getSideEffects().add(this.sideEffectKey, map);
}
 
Example #11
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Choose the right traversal option to apply and seed those options with this traverser.
 */
private void applyCurrentTraverser(final Traverser.Admin<S> start) {
    // first get the value of the choice based on the current traverser and use that to select the right traversal
    // option to which that traverser should be routed
    final Object choice = TraversalUtil.apply(start, this.branchTraversal);
    final List<Traversal.Admin<S, E>> branches = pickBranches(choice);

    // if a branch is identified, then split the traverser and add it to the start of the option so that when
    // that option is iterated (in the calling method) that value can be applied.
    if (null != branches)
        branches.forEach(traversal -> traversal.addStart(start.split()));

    if (choice != Pick.any) {
        final List<Traversal.Admin<S, E>> anyBranch = this.traversalPickOptions.get(Pick.any);
        if (null != anyBranch)
            anyBranch.forEach(traversal -> traversal.addStart(start.split()));
    }
}
 
Example #12
Source File: TraversalUtil.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static final <S, E> boolean test(final Traverser.Admin<S> traverser, final Traversal.Admin<S, E> traversal, E end) {
    if (null == end) return TraversalUtil.test(traverser, traversal);

    final Traverser.Admin<S> split = traverser.split();
    split.setSideEffects(traversal.getSideEffects());
    split.setBulk(1l);
    traversal.reset();
    traversal.addStart(split);
    final Step<?, E> endStep = traversal.getEndStep();
    boolean result = false;
    while (traversal.hasNext()) {
        if (endStep.next().get().equals(end)) {
            result = true;
            break;
        }
    }

    // The traversal might not have been fully consumed in the loop above. Close the traversal to release any underlying
    // resources.
    CloseableIterator.closeIterator(traversal);

    return result;
}
 
Example #13
Source File: AbstractStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    if (EmptyTraverser.instance() != this.nextEnd) {
        try {
            return this.prepareTraversalForNextStep(this.nextEnd);
        } finally {
            this.nextEnd = EmptyTraverser.instance();
        }
    } else {
        while (true) {
            if (Thread.interrupted()) throw new TraversalInterruptedException();
            final Traverser.Admin<E> traverser = this.processNextStart();
            if (traverser.bulk() > 0)
                return this.prepareTraversalForNextStep(traverser);
        }
    }
}
 
Example #14
Source File: SqlgTraversalUtil.java    From sqlg with MIT License 5 votes vote down vote up
public static <S, E> boolean test(final Traverser.Admin<S> traverser, final Traversal.Admin<S, E> traversal) {
    final Traverser.Admin<S> split = traverser.split();
    split.setSideEffects(traversal.getSideEffects());
    split.setBulk(1l);
    traversal.addStart(split);
    return traversal.hasNext(); // filter
}
 
Example #15
Source File: FlatMapStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() {
    while (true) {
        if (this.iterator.hasNext()) {
            return this.head.split(this.iterator.next(), this);
        } else {
            closeIterator();
            this.head = this.starts.next();
            this.iterator = this.flatMap(this.head);
        }
    }
}
 
Example #16
Source File: ComputerResultStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<S> processNextStart() throws NoSuchElementException {
    while (true) {
        if (this.currentIterator.hasNext())
            return this.currentIterator.next();
        else {
            final ComputerResult result = this.starts.next().get();
            this.currentIterator = attach(result.memory().exists(TraversalVertexProgram.HALTED_TRAVERSERS)
                    ? result.memory().<TraverserSet<S>>get(TraversalVertexProgram.HALTED_TRAVERSERS).iterator()
                    : EmptyIterator.instance(), result.graph());
        }
    }
}
 
Example #17
Source File: B_O_S_SE_SL_Traverser.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void merge(final Traverser.Admin<?> other) {
    super.merge(other);
    if (null != this.sack && null != this.sideEffects.getSackMerger())
        this.sack = this.sideEffects.getSackMerger().apply(this.sack, other.sack());

}
 
Example #18
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Iterator<Traverser.Admin<E>> standardAlgorithm() {
    while (true) {
        if (!this.first) {
            // this block is ignored on the first pass through the while(true) giving the opportunity for
            // the traversalOptions to be prepared. Iterate all of them and simply return the ones that yield
            // results. applyCurrentTraverser() will have only injected the current traverser into the options
            // that met the choice requirements.  Note that in addGlobalChildOption an IdentityStep was added to
            // be a holder for that current traverser. That allows us to check that first step for an injected
            // traverser as part of the condition for using that traversal option in the output. This is necessary
            // because barriers like fold(), max(), etc. will always return true for hasNext() even if a traverser
            // was not seeded in applyCurrentTraverser().
            for (final Traversal.Admin<S, E> option : getGlobalChildren()) {
                if (option.getStartStep().hasNext() && option.hasNext())
                    return option.getEndStep();
            }
        }

        this.first = false;

        // pass the current traverser to applyCurrentTraverser() which will make the "choice" of traversal to
        // apply with the given traverser. as this is in a while(true) this phase essentially prepares the options
        // for execution above
        if (this.hasBarrier) {
            if (!this.starts.hasNext())
                throw FastNoSuchElementException.instance();
            while (this.starts.hasNext()) {
                this.applyCurrentTraverser(this.starts.next());
            }
        } else {
            this.applyCurrentTraverser(this.starts.next());
        }
    }
}
 
Example #19
Source File: MaxLocalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected E map(final Traverser.Admin<S> traverser) {
    final Iterator<E> iterator = traverser.get().iterator();
    if (iterator.hasNext()) {
        Comparable result = iterator.next();
        while (iterator.hasNext()) {
            result = max(iterator.next(), result);
        }
        return (E) result;
    }
    throw FastNoSuchElementException.instance();
}
 
Example #20
Source File: PathStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Path map(final Traverser.Admin<S> traverser) {
    final Path path = traverser.path().subPath(this.fromLabel, this.toLabel);
    if (this.traversalRing.isEmpty())
        return path;
    else {
        this.traversalRing.reset();
        final Path byPath = MutablePath.make();
        path.forEach((object, labels) -> byPath.extend(TraversalUtil.applyNullable(object, this.traversalRing.next()), labels));
        return byPath;
    }
}
 
Example #21
Source File: AggregateGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<S> processNextStart() {
    if (this.barrier.isEmpty()) {
        this.processAllStarts();
    }
    return this.barrier.remove();
}
 
Example #22
Source File: MatchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<Object> processNextStart() throws NoSuchElementException {
    if (null == this.parent)
        this.parent = (MatchStep<?, ?>) this.getTraversal().getParent();

    final Traverser.Admin<Object> traverser = this.starts.next();
    this.parent.getMatchAlgorithm().recordStart(traverser, this.getTraversal());
    // TODO: sideEffect check?
    return null == this.selectKey ? traverser : traverser.split(traverser.path().get(Pop.last, this.selectKey), this);
}
 
Example #23
Source File: Scoping.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link #getScopeValue(Pop, Object, Traverser.Admin)} and returns {@code null} if the key is not found.
 * Use this method with caution as {@code null} has one of two meanings as a return value. It could be that the
 * key was found and its value was {@code null} or it might mean that the key was not found and {@code null} was
 * simply returned.
 */
public default <S> S getNullableScopeValue(final Pop pop, final String key, final Traverser.Admin<?> traverser) {
    try {
        return getScopeValue(pop, key, traverser);
    } catch (KeyNotFoundException nfe) {
        return null;
    }
}
 
Example #24
Source File: PartitionStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<Property>> apply(final Traverser<Map<String, List<Property>>> mapTraverser) {
    final Map<String, List<Property>> values = mapTraverser.get();
    final Map<String, List<Property>> converted = new HashMap<>();

    values.entrySet().forEach(p -> {
        final List l = p.getValue().stream().map(property -> property.value()).collect(Collectors.toList());
        converted.put(p.getKey(), l);
    });

    return converted;
}
 
Example #25
Source File: PathFilterStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    final Path path = traverser.path().subPath(this.fromLabel, this.toLabel);
    if (this.traversalRing.isEmpty())
        return path.isSimple() == this.isSimple;
    else {
        this.traversalRing.reset();
        final Path byPath = MutablePath.make();
        path.forEach((object, labels) -> byPath.extend(TraversalUtil.applyNullable(object, this.traversalRing.next()), labels));
        return byPath.isSimple() == this.isSimple;
    }
}
 
Example #26
Source File: SelectOneStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<E> processNextStart() throws NoSuchElementException {
    final Traverser.Admin<S> traverser = this.starts.next();

    try {
        final S o = getScopeValue(pop, selectKey, traverser);
        if (null == o) return traverser.split(null, this);
        final Traverser.Admin<E> outTraverser = traverser.split(TraversalUtil.applyNullable(o, this.selectTraversal), this);
        if (!(this.getTraversal().getParent() instanceof MatchStep))
            PathProcessor.processTraverserPathLabels(outTraverser, this.keepLabels);
        return outTraverser;
    } catch (KeyNotFoundException nfe) {
        return EmptyTraverser.instance();
    }
}
 
Example #27
Source File: EdgeOtherVertexStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Vertex map(final Traverser.Admin<Edge> traverser) {
    final List<Object> objects = traverser.path().objects();
    for (int i = objects.size() - 2; i >= 0; i--) {
        if (objects.get(i) instanceof Vertex) {
            return ElementHelper.areEqual((Vertex) objects.get(i), traverser.get().outVertex()) ?
                    traverser.get().inVertex() :
                    traverser.get().outVertex();
        }
    }
    throw new IllegalStateException("The path history of the traverser does not contain a previous vertex: " + traverser.path());
}
 
Example #28
Source File: TraverserSet.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public long bulkSize() {
    long bulk = 0L;
    for (final Traverser.Admin<S> traverser : this.map.values()) {
        bulk = bulk + traverser.bulk();
    }
    return bulk;
}
 
Example #29
Source File: SqlgExpandableStepIterator.java    From sqlg with MIT License 5 votes vote down vote up
@Override
public Traverser.Admin<S> next() {
    if (!this.traversers.isEmpty())
        return this.traversers.poll();
    /////////////
    if (this.hostStep.getPreviousStep().hasNext())
        return this.hostStep.getPreviousStep().next();
    /////////////
    throw FastNoSuchElementException.instance();
}
 
Example #30
Source File: WherePredicateStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean filter(final Traverser.Admin<S> traverser) {
    final Object value = null == this.startKey ?
            TraversalUtil.applyNullable(traverser, this.traversalRing.next()) :
            TraversalUtil.applyNullable((S) this.getSafeScopeValue(Pop.last, this.startKey, traverser), this.traversalRing.next());
    this.setPredicateValues(this.predicate, traverser, this.selectKeys.iterator());
    this.traversalRing.reset();
    return this.predicate.test(value);
}