Search in sources :

Example 41 with OCommandRequestText

use of com.orientechnologies.orient.core.command.OCommandRequestText in project orientdb by orientechnologies.

the class OCommandExecutorSQLDeleteVertex method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLDeleteVertex parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        // System.out.println("NEW PARSER FROM: " + queryText);
        queryText = preParse(queryText, iRequest);
        // System.out.println("NEW PARSER TO: " + queryText);
        textRequest.setText(queryText);
        database = getDatabase();
        init((OCommandRequestText) iRequest);
        parserRequiredKeyword("DELETE");
        parserRequiredKeyword("VERTEX");
        OClass clazz = null;
        String where = null;
        int limit = -1;
        String word = parseOptionalWord(true);
        while (word != null) {
            if (word.startsWith("#")) {
                rid = new ORecordId(word);
            } else if (word.equalsIgnoreCase("from")) {
                final StringBuilder q = new StringBuilder();
                final int newPos = OStringSerializerHelper.getEmbedded(parserText, parserGetCurrentPosition(), -1, q);
                query = database.command(new OSQLAsynchQuery<ODocument>(q.toString(), this));
                parserSetCurrentPosition(newPos);
            } else if (word.equals(KEYWORD_WHERE)) {
                if (clazz == null)
                    // ASSIGN DEFAULT CLASS
                    clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(OrientVertexType.CLASS_NAME);
                where = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetPreviousPosition()) : "";
                query = database.command(new OSQLAsynchQuery<ODocument>("select from `" + clazz.getName() + "`" + where, this));
                break;
            } else if (word.equals(KEYWORD_LIMIT)) {
                word = parseOptionalWord(true);
                try {
                    limit = Integer.parseInt(word);
                } catch (Exception e) {
                    throw OException.wrapException(new OCommandSQLParsingException("Invalid LIMIT: " + word), e);
                }
            } else if (word.equals(KEYWORD_RETURN)) {
                returning = parseReturn();
            } else if (word.equals(KEYWORD_BATCH)) {
                word = parserNextWord(true);
                if (word != null)
                    batch = Integer.parseInt(word);
            } else if (word.length() > 0) {
                // GET/CHECK CLASS NAME
                clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(word);
                if (clazz == null)
                    throw new OCommandSQLParsingException("Class '" + word + "' was not found");
            }
            word = parseOptionalWord(true);
            if (parserIsEnded())
                break;
        }
        if (where == null)
            where = "";
        else
            where = " WHERE " + where;
        if (query == null && rid == null) {
            StringBuilder queryString = new StringBuilder();
            queryString.append("select from `");
            if (clazz == null) {
                queryString.append(OrientVertexType.CLASS_NAME);
            } else {
                queryString.append(clazz.getName());
            }
            queryString.append("`");
            queryString.append(where);
            if (limit > -1) {
                queryString.append(" LIMIT ").append(limit);
            }
            query = database.command(new OSQLAsynchQuery<ODocument>(queryString.toString(), this));
        }
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OMetadataInternal(com.orientechnologies.orient.core.metadata.OMetadataInternal) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OException(com.orientechnologies.common.exception.OException) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 42 with OCommandRequestText

use of com.orientechnologies.orient.core.command.OCommandRequestText in project orientdb by orientechnologies.

the class OClientConnectionManager method cleanExpiredConnections.

