Search in sources :

Example 11 with OrientVertex

use of com.tinkerpop.blueprints.impls.orient.OrientVertex in project orientdb by orientechnologies.

the class OServerCommandGetGephi method execute.

@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    String[] urlParts = checkSyntax(iRequest.url, 4, "Syntax error: gephi/<database>/<language>/<query-text>[/<limit>][/<fetchPlan>].<br>Limit is optional and is setted to 20 by default. Set expressely to 0 to have no limits.");
    final String language = urlParts[2];
    final String text = urlParts[3];
    final int limit = urlParts.length > 4 ? Integer.parseInt(urlParts[4]) : 20;
    final String fetchPlan = urlParts.length > 5 ? urlParts[5] : null;
    iRequest.data.commandInfo = "Gephi";
    iRequest.data.commandDetail = text;
    final ODatabaseDocument db = getProfiledDatabaseInstance(iRequest);
    final OModifiableBoolean shutdownFlag = new OModifiableBoolean();
    final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getAnyGraph(shutdownFlag);
    try {
        final Iterable<OrientElement> vertices;
        if (language.equals("sql"))
            vertices = graph.command(new OSQLSynchQuery<OrientVertex>(text, limit).setFetchPlan(fetchPlan)).execute();
        else if (language.equals("gremlin")) {
            List<Object> result = new ArrayList<Object>();
            OGremlinHelper.execute(graph, text, null, null, result, null, null);
            vertices = new ArrayList<OrientElement>(result.size());
            for (Object o : result) {
                ((ArrayList<OrientElement>) vertices).add(graph.getVertex(o));
            }
        } else
            throw new IllegalArgumentException("Language '" + language + "' is not supported. Use 'sql' or 'gremlin'");
        sendRecordsContent(iRequest, iResponse, vertices, fetchPlan);
    } finally {
        if (graph != null && shutdownFlag.getValue())
            graph.shutdown(false, false);
        if (db != null)
            db.close();
    }
    return false;
}
Also used : ArrayList(java.util.ArrayList) OrientElement(com.tinkerpop.blueprints.impls.orient.OrientElement) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OrientBaseGraph(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) ArrayList(java.util.ArrayList) List(java.util.List) OModifiableBoolean(com.orientechnologies.common.types.OModifiableBoolean)

Example 12 with OrientVertex

use of com.tinkerpop.blueprints.impls.orient.OrientVertex in project orientdb by orientechnologies.

the class OCommandExecutorSQLCreateEdge method execute.

