org.apache.tinkerpop.gremlin.structure.Element Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Element. 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 Project: tinkerpop   Author: apache   File: ReferenceElement.java    License: Apache License 2.0 6 votes vote down vote up
public ReferenceElement(final Element element) {
    this.id = element.id();
    try {
        //Exception creation takes too much time, return default values for known types
        if (element instanceof ComputerGraph.ComputerAdjacentVertex) {
            this.label = Vertex.DEFAULT_LABEL;
        } else {
            this.label = element.label();
        }
    } catch (final UnsupportedOperationException e) {
        if (element instanceof Vertex)
            this.label = Vertex.DEFAULT_LABEL;
        else if (element instanceof Edge)
            this.label = Edge.DEFAULT_LABEL;
        else
            this.label = VertexProperty.DEFAULT_LABEL;
    }
}
 
Example #2
Source Project: sqlg   Author: pietermartin   File: SqlgPropertiesStep.java    License: MIT License 6 votes vote down vote up
@Override
protected Iterator<E> flatMap(final Traverser.Admin<Element> traverser) {
    for (String appliesToLabel : appliesToLabels) {
        String label = SqlgUtil.originalLabel(appliesToLabel);
        Object o = traverser.path().get(label);
        if (o instanceof List) {
            List<SqlgElement> objects = (List) o;
            SqlgElement last = objects.get(objects.size() - 1);
            if (this.returnType.equals(PropertyType.VALUE)) {
                return last.values(this.propertyKeys);
            } else {
                return (Iterator)last.properties(this.propertyKeys);
            }
        } else {
            SqlgElement sqlgElement = traverser.path().get(label);
            if (this.returnType.equals(PropertyType.VALUE)) {
                return sqlgElement.values(this.propertyKeys);
            } else {
                return (Iterator) sqlgElement.properties(this.propertyKeys);
            }
        }
    }
    return EmptyIterator.INSTANCE;
}
 
Example #3
Source Project: windup   Author: windup   File: MapInAdjacentVerticesHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@RuntimeType
public static Object execute(@This final ElementFrame thisFrame, @Origin final Method method, @RuntimeType @AllArguments final Object[] args)
{
    final MapInAdjacentVertices ann = ((CachesReflection) thisFrame).getReflectionCache().getAnnotation(method, MapInAdjacentVertices.class);

    Element thisElement = thisFrame.getElement();
    if (!(thisElement instanceof Vertex))
        throw new WindupException("Element is not of supported type, must be Vertex, but was: " + thisElement.getClass().getCanonicalName());
    Vertex vertex = (Vertex) thisElement;

    String methodName = method.getName();
    if (methodName.startsWith("get"))
    {
        return handleGetter(vertex, method, args, ann, thisFrame.getGraph());
    }
    else if (methodName.startsWith("set"))
    {
        handleSetter((VertexFrame)thisFrame, method, args, ann, thisFrame.getGraph());
        return null;
    }

    throw new WindupException("Only get* and set* method names are supported.");
}
 
Example #4
Source Project: grakn   Author: graknlabs   File: TypeUtil.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static void checkTypeName(JanusGraphSchemaCategory category, String name) {
    switch (category) {
        case EDGELABEL:
        case VERTEXLABEL:
            if (name == null) throw Element.Exceptions.labelCanNotBeNull();
            if (StringUtils.isBlank(name)) throw Element.Exceptions.labelCanNotBeEmpty();
            break;
        case PROPERTYKEY:
            if (name == null) throw Property.Exceptions.propertyKeyCanNotBeNull();
            if (StringUtils.isBlank(name)) throw Property.Exceptions.propertyKeyCanNotBeEmpty();
            break;
        case GRAPHINDEX:
            Preconditions.checkArgument(StringUtils.isNotBlank(name), "Index name cannot be empty: %s", name);
            break;
        default:
            throw new AssertionError(category);
    }
}
 
