Search in sources :

Example 16 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException 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 17 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException 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 18 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OSQLFunctionLabel method getLabel.

private Object getLabel(final OrientBaseGraph graph, final OIdentifiable iCurrentRecord) {
    final ODocument rec = iCurrentRecord.getRecord();
    OImmutableClass immutableClass = ODocumentInternal.getImmutableSchemaClass(rec);
    if (immutableClass.isVertexType()) {
        // VERTEX
        final OrientVertex vertex = graph.getVertex(iCurrentRecord);
        return vertex.getLabel();
    } else if (immutableClass.isEdgeType()) {
        // EDGE
        final OrientEdge edge = graph.getEdge(iCurrentRecord);
        return edge.getLabel();
    } else
        throw new OCommandExecutionException("Invalid record: is neither a vertex nor an edge. Found class: " + immutableClass);
}
Also used : OImmutableClass(com.orientechnologies.orient.core.metadata.schema.OImmutableClass) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 19 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLHAStatus method execute.

/**
   * Execute the command.
   */
public Object execute(final Map<Object, Object> iArgs) {
    final ODatabaseDocumentInternal database = getDatabase();
    database.checkSecurity(ORule.ResourceGeneric.SERVER, "status", ORole.PERMISSION_READ);
    final String dbUrl = database.getURL();
    final String path = dbUrl.substring(dbUrl.indexOf(":") + 1);
    final OServer serverInstance = OServer.getInstanceByPath(path);
    final OHazelcastPlugin dManager = (OHazelcastPlugin) serverInstance.getDistributedManager();
    if (dManager == null || !dManager.isEnabled())
        throw new OCommandExecutionException("OrientDB is not started in distributed mode");
    final String databaseName = database.getName();
    final ODistributedConfiguration cfg = dManager.getDatabaseConfiguration(databaseName);
    if (parsedStatement.outputText) {
        final StringBuilder output = new StringBuilder();
        if (parsedStatement.servers)
            output.append(ODistributedOutput.formatServerStatus(dManager, dManager.getClusterConfiguration()));
        if (parsedStatement.db)
            output.append(ODistributedOutput.formatClusterTable(dManager, databaseName, cfg, dManager.getAvailableNodes(databaseName)));
        if (parsedStatement.latency)
            output.append(ODistributedOutput.formatLatency(dManager, dManager.getClusterConfiguration()));
        if (parsedStatement.messages)
            output.append(ODistributedOutput.formatMessages(dManager, dManager.getClusterConfiguration()));
        return output.toString();
    }
    final ODocument output = new ODocument();
    if (parsedStatement.servers)
        output.field("servers", dManager.getClusterConfiguration(), OType.EMBEDDED);
    if (parsedStatement.db)
        output.field("database", cfg.getDocument(), OType.EMBEDDED);
    return output;
}
Also used : OServer(com.orientechnologies.orient.server.OServer) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OHazelcastPlugin(com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin) ODistributedConfiguration(com.orientechnologies.orient.server.distributed.ODistributedConfiguration) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 20 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLHASyncCluster method replaceCluster.