public void cleanExpiredConnections() {
    final Iterator<Entry<Integer, OClientConnection>> iterator = connections.entrySet().iterator();
    while (iterator.hasNext()) {
        final Entry<Integer, OClientConnection> entry = iterator.next();
        final Socket socket;
        if (entry.getValue().getProtocol() == null || entry.getValue().getProtocol().getChannel() == null)
            socket = null;
        else
            socket = entry.getValue().getProtocol().getChannel().socket;
        if (socket == null || socket.isClosed() || socket.isInputShutdown()) {
            OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)", entry.getKey(), socket);
            try {
                OCommandRequestText command = entry.getValue().getData().command;
                if (command != null && command.isIdempotent()) {
                    entry.getValue().getProtocol().sendShutdown();
                    entry.getValue().getProtocol().interrupt();
                }
                entry.getValue().close();
            } catch (Exception e) {
                OLogManager.instance().error(this, "Error during close of connection for close channel", e);
            }
            iterator.remove();
        } else if (Boolean.TRUE.equals(entry.getValue().getTokenBased())) {
            if (entry.getValue().getToken() != null && !entry.getValue().getToken().isNowValid() && !entry.getValue().getToken().getIsValid()) {
                // Close the current session but not the network because can be used by another session.
                entry.getValue().close();
                iterator.remove();
            }
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Entry(java.util.Map.Entry) OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) OException(com.orientechnologies.common.exception.OException) OTokenSecurityException(com.orientechnologies.orient.enterprise.channel.binary.OTokenSecurityException) IOException(java.io.IOException)

Example 43 with OCommandRequestText

use of com.orientechnologies.orient.core.command.OCommandRequestText in project orientdb by orientechnologies.

the class OServerCommandPostBatch method execute.

@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    checkSyntax(iRequest.url, 2, "Syntax error: batch/<database>");
    iRequest.data.commandInfo = "Execute multiple requests in one shot";
    ODatabaseDocument db = null;
    ODocument batch = null;
    Object lastResult = null;
    try {
        db = getProfiledDatabaseInstance(iRequest);
        if (db.getTransaction().isActive()) {
            // TEMPORARY PATCH TO UNDERSTAND WHY UNDER HIGH LOAD TX IS NOT COMMITTED AFTER BATCH. MAYBE A PENDING TRANSACTION?
            OLogManager.instance().warn(this, "Found database instance from the pool with a pending transaction. Forcing rollback before using it");
            db.rollback(true);
        }
        batch = new ODocument().fromJSON(iRequest.content);
        Boolean tx = batch.field("transaction");
        if (tx == null)
            tx = false;
        final Collection<Map<Object, Object>> operations;
        try {
            operations = batch.field("operations");
        } catch (Exception e) {
            throw new IllegalArgumentException("Expected 'operations' field as a collection of objects", e);
        }
        if (operations == null || operations.isEmpty())
            throw new IllegalArgumentException("Input JSON has no operations to execute");
        boolean txBegun = false;
        if (tx && !db.getTransaction().isActive()) {
            db.begin();
            txBegun = true;
        }
        // BROWSE ALL THE OPERATIONS
        for (Map<Object, Object> operation : operations) {
            final String type = (String) operation.get("type");
            if (type.equals("c")) {
                // CREATE
                final ODocument doc = getRecord(operation);
                doc.save();
                lastResult = doc;
            } else if (type.equals("u")) {
                // UPDATE
                final ODocument doc = getRecord(operation);
                doc.save();
                lastResult = doc;
            } else if (type.equals("d")) {
                // DELETE
                final ODocument doc = getRecord(operation);
                db.delete(doc.getIdentity());
                lastResult = doc.getIdentity();
            } else if (type.equals("cmd")) {
                // COMMAND
                final String language = (String) operation.get("language");
                if (language == null)
                    throw new IllegalArgumentException("language parameter is null");
                final Object command = operation.get("command");
                if (command == null)
                    throw new IllegalArgumentException("command parameter is null");
                String commandAsString = null;
                if (command != null)
                    if (OMultiValue.isMultiValue(command)) {
                        for (Object c : OMultiValue.getMultiValueIterable(command)) {
                            if (commandAsString == null)
                                commandAsString = c.toString();
                            else
                                commandAsString += ";" + c.toString();
                        }
                    } else
                        commandAsString = command.toString();
                final OCommandRequestText cmd = (OCommandRequestText) OCommandManager.instance().getRequester(language);
                cmd.setText(commandAsString);
                lastResult = db.command(cmd).execute();
            } else if (type.equals("script")) {
                // COMMAND
                final String language = (String) operation.get("language");
                if (language == null)
                    throw new IllegalArgumentException("language parameter is null");
                final Object script = operation.get("script");
                if (script == null)
                    throw new IllegalArgumentException("script parameter is null");
                StringBuilder text = new StringBuilder(1024);
                if (OMultiValue.isMultiValue(script)) {
                    // ENSEMBLE ALL THE SCRIPT LINES IN JUST ONE SEPARATED BY LINEFEED
                    int i = 0;
                    for (Object o : OMultiValue.getMultiValueIterable(script)) {
                        if (o != null) {
                            if (i++ > 0)
                                text.append("\n");
                            text.append(o.toString());
                        }
                    }
                } else
                    text.append(script);
                lastResult = db.command(new OCommandScript(language, text.toString())).execute();
            }
        }
        if (txBegun)
            db.commit();
        try {
            iResponse.writeResult(lastResult);
        } catch (RuntimeException e) {
            OLogManager.instance().error(this, "Error (%s) on serializing result of batch command:\n%s", e, batch.toJSON("prettyPrint"));
            throw e;
        }
    } finally {
        if (db != null)
            db.close();
    }
    return false;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript) Map(java.util.Map) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 44 with OCommandRequestText