Example #5
Source Project: bitsy   Author: lambdazen   File: MemoryGraphStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Element> void createKeyIndex(String key, Class<T> elementType) {
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in createKeyIndex() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            vIndexMap.createKeyIndex(key, getAllVertices().iterator());
        } else if (elementType.equals(Edge.class)) {
            eIndexMap.createKeyIndex(key, getAllEdges().iterator());
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example #6
Source Project: Ferma   Author: Syncleus   File: PolymorphicTypeResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <P extends Element, T extends Element> GraphTraversal<P, T> hasNotType(final GraphTraversal<P, T> traverser, final Class<?> type) {
    final Set<? extends String> allAllowedValues = this.reflectionCache.getSubTypeNames(type.getName());
    return traverser.filter(new Predicate<Traverser<T>>() {
        @Override
        public boolean test(final Traverser<T> toCheck) {
            final Property<String> property = toCheck.get().property(typeResolutionKey);
            if( !property.isPresent() )
                return true;

            final String resolvedType = property.value();
            if( allAllowedValues.contains(resolvedType) )
                return false;
            else
                return true;
        }
    });
}
 
Example #7
Source Project: tinkerpop   Author: apache   File: ElementHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeterminePropertiesAreNotEqualWhenKeysAreDifferent() {
    final Property mockPropertyA = mock(Property.class);
    final Property mockPropertyB = mock(Property.class);
    final Element mockElement = mock(Element.class);
    when(mockPropertyA.isPresent()).thenReturn(true);
    when(mockPropertyB.isPresent()).thenReturn(true);
    when(mockPropertyA.element()).thenReturn(mockElement);
    when(mockPropertyB.element()).thenReturn(mockElement);
    when(mockPropertyA.key()).thenReturn("k");
    when(mockPropertyB.key()).thenReturn("k1");
    when(mockPropertyA.value()).thenReturn("v");
    when(mockPropertyB.value()).thenReturn("v");

    assertFalse(ElementHelper.areEqual(mockPropertyA, mockPropertyB));
}
 
Example #8
Source Project: titan1withtp3.1   Author: graben1437   File: TitanPropertiesStep.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Iterator<E> flatMap(final Traverser.Admin<Element> traverser) {
    if (useMultiQuery) { //it is guaranteed that all elements are vertices
        assert multiQueryResults != null;
        return convertIterator(multiQueryResults.get(traverser.get()));
    } else if (traverser.get() instanceof Vertex) {
        TitanVertexQuery query = makeQuery((TitanTraversalUtil.getTitanVertex(traverser)).query());
        return convertIterator(query.properties());
    } else {
        //It is some other element (edge or vertex property)
        Iterator<E> iter;
        if (getReturnType().forValues()) {
            assert orders.isEmpty() && hasContainers.isEmpty();
            iter = traverser.get().values(getPropertyKeys());
        } else {
            //this asks for properties
            assert orders.isEmpty();
            //HasContainers don't apply => empty result set
            if (!hasContainers.isEmpty()) return Collections.emptyIterator();
            iter = (Iterator<E>) traverser.get().properties(getPropertyKeys());
        }
        if (limit!=Query.NO_LIMIT) iter = Iterators.limit(iter,limit);
        return iter;
    }
}
 
Example #9
Source Project: gremlin-ogm   Author: karthicks   File: AddV.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SneakyThrows
public GraphTraversal<Element, Element> apply(GraphTraversalSource g) {
  GraphTraversal traversal = g.addV(element.label());
  if (element.id() != null && HasFeature.Verifier.of(g)
      .verify(supportsUserSuppliedIds(element))) {
    traversal.property(T.id, element.id());
  }
  for (Field field : keyFields(element)) {
    String key = propertyKey(field);
    Object value = propertyValue(field, element);
    if (isMissing(value)) {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions.requiredKeysMissing(
          element.getClass(), key);
    }
    traversal.property(key, value);
  }
  return traversal;
}
 
Example #10
Source Project: Ferma   Author: Syncleus   File: PolymorphicTypeResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> Class<? extends T> resolve(final Element element, final Class<T> kind) {
    final Property<String> nodeClazzProperty = element.<String>property(this.typeResolutionKey);
    final String nodeClazz;
    if( nodeClazzProperty.isPresent() )
        nodeClazz = nodeClazzProperty.value();
    else
        return kind;

    final Class<T> nodeKind = (Class<T>) this.reflectionCache.forName(nodeClazz);

    if (kind.isAssignableFrom(nodeKind) || kind.equals(VertexFrame.class) || kind.equals(EdgeFrame.class) || kind.equals(AbstractVertexFrame.class) || kind.equals(AbstractEdgeFrame.class) || kind.
          equals(Object.class))
        return nodeKind;
    else
        return kind;
}
 
Example #11
Source Project: bitsy   Author: lambdazen   File: MemoryGraphStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Element> Set<String> getIndexedKeys(Class<T> elementType) {
    // Getting a write lock because this method accesses the list of index names which isn't thread-safe
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in getIndexedKeys() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            return vIndexMap.getIndexedKeys();
        } else if (elementType.equals(Edge.class)) {
            return eIndexMap.getIndexedKeys();
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example #12
Source Project: grakn   Author: graknlabs   File: JanusGraphPropertiesStep.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected Iterator<E> flatMap(Traverser.Admin<Element> traverser) {
    if (useMultiQuery) { //it is guaranteed that all elements are vertices
        if (multiQueryResults == null || !multiQueryResults.containsKey(traverser.get())) {
            initializeMultiQuery(Arrays.asList(traverser));
        }
        return convertIterator(multiQueryResults.get(traverser.get()));
    } else if (traverser.get() instanceof JanusGraphVertex || traverser.get() instanceof WrappedVertex) {
        JanusGraphVertexQuery query = makeQuery((JanusGraphTraversalUtil.getJanusGraphVertex(traverser)).query());
        return convertIterator(query.properties());
    } else {
        //It is some other element (edge or vertex property)
        Iterator<E> iterator;
        if (getReturnType().forValues()) {
            iterator = traverser.get().values(getPropertyKeys());
        } else {
            //HasContainers don't apply => empty result set
            if (!hasContainers.isEmpty()) return Collections.emptyIterator();
            iterator = (Iterator<E>) traverser.get().properties(getPropertyKeys());
        }
        if (limit != Query.NO_LIMIT) iterator = Iterators.limit(iterator, limit);
        return iterator;
    }
}
 
Example #13
Source Project: bitsy   Author: lambdazen   File: FileBackedMemoryGraphStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Element> void dropKeyIndex(String key, Class<T> elementType) {
    memStore.dropKeyIndex(key, elementType);

    // Rewrite the metadata file -- all metadata file ops are synchronized on the mA object
    synchronized (mA) {
        saveVersionAndIndexes();
    }
}
 
Example #14
Source Project: sqlg   Author: pietermartin   File: TestGremlinCompileWithAs.java    License: MIT License 5 votes vote down vote up
private void testAsWithDuplicatePaths_assert(SqlgGraph sqlgGraph, Vertex a1, Edge e1) {
    DefaultGraphTraversal<Vertex, Map<String, Element>> gt = (DefaultGraphTraversal<Vertex, Map<String, Element>>) sqlgGraph.traversal()
            .V(a1)
            .outE().as("e")
            .inV()
            .in().as("v")
            .<Element>select("e", "v");
    Assert.assertEquals(5, gt.getSteps().size());

    List<Map<String, Element>> result = gt.toList();
    Assert.assertEquals(2, gt.getSteps().size());
    Assert.assertEquals(1, result.size());
    Assert.assertEquals(e1, result.get(0).get("e"));
    Assert.assertEquals(a1, result.get(0).get("v"));
}
 
Example #15
Source Project: tinkerpop   Author: apache   File: IoTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void assertId(final Graph g, final boolean lossyForId, final Element e, final Object expected) {
    // it is possible that a Graph (e.g. elastic-gremlin) can supportUserSuppliedIds but internally
    // represent them as a value other than Numeric (which is what's in all of the test/toy data).
    // as we feature check for userSuppliedIds when asserting the identifier, we also ensure that
    // the id can be properly asserted for that Element before attempting to do so.  By asserting
    // at this level in this way, graphs can enjoy greater test coverage in IO.
    if ((e instanceof Vertex && g.features().vertex().supportsUserSuppliedIds() && g.features().vertex().supportsNumericIds())
            || (e instanceof Edge && g.features().edge().supportsUserSuppliedIds() && g.features().edge().supportsNumericIds())
            || (e instanceof VertexProperty && g.features().vertex().properties().supportsUserSuppliedIds()) && g.features().vertex().properties().supportsNumericIds()) {
        if (lossyForId)
            assertEquals(expected.toString(), e.id().toString());
        else
            assertEquals(expected, e.id());
    }
}
 
Example #16
Source Project: hugegraph   Author: hugegraph   File: HugeElement.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Element)) {
        return false;
    }

    Element other = (Element) obj;
    if (this.id() == null) {
        return false;
    }

    return this.id().equals(other.id());
}
 