public static Object replaceCluster(final ODistributedAbstractPlugin dManager, final OServer serverInstance, final String databaseName, final String clusterName) {
    final ODistributedConfiguration cfg = dManager.getDatabaseConfiguration(databaseName);
    final String dbPath = serverInstance.getDatabaseDirectory() + databaseName;
    final String nodeName = dManager.getLocalNodeName();
    final List<String> nodesWhereClusterIsCfg = cfg.getServers(clusterName, null);
    nodesWhereClusterIsCfg.remove(nodeName);
    if (nodesWhereClusterIsCfg.isEmpty())
        throw new OCommandExecutionException("Cannot synchronize cluster '" + clusterName + "' because is not configured on any running nodes");
    final OSyncClusterTask task = new OSyncClusterTask(clusterName);
    final ODistributedResponse response = dManager.sendRequest(databaseName, null, nodesWhereClusterIsCfg, task, dManager.getNextMessageIdCounter(), ODistributedRequest.EXECUTION_MODE.RESPONSE, null, null);
    final Map<String, Object> results = (Map<String, Object>) response.getPayload();
    File tempFile = null;
    FileOutputStream out = null;
    try {
        tempFile = new File(Orient.getTempPath() + "/backup_" + databaseName + "_" + clusterName + "_toInstall.zip");
        if (tempFile.exists())
            tempFile.delete();
        else
            tempFile.getParentFile().mkdirs();
        tempFile.createNewFile();
        long fileSize = 0;
        out = new FileOutputStream(tempFile, false);
        for (Map.Entry<String, Object> r : results.entrySet()) {
            final Object value = r.getValue();
            if (value instanceof Boolean) {
                continue;
            } else if (value instanceof Throwable) {
                ODistributedServerLog.error(null, nodeName, r.getKey(), ODistributedServerLog.DIRECTION.IN, "error on installing cluster %s in %s", (Exception) value, databaseName, dbPath);
            } else if (value instanceof ODistributedDatabaseChunk) {
                ODistributedDatabaseChunk chunk = (ODistributedDatabaseChunk) value;
                // DELETE ANY PREVIOUS .COMPLETED FILE
                final File completedFile = new File(tempFile.getAbsolutePath() + ".completed");
                if (completedFile.exists())
                    completedFile.delete();
                fileSize = writeDatabaseChunk(nodeName, 1, chunk, out);
                for (int chunkNum = 2; !chunk.last; chunkNum++) {
                    final Object result = dManager.sendRequest(databaseName, null, OMultiValue.getSingletonList(r.getKey()), new OCopyDatabaseChunkTask(chunk.filePath, chunkNum, chunk.offset + chunk.buffer.length, false), dManager.getNextMessageIdCounter(), ODistributedRequest.EXECUTION_MODE.RESPONSE, null, null);
                    if (result instanceof Boolean)
                        continue;
                    else if (result instanceof Exception) {
                        ODistributedServerLog.error(null, nodeName, r.getKey(), ODistributedServerLog.DIRECTION.IN, "error on installing database %s in %s (chunk #%d)", (Exception) result, databaseName, dbPath, chunkNum);
                    } else if (result instanceof ODistributedDatabaseChunk) {
                        chunk = (ODistributedDatabaseChunk) result;
                        fileSize += writeDatabaseChunk(nodeName, chunkNum, chunk, out);
                    }
                }
                out.flush();
                // CREATE THE .COMPLETED FILE TO SIGNAL EOF
                new File(tempFile.getAbsolutePath() + ".completed").createNewFile();
            }
        }
        final String tempDirectoryPath = Orient.getTempPath() + "/backup_" + databaseName + "_" + clusterName + "_toInstall";
        final File tempDirectory = new File(tempDirectoryPath);
        tempDirectory.mkdirs();
        OZIPCompressionUtil.uncompressDirectory(new FileInputStream(tempFile), tempDirectory.getAbsolutePath(), null);
        ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
        final boolean openDatabaseHere = db == null;
        if (db == null)
            db = serverInstance.openDatabase("plocal:" + dbPath, "", "", null, true);
        try {
            final OAbstractPaginatedStorage stg = (OAbstractPaginatedStorage) db.getStorage().getUnderlying();
            // TODO: FREEZE COULD IT NOT NEEDED
            stg.freeze(false);
            try {
                final OPaginatedCluster cluster = (OPaginatedCluster) stg.getClusterByName(clusterName);
                final File tempClusterFile = new File(tempDirectoryPath + "/" + clusterName + OPaginatedCluster.DEF_EXTENSION);
                cluster.replaceFile(tempClusterFile);
            } finally {
                stg.release();
            }
            db.getLocalCache().invalidate();
        } finally {
            if (openDatabaseHere)
                db.close();
        }
        return String.format("Cluster correctly replaced, transferred %d bytes", fileSize);
    } catch (Exception e) {
        ODistributedServerLog.error(null, nodeName, null, ODistributedServerLog.DIRECTION.NONE, "error on transferring database '%s' to '%s'", e, databaseName, tempFile);
        throw OException.wrapException(new ODistributedException("Error on transferring database"), e);
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
        }
    }
}
Also used : ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) OCopyDatabaseChunkTask(com.orientechnologies.orient.server.distributed.impl.task.OCopyDatabaseChunkTask) OPaginatedCluster(com.orientechnologies.orient.core.storage.impl.local.paginated.OPaginatedCluster) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OAbstractPaginatedStorage(com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage) IOException(java.io.IOException) OSyncClusterTask(com.orientechnologies.orient.server.distributed.impl.task.OSyncClusterTask) OException(com.orientechnologies.common.exception.OException) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) ODistributedDatabaseChunk(com.orientechnologies.orient.server.distributed.impl.ODistributedDatabaseChunk) Map(java.util.Map) File(java.io.File)

Aggregations

OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)82 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)20 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)19 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)16 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)15 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)14 OException (com.orientechnologies.common.exception.OException)9 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)9 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)6 IOException (java.io.IOException)6 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)5 OType (com.orientechnologies.orient.core.metadata.schema.OType)5 OQueryParsingException (com.orientechnologies.orient.core.exception.OQueryParsingException)4 OSchema (com.orientechnologies.orient.core.metadata.schema.OSchema)4 ORecord (com.orientechnologies.orient.core.record.ORecord)4 OHazelcastPlugin (com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin)4 OrientVertex (com.tinkerpop.blueprints.impls.orient.OrientVertex)4 ArrayList (java.util.ArrayList)4 ORID (com.orientechnologies.orient.core.id.ORID)3 ORecordId (com.orientechnologies.orient.core.id.ORecordId)3