use of com.orientechnologies.orient.core.command.OCommandRequestText in project orientdb by orientechnologies.

the class OServerCommandPostCommand method execute.

@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    final String[] urlParts = checkSyntax(iRequest.url, 3, "Syntax error: command/<database>/<language>/<command-text>[/limit][/<fetchPlan>]");
    // TRY TO GET THE COMMAND FROM THE URL, THEN FROM THE CONTENT
    final String language = urlParts.length > 2 ? urlParts[2].trim() : "sql";
    String text = urlParts.length > 3 ? urlParts[3].trim() : iRequest.content;
    final int limit = urlParts.length > 4 ? Integer.parseInt(urlParts[4].trim()) : -1;
    String fetchPlan = urlParts.length > 5 ? urlParts[5] : null;
    final String accept = iRequest.getHeader("accept");
    Object params = null;
    String mode = "resultset";
    if (iRequest.content != null && !iRequest.content.isEmpty()) {
        // CONTENT REPLACES TEXT
        if (iRequest.content.startsWith("{")) {
            // JSON PAYLOAD
            final ODocument doc = new ODocument().fromJSON(iRequest.content);
            text = doc.field("command");
            params = doc.field("parameters");
            if (doc.containsField("mode"))
                mode = doc.field("mode");
            if (params instanceof Collection) {
                final Object[] paramArray = new Object[((Collection) params).size()];
                ((Collection) params).toArray(paramArray);
                params = paramArray;
            }
        } else {
            text = iRequest.content;
        }
    }
    if (text == null)
        throw new IllegalArgumentException("text cannot be null");
    iRequest.data.commandInfo = "Command";
    iRequest.data.commandDetail = text;
    ODatabaseDocument db = null;
    Object response;
    try {
        db = getProfiledDatabaseInstance(iRequest);
        final OCommandRequestText cmd = (OCommandRequestText) OCommandManager.instance().getRequester(language);
        cmd.setText(text);
        cmd.setLimit(limit);
        cmd.setFetchPlan(fetchPlan);
        final OCommandExecutor executor = OCommandManager.instance().getExecutor(cmd);
        executor.setContext(cmd.getContext());
        executor.setProgressListener(cmd.getProgressListener());
        executor.parse(cmd);
        if (!executor.isIdempotent() && iRequest.httpMethod.equals("GET"))
            throw new OCommandExecutionException("Cannot execute non idempotent command using HTTP GET");
        // REQUEST CAN'T MODIFY THE RESULT, SO IT'S CACHEABLE
        cmd.setCacheableResult(true);
        if (params == null) {
            response = db.command(cmd).execute();
        } else {
            response = db.command(cmd).execute(params);
        }
        fetchPlan = executor.getFetchPlan();
        String format = null;
        if (iRequest.parameters.get("format") != null)
            format = iRequest.parameters.get("format");
        if (fetchPlan != null)
            if (format != null)
                format += ",fetchPlan:" + fetchPlan;
            else
                format = "fetchPlan:" + fetchPlan;
        Map<String, Object> additionalContent = null;
        final List<String> tips = (List<String>) executor.getContext().getVariable("tips");
        if (tips != null) {
            additionalContent = new HashMap<String, Object>(1);
            additionalContent.put("warnings", tips);
        }
        if (iRequest.getHeader("TE") != null)
            iResponse.setStreaming(true);
        iResponse.writeResult(response, format, accept, additionalContent, mode);
    } finally {
        if (db != null) {
            db.activateOnCurrentThread();
            db.close();
        }
    }
    return false;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OCommandExecutor(com.orientechnologies.orient.core.command.OCommandExecutor) Collection(java.util.Collection) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) List(java.util.List) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)44 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)12 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)9 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)7 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)5 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)4 OSQLAsynchQuery (com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery)4 OException (com.orientechnologies.common.exception.OException)3 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)3 OCommandExecutor (com.orientechnologies.orient.core.command.OCommandExecutor)2 OQueryParsingException (com.orientechnologies.orient.core.exception.OQueryParsingException)2 ORecordId (com.orientechnologies.orient.core.id.ORecordId)2 OCommandSQLParsingException (com.orientechnologies.orient.core.sql.OCommandSQLParsingException)2 OIdentifier (com.orientechnologies.orient.core.sql.parser.OIdentifier)2 OTokenSecurityException (com.orientechnologies.orient.enterprise.channel.binary.OTokenSecurityException)2 IOException (java.io.IOException)2 Socket (java.net.Socket)2 Entry (java.util.Map.Entry)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Matcher (java.util.regex.Matcher)2