Example #17
Source Project: hugegraph   Author: hugegraph   File: HugeElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Classify parameter list(pairs) from call request
 * @param keyValues The property key-value pair of the vertex or edge
 * @return          Key-value pairs that are classified and processed
 */
@Watched(prefix = "element")
public static final ElementKeys classifyKeys(Object... keyValues) {
    ElementKeys elemKeys = new ElementKeys();

    if ((keyValues.length & 1) == 1) {
        throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo();
    }
    for (int i = 0; i < keyValues.length; i = i + 2) {
        Object key = keyValues[i];
        Object val = keyValues[i + 1];

        if (!(key instanceof String) && !(key instanceof T)) {
            throw Element.Exceptions
                  .providedKeyValuesMustHaveALegalKeyOnEvenIndices();
        }
        if (val == null) {
            throw Property.Exceptions.propertyValueCanNotBeNull();
        }

        if (key.equals(T.id)) {
            elemKeys.id = val;
        } else if (key.equals(T.label)) {
            elemKeys.label = val;
        } else {
            elemKeys.keys.add(key.toString());
        }
    }
    return elemKeys;
}
 
Example #18
Source Project: hugegraph   Author: hugegraph   File: TraversalUtil.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <V> Iterator<V> filterResult(
                              List<HasContainer> hasContainers,
                              Iterator<? extends Element> iterator) {
    Iterator<?> result = new FilterIterator<>(iterator, elem -> {
        return HasContainer.testAll(elem, hasContainers);
    });
    return (Iterator<V>) result;
}
 
