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 File: JanusGraphPropertiesStep.java    From grakn with 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 #2
Source File: ReferenceElement.java    From tinkerpop with 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 #3
Source File: ElementHelperTest.java    From tinkerpop with 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 #4
Source File: MemoryGraphStore.java    From bitsy with 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 #5
Source File: PolymorphicTypeResolver.java    From Ferma with 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 #6
Source File: TitanPropertiesStep.java    From titan1withtp3.1 with 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 #7
Source File: TypeUtil.java    From grakn with 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 #8
Source File: MapInAdjacentVerticesHandler.java    From windup with 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 #9
Source File: PolymorphicTypeResolver.java    From Ferma with 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 #10
Source File: SqlgPropertiesStep.java    From sqlg with 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 #11
Source File: MemoryGraphStore.java    From bitsy with 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 #12
Source File: AddV.java    From gremlin-ogm with 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 #13
Source File: HasKeys.java    From gremlin-ogm with 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;
}
 
Example #14
Source File: DelegatingFramedGraph.java    From Ferma with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T frameNewElementExplicit(final Element e, final ClassInitializer<T> initializer) {
    final T frame = frameElement(e, initializer.getInitializationType());
    this.untypedResolver.init(e, initializer.getInitializationType());
    ((AbstractElementFrame) frame).init();
    initializer.initalize(frame);
    return frame;
}
 
Example #15
Source File: DetachedFactory.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static DetachedElement detach(final Element element, final boolean withProperties) {
    if (element instanceof Vertex)
        return detach((Vertex) element, withProperties);
    else if (element instanceof Edge)
        return detach((Edge) element, withProperties);
    else if (element instanceof VertexProperty)
        return detach((VertexProperty) element, withProperties);
    else
        throw new IllegalArgumentException("The provided argument is an unknown element: " + element + ':' + element.getClass());
}
 
Example #16
Source File: TinkerGraph.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an {@link TinkerGraph.IdManager} from the TinkerGraph {@code Configuration}.
 */
private static IdManager<?> selectIdManager(final Configuration config, final String configKey, final Class<? extends Element> clazz) {
    final String vertexIdManagerConfigValue = config.getString(configKey, DefaultIdManager.ANY.name());
    try {
        return DefaultIdManager.valueOf(vertexIdManagerConfigValue);
    } catch (IllegalArgumentException iae) {
        try {
            return (IdManager) Class.forName(vertexIdManagerConfigValue).newInstance();
        } catch (Exception ex) {
            throw new IllegalStateException(String.format("Could not configure TinkerGraph %s id manager with %s", clazz.getSimpleName(), vertexIdManagerConfigValue));
        }
    }
}
 
Example #17
Source File: FramedGraph.java    From peapod with Apache License 2.0 5 votes vote down vote up
public <F, E extends Element> List<F> frame(Iterator<E> it, Class<F> clazz) {
    List<F> result = new ArrayList<>();
    it.forEachRemaining(e -> {
        IFramer<E, F> framer = registry.get(e, clazz);
        result.add(framer.frame(e, this));
    });
    return Collections.unmodifiableList(result);
}
 
Example #18
Source File: FramedGraphTest.java    From Ferma with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomFrameBuilderExplicitByClass() {
    final Person o = new Person();
    final Graph g = TinkerGraph.open();
    final FramedGraph fg = new DelegatingFramedGraph(g, new FrameFactory() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T create(final Element e, final Class<T> kind) {
            return (T) o;
        }
    }, new PolymorphicTypeResolver());
    final Person person = fg.addFramedVertexExplicit(Person.class);
    Assert.assertEquals(o, person);
}
 
Example #19
Source File: HBaseIndexImportMapper.java    From hgraphdb with Apache License 2.0 5 votes vote down vote up
protected static Iterator<? extends Mutation> constructMutations(
        HBaseGraph graph, IndexMetadata index, ElementReader<?> reader, Result result)
        throws IOException, InterruptedException {

    Element element = reader.parse(result);
    if (element.label().equals(index.label()) && ((HBaseElement) element).hasProperty(index.propertyKey())) {
        Creator writer = index.type() == ElementType.EDGE
                ? new EdgeIndexWriter(graph, (Edge) element, index.propertyKey())
                : new VertexIndexWriter(graph, (Vertex) element, index.propertyKey());
        return writer.constructInsertions();
    }
    return Collections.emptyIterator();
}
 
Example #20
Source File: ElementHelperTest.java    From tinkerpop with 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 #21
Source File: DelegatingFramedGraph.java    From Ferma with 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 #22
Source File: DefaultTraversable.java    From Ferma with Apache License 2.0 5 votes vote down vote up
@Override
public <N> Iterator<? extends N> frameExplicit(final Class<N> kind) {
    return new Iterator<N>() {
        @Override
        public boolean hasNext() {
            return baseTraversal.hasNext();
        }

        @Override
        public N next() {
            return parentGraph.frameElementExplicit((Element) baseTraversal.next(), kind);
        }
    };
}
 
Example #23
Source File: UntypedTypeResolverTest.java    From Ferma with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveWithDefault() {
    Element mockElement = Mockito.mock(Element.class);
    Assert.assertEquals(resolver.resolve(mockElement, VertexFrame.class), TVertex.class);
    Mockito.verifyZeroInteractions(mockElement);
    Assert.assertEquals(resolver.resolve(mockElement, AbstractVertexFrame.class), TVertex.class);
    Mockito.verifyZeroInteractions(mockElement);
    Assert.assertEquals(resolver.resolve(mockElement, EdgeFrame.class), TEdge.class);
    Mockito.verifyZeroInteractions(mockElement);
    Assert.assertEquals(resolver.resolve(mockElement, AbstractEdgeFrame.class), TEdge.class);
    Mockito.verifyZeroInteractions(mockElement);
    Assert.assertEquals(resolver.resolve(mockElement, God.class), God.class);
    Mockito.verifyZeroInteractions(mockElement);
}
 
Example #24
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private static String[] getEntityTypes(Element element) {
  try {
    String typesProp = getRequiredProp(element, "types", "");
    if (typesProp.equals("[]")) {
      LOG.error(databaseInvariant, "Entitytypes not present on vertex with ID " + element.id());
      return new String[0];
    } else {
      return arrayToEncodedArray.tinkerpopToJava(typesProp, String[].class);
    }
  } catch (IOException e) {
    LOG.error(databaseInvariant, "Could not parse entitytypes property on vertex with ID " + element.id());
    return new String[0];
  }
}
 
Example #25
Source File: JanusGraphPropertiesStep.java    From grakn with 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 #26
Source File: ElementModel.java    From hgraphdb with 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 #27
Source File: ElementHelperTest.java    From tinkerpop with 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 #28
Source File: IndexHelper.java    From titan1withtp3.1 with 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 #29
Source File: OutRolePlayerFragment.java    From grakn with 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 #30
Source File: HasTest.java    From tinkerpop with 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);
    }
}