/**
   * Execute the command and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (clazz == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    return OGraphCommandExecutorSQLFactory.runInConfiguredTxMode(new OGraphCommandExecutorSQLFactory.GraphCallBack<List<Object>>() {

        @Override
        public List<Object> call(OrientBaseGraph graph) {
            final Set<OIdentifiable> fromIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), from, context, iArgs);
            final Set<OIdentifiable> toIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), to, context, iArgs);
            // CREATE EDGES
            final List<Object> edges = new ArrayList<Object>();
            for (OIdentifiable from : fromIds) {
                final OrientVertex fromVertex = graph.getVertex(from);
                if (fromVertex == null)
                    throw new OCommandExecutionException("Source vertex '" + from + "' not exists");
                for (OIdentifiable to : toIds) {
                    final OrientVertex toVertex;
                    if (from.equals(to)) {
                        toVertex = fromVertex;
                    } else {
                        toVertex = graph.getVertex(to);
                    }
                    if (fields != null)
                        // EVALUATE FIELDS
                        for (final OPair<String, Object> f : fields) {
                            if (f.getValue() instanceof OSQLFunctionRuntime) {
                                f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(to, null, context));
                            } else if (f.getValue() instanceof OSQLFilterItem) {
                                f.setValue(((OSQLFilterItem) f.getValue()).getValue(to, null, context));
                            }
                        }
                    OrientEdge edge = null;
                    if (content != null) {
                        if (fields != null)
                            // MERGE CONTENT WITH FIELDS
                            fields.addAll(OPair.convertFromMap(content.toMap()));
                        else
                            fields = OPair.convertFromMap(content.toMap());
                    }
                    edge = fromVertex.addEdge(null, toVertex, edgeLabel, clusterName, fields);
                    if (fields != null && !fields.isEmpty()) {
                        if (edge.isLightweight())
                            edge.convertToDocument();
                        OSQLHelper.bindParameters(edge.getRecord(), fields, new OCommandParameters(iArgs), context);
                    }
                    edge.save(clusterName);
                    edges.add(edge);
                    if (batch > 0 && edges.size() % batch == 0) {
                        graph.commit();
                        graph.begin();
                    }
                }
            }
            if (edges.isEmpty()) {
                if (fromIds.isEmpty())
                    throw new OCommandExecutionException("No edge has been created because no source vertices");
                else if (toIds.isEmpty())
                    throw new OCommandExecutionException("No edge has been created because no target vertices");
                throw new OCommandExecutionException("No edge has been created between " + fromIds + " and " + toIds);
            }
            return edges;
        }
    });
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OSQLFilterItem(com.orientechnologies.orient.core.sql.filter.OSQLFilterItem) OrientBaseGraph(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException)

Example 13 with OrientVertex

use of com.tinkerpop.blueprints.impls.orient.OrientVertex in project orientdb by orientechnologies.

the class OCommandExecutorSQLDeleteVertex method execute.

/**
   * Execute the command and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (rid == null && query == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    if (!returning.equalsIgnoreCase("COUNT"))
        allDeletedRecords = new ArrayList<ORecord>();
    txAlreadyBegun = getDatabase().getTransaction().isActive();
    if (rid != null) {
        // REMOVE PUNCTUAL RID
        OGraphCommandExecutorSQLFactory.runInConfiguredTxMode(new OGraphCommandExecutorSQLFactory.GraphCallBack<Object>() {

            @Override
            public Object call(OrientBaseGraph graph) {
                final OrientVertex v = graph.getVertex(rid);
                if (v != null) {
                    v.remove();
                    removed = 1;
                }
                return null;
            }
        });
        // CLOSE PENDING TX
        end();
    } else if (query != null) {
        // TARGET IS A CLASS + OPTIONAL CONDITION
        OGraphCommandExecutorSQLFactory.runInConfiguredTxMode(new OGraphCommandExecutorSQLFactory.GraphCallBack<OrientGraph>() {

            @Override
            public OrientGraph call(final OrientBaseGraph iGraph) {
                // TARGET IS A CLASS + OPTIONAL CONDITION
                currentGraph.set(iGraph);
                query.setContext(getContext());
                query.execute(iArgs);
                return null;
            }
        });
    } else
        throw new OCommandExecutionException("Invalid target");
    if (returning.equalsIgnoreCase("COUNT"))
        // RETURNS ONLY THE COUNT
        return removed;
    else
        // RETURNS ALL THE DELETED RECORDS
        return allDeletedRecords;
}
Also used : ArrayList(java.util.ArrayList) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OrientBaseGraph(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph)

Example 14 with OrientVertex

use of com.tinkerpop.blueprints.impls.orient.OrientVertex in project orientdb by orientechnologies.

the class OCommandExecutorSQLMoveVertex method execute.

/**
   * Executes the command and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (className == null && clusterName == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    OModifiableBoolean shutdownGraph = new OModifiableBoolean();
    final boolean txAlreadyBegun = getDatabase().getTransaction().isActive();
    final OrientGraph graph = OGraphCommandExecutorSQLFactory.getGraph(true, shutdownGraph);
    try {
        final Set<OIdentifiable> sourceRIDs = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), source, context, iArgs);
        // CREATE EDGES
        final List<ODocument> result = new ArrayList<ODocument>(sourceRIDs.size());
        for (OIdentifiable from : sourceRIDs) {
            final OrientVertex fromVertex = graph.getVertex(from);
            if (fromVertex == null)
                continue;
            final ORID oldVertex = fromVertex.getIdentity().copy();
            final ORID newVertex = fromVertex.moveTo(className, clusterName);
            final ODocument newVertexDoc = newVertex.getRecord();
            if (fields != null) {
                // EVALUATE FIELDS
                for (final OPair<String, Object> f : fields) {
                    if (f.getValue() instanceof OSQLFunctionRuntime)
                        f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(newVertex.getRecord(), null, context));
                }
                OSQLHelper.bindParameters(newVertexDoc, fields, new OCommandParameters(iArgs), context);
            }
            if (merge != null)
                newVertexDoc.merge(merge, true, false);
            // SAVE CHANGES
            newVertexDoc.save();
            // PUT THE MOVE INTO THE RESULT
            result.add(new ODocument().setTrackingChanges(false).field("old", oldVertex, OType.LINK).field("new", newVertex, OType.LINK));
            if (batch > 0 && result.size() % batch == 0) {
                graph.commit();
                if (!graph.isAutoStartTx())
                    graph.begin();
            }
        }
        graph.commit();
        return result;
    } finally {
        if (!txAlreadyBegun)
            graph.commit();
        if (shutdownGraph.getValue())
            graph.shutdown(false);
    }
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) OrientGraph(com.tinkerpop.blueprints.impls.orient.OrientGraph) ArrayList(java.util.ArrayList) OCommandParameters(com.orientechnologies.orient.core.sql.OCommandParameters) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ORID(com.orientechnologies.orient.core.id.ORID) OModifiableBoolean(com.orientechnologies.common.types.OModifiableBoolean) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 15 with OrientVertex

use of com.tinkerpop.blueprints.impls.orient.OrientVertex in project orientdb by orientechnologies.

the class OHttpGraphResponse method writeRecords.

public void writeRecords(final Object iRecords, final String iFetchPlan, String iFormat, final String accept, final Map<String, Object> iAdditionalProperties, final String mode) throws IOException {
    if (iRecords == null) {
        send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null);
        return;
    }
    if (!mode.equalsIgnoreCase("graph")) {
        super.writeRecords(iRecords, iFetchPlan, iFormat, accept, iAdditionalProperties, mode);
        return;
    }
    if (accept != null && accept.contains("text/csv"))
        throw new IllegalArgumentException("Graph mode cannot accept '" + accept + "'");
    final OrientGraphNoTx graph = (OrientGraphNoTx) OrientGraphFactory.getNoTxGraphImplFactory().getGraph((ODatabaseDocumentTx) ODatabaseRecordThreadLocal.INSTANCE.get());
    try {
        // DIVIDE VERTICES FROM EDGES
        final Set<OrientVertex> vertices = new HashSet<OrientVertex>();
        final Set<OrientEdge> edges = new HashSet<OrientEdge>();
        final Iterator<Object> iIterator = OMultiValue.getMultiValueIterator(iRecords);
        while (iIterator.hasNext()) {
            Object entry = iIterator.next();
            if (entry == null || !(entry instanceof OIdentifiable))
                // IGNORE IT
                continue;
            entry = ((OIdentifiable) entry).getRecord();
            if (entry == null || !(entry instanceof OIdentifiable))
                // IGNORE IT
                continue;
            if (entry instanceof ODocument) {
                OClass schemaClass = ((ODocument) entry).getSchemaClass();
                if (schemaClass != null && schemaClass.isVertexType())
                    vertices.add(graph.getVertex(entry));
                else if (schemaClass != null && schemaClass.isEdgeType()) {
                    OrientEdge edge = graph.getEdge(entry);
                    vertices.add(graph.getVertex(edge.getVertex(Direction.IN)));
                    vertices.add(graph.getVertex(edge.getVertex(Direction.OUT)));
                    edges.add(edge);
                } else
                    // IGNORE IT
                    continue;
            }
        }
        final StringWriter buffer = new StringWriter();
        final OJSONWriter json = new OJSONWriter(buffer, "");
        json.beginObject();
        json.beginObject("graph");
        // WRITE VERTICES
        json.beginCollection("vertices");
        for (OrientVertex vertex : vertices) {
            json.beginObject();
            json.writeAttribute("@rid", vertex.getIdentity());
            json.writeAttribute("@class", vertex.getRecord().getClassName());
            // ADD ALL THE VERTEX'S EDGES
            for (Edge e : vertex.getEdges(Direction.BOTH)) edges.add((OrientEdge) e);
            // ADD ALL THE PROPERTIES
            for (String field : vertex.getPropertyKeys()) {
                final Object v = vertex.getProperty(field);
                if (v != null)
                    json.writeAttribute(field, v);
            }
            json.endObject();
        }
        json.endCollection();
        // WRITE EDGES
        json.beginCollection("edges");
        for (OrientEdge edge : edges) {
            if (!vertices.contains(edge.getVertex(Direction.OUT)) || !vertices.contains(edge.getVertex(Direction.IN)))
                // ONE OF THE 2 VERTICES ARE NOT PART OF THE RESULT SET: DISCARD IT
                continue;
            json.beginObject();
            json.writeAttribute("@rid", edge.getIdentity());
            json.writeAttribute("@class", edge.getRecord().getClassName());
            json.writeAttribute("out", edge.getVertex(Direction.OUT).getId());
            json.writeAttribute("in", edge.getVertex(Direction.IN).getId());
            for (String field : edge.getPropertyKeys()) {
                final Object v = edge.getProperty(field);
                if (v != null)
                    json.writeAttribute(field, v);
            }
            json.endObject();
        }
        json.endCollection();
        if (iAdditionalProperties != null) {
            for (Map.Entry<String, Object> entry : iAdditionalProperties.entrySet()) {
                final Object v = entry.getValue();
                if (OMultiValue.isMultiValue(v)) {
                    json.beginCollection(-1, true, entry.getKey());
                    formatMultiValue(OMultiValue.getMultiValueIterator(v), buffer, null);
                    json.endCollection(-1, true);
                } else
                    json.writeAttribute(entry.getKey(), v);
                if (Thread.currentThread().isInterrupted())
                    break;
            }
        }
        json.endObject();
        json.endObject();
        send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null);
    } finally {
        graph.shutdown();
    }
}
Also used : OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter) ODatabaseDocumentTx(com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) StringWriter(java.io.StringWriter) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OrientGraphNoTx(com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx) Edge(com.tinkerpop.blueprints.Edge) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) Map(java.util.Map) HashSet(java.util.HashSet) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OrientVertex (com.tinkerpop.blueprints.impls.orient.OrientVertex)155 Test (org.junit.Test)73 OrientGraph (com.tinkerpop.blueprints.impls.orient.OrientGraph)42 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)40 OrientBaseGraph (com.tinkerpop.blueprints.impls.orient.OrientBaseGraph)37 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)35 OrientGraphNoTx (com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx)26 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)25 OrientEdge (com.tinkerpop.blueprints.impls.orient.OrientEdge)25 Vertex (com.tinkerpop.blueprints.Vertex)24 HashMap (java.util.HashMap)20 OBasicCommandContext (com.orientechnologies.orient.core.command.OBasicCommandContext)13 OrientGraphFactory (com.tinkerpop.blueprints.impls.orient.OrientGraphFactory)13 OrientVertexType (com.tinkerpop.blueprints.impls.orient.OrientVertexType)13 Edge (com.tinkerpop.blueprints.Edge)12 OConcurrentModificationException (com.orientechnologies.orient.core.exception.OConcurrentModificationException)10 GraphNoTxAbstractTest (com.orientechnologies.orient.graph.GraphNoTxAbstractTest)9 ORID (com.orientechnologies.orient.core.id.ORID)7 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)7 GraphTxAbstractTest (com.orientechnologies.orient.graph.GraphTxAbstractTest)7