Example #19
Source Project: timbuctoo   Author: HuygensING   File: TinkerPopOperations.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Optional<Collection> getOwnCollectionOfElement(Vre vre, Element sourceV) {
  String ownType = vre.getOwnType(getEntityTypes(sourceV));
  if (ownType == null) {
    return Optional.empty();
  }
  return Optional.of(vre.getCollectionForTypeName(ownType));
}
 
Example #20
Source Project: grakn   Author: graknlabs   File: OutHasFragment.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
GraphTraversal<Vertex, Vertex> applyTraversalInner(GraphTraversal<Vertex, ? extends Element> traversal, ConceptManager conceptManager, Collection<Variable> vars) {
    // a type can own any attribute that any of its parents (self inclusive) can own
    return Fragments
            .outSubs(Fragments.isVertex(traversal))
            .out(Schema.EdgeLabel.HAS.getLabel(), Schema.EdgeLabel.KEY.getLabel());
}
 
Example #21
Source Project: tinkerpop   Author: apache   File: JavaUtilSerializersV1d0.java    License: Apache License 2.0 5 votes vote down vote up
private static void ser(final Map.Entry entry, final JsonGenerator jsonGenerator,
                        final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
    jsonGenerator.writeStartObject();
    if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());

    // this treatment of keys is consistent with the current GraphSONKeySerializer which extends the
    // StdKeySerializer
    final Object key = entry.getKey();
    final Class cls = key.getClass();
    String k;
    if (cls == String.class)
        k = (String) key;
    else if (Element.class.isAssignableFrom(cls))
        k = ((Element) key).id().toString();
    else if(Date.class.isAssignableFrom(cls)) {
        if (serializerProvider.isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS))
            k = String.valueOf(((Date) key).getTime());
        else
            k = serializerProvider.getConfig().getDateFormat().format((Date) key);
    } else if(cls == Class.class)
        k = ((Class) key).getName();
    else
        k = key.toString();

    serializerProvider.defaultSerializeField(k, entry.getValue(), jsonGenerator);
    jsonGenerator.writeEndObject();
}
 
Example #22
Source Project: Ferma   Author: Syncleus   File: DelegatingFramedGraph.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T frameElementExplicit(final Element e, final Class<T> kind) {
    if (e == null)
        return null;

    final Class<? extends T> frameType = this.untypedResolver.resolve(e, kind);

    final T frame = builder.create(e, frameType);
    ((AbstractElementFrame) frame).init(this, e);
    return frame;
}
 
Example #23
Source Project: grakn   Author: graknlabs   File: OutRolePlayerFragment.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public GraphTraversal<Vertex, ? extends Element> applyTraversalInner(
        GraphTraversal<Vertex, ? extends Element> traversal, ConceptManager conceptManager, Collection<Variable> vars) {

    return Fragments.union(traversal, ImmutableSet.of(
            relationTraversal(conceptManager, vars)
    ));
}
 
Example #24
Source Project: tinkerpop   Author: apache   File: HasTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXage_isXgt_30XX() {
    final Traversal<Vertex, Vertex> traversal = get_g_V_hasXage_isXgt_30XX();
    printTraversalForm(traversal);
    final List<Vertex> list = traversal.toList();
    assertEquals(2, list.size());
    for (final Element v : list) {
        assertTrue(v.<Integer>value("age") > 30);
    }
}
 
Example #25
Source Project: titan1withtp3.1   Author: graben1437   File: IndexHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Iterable<? extends Element> getQueryResults(CompositeIndexType index, Object[] values, StandardTitanTx tx) {
    GraphCentricQueryBuilder gb = getQuery(index,values,tx);
    switch(index.getElement()) {
        case VERTEX:
            return gb.vertices();
        case EDGE:
            return gb.edges();
        case PROPERTY:
            return gb.properties();
        default: throw new AssertionError();
    }
}
 
Example #26
Source Project: tinkerpop   Author: apache   File: ElementHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDetermineEdgesAreEqual() {
    final Element mockEdgeA = mock(Edge.class);
    final Element mockEdgeB = mock(Edge.class);
    when(mockEdgeA.id()).thenReturn("1");
    when(mockEdgeB.id()).thenReturn("1");
    assertTrue(ElementHelper.areEqual(mockEdgeA, mockEdgeB));
}
 
Example #27
Source Project: hgraphdb   Author: rayokota   File: ElementModel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load the element from the backing table.
 *
 * @param element The element
 */
@SuppressWarnings("unchecked")
public void load(Element element) {
    LOGGER.trace("Executing Get, type: {}, id: {}", getClass().getSimpleName(), element.id());

    Get get = new Get(ValueUtils.serializeWithSalt(element.id()));

    try {
        Result result = table.get(get);
        getReader().load(element, result);
    } catch (IOException e) {
        throw new HBaseGraphException(e);
    }
}
 
Example #28
Source Project: grakn   Author: graknlabs   File: JanusGraphPropertiesStep.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void initialize() {
    initialized = true;

    if (!starts.hasNext()) throw FastNoSuchElementException.instance();
    List<Traverser.Admin<Element>> elements = new ArrayList<>();
    starts.forEachRemaining(elements::add);
    starts.add(elements.iterator());

    useMultiQuery = useMultiQuery && elements.stream().allMatch(e -> e.get() instanceof Vertex);

    if (useMultiQuery) {
        initializeMultiQuery(elements);
    }
}
 
Example #29
Source Project: tinkerpop   Author: apache   File: ElementHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotAllowEvenNumberOfKeyValuesAndInvalidKeys() {
    try {
        ElementHelper.legalPropertyKeyValueArray("aKey", "test", "value-for-this-one", 1, 1, "none");
        fail("Should fail as there is an even number of key-values, but a bad key");
    } catch (IllegalArgumentException iae) {
        assertEquals(Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices().getMessage(), iae.getMessage());
    }
}
 
Example #30
Source Project: gremlin-ogm   Author: karthicks   File: HasKeys.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SneakyThrows
public GraphTraversal<Element, Element> apply(GraphTraversal<Element, Element> traversal) {
  traversal.hasLabel(element.label());
  List<Field> fields;
  if (keyType != null) {
    if (is(keyType, PrimaryKey.class)) {
      fields = primaryKeyFields(element);
    } else if (is(keyType, OrderingKey.class)) {
      fields = orderingKeyFields(element);
    } else {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions
          .invalidAnnotationType(keyType);
    }
  } else {
    fields = keyFields(element);
  }
  for (Field field : fields) {
    String key = propertyKey(field);
    Object value = propertyValue(field, element);
    if (isMissing(value)) {
      throw org.apache.tinkerpop.gremlin.object.structure.Element.Exceptions.requiredKeysMissing(
          element.getClass(), key);
    }
    traversal.has(key, value);
  }
  return traversal;
}