Search in sources :

Example 6 with Neo4jError

use of org.neo4j.server.rest.transactional.error.Neo4jError in project neo4j by neo4j.

the class StatementDeserializer method beginsWithCorrectTokens.

private boolean beginsWithCorrectTokens() throws IOException {
    List<JsonToken> expectedTokens = asList(START_OBJECT, FIELD_NAME, START_ARRAY);
    String expectedField = "statements";
    List<JsonToken> foundTokens = new ArrayList<>();
    for (int i = 0; i < expectedTokens.size(); i++) {
        JsonToken token = input.nextToken();
        if (i == 0 && token == null) {
            return false;
        }
        if (token == FIELD_NAME && !expectedField.equals(input.getText())) {
            addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException(String.format("Unable to deserialize request. " + "Expected first field to be '%s', but was '%s'.", expectedField, input.getText()))));
            return false;
        }
        foundTokens.add(token);
    }
    if (!expectedTokens.equals(foundTokens)) {
        addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException(String.format("Unable to deserialize request. " + "Expected %s, found %s.", expectedTokens, foundTokens))));
        return false;
    }
    return true;
}
Also used : Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) ArrayList(java.util.ArrayList) JsonToken(org.codehaus.jackson.JsonToken)

Example 7 with Neo4jError

use of org.neo4j.server.rest.transactional.error.Neo4jError in project neo4j by neo4j.

the class TransactionHandle method executeStatements.

private void executeStatements(StatementDeserializer statements, ExecutionResultSerializer output, List<Neo4jError> errors, HttpServletRequest request) {
    try {
        boolean hasPrevious = false;
        while (statements.hasNext()) {
            Statement statement = statements.next();
            try {
                boolean hasPeriodicCommit = engine.isPeriodicCommit(statement.statement());
                if ((statements.hasNext() || hasPrevious) && hasPeriodicCommit) {
                    throw new QueryExecutionKernelException(new InvalidSemanticsException("Cannot execute another statement after executing " + "PERIODIC COMMIT statement in the same transaction"));
                }
                if (!hasPrevious && hasPeriodicCommit) {
                    context.closeTransactionForPeriodicCommit();
                }
                hasPrevious = true;
                TransactionalContext tc = txManagerFacade.create(request, queryService, type, securityContext, statement.statement(), statement.parameters());
                Result result = safelyExecute(statement, hasPeriodicCommit, tc);
                output.statementResult(result, statement.includeStats(), statement.resultDataContents());
                output.notifications(result.getNotifications());
            } catch (KernelException | CypherException | AuthorizationViolationException | WriteOperationsNotAllowedException e) {
                errors.add(new Neo4jError(e.status(), e));
                break;
            } catch (DeadlockDetectedException e) {
                errors.add(new Neo4jError(Status.Transaction.DeadlockDetected, e));
            } catch (IOException e) {
                errors.add(new Neo4jError(Status.Network.CommunicationError, e));
                break;
            } catch (Exception e) {
                Throwable cause = e.getCause();
                if (cause instanceof Status.HasStatus) {
                    errors.add(new Neo4jError(((Status.HasStatus) cause).status(), cause));
                } else {
                    errors.add(new Neo4jError(Status.Statement.ExecutionFailed, e));
                }
                break;
            }
        }
        addToCollection(statements.errors(), errors);
    } catch (Throwable e) {
        errors.add(new Neo4jError(Status.General.UnknownError, e));
    }
}
Also used : InvalidSemanticsException(org.neo4j.cypher.InvalidSemanticsException) Status(org.neo4j.kernel.api.exceptions.Status) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) DeadlockDetectedException(org.neo4j.kernel.DeadlockDetectedException) IOException(java.io.IOException) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) TransactionFailureException(org.neo4j.kernel.api.exceptions.TransactionFailureException) CypherException(org.neo4j.cypher.CypherException) DeadlockDetectedException(org.neo4j.kernel.DeadlockDetectedException) IOException(java.io.IOException) KernelException(org.neo4j.kernel.api.exceptions.KernelException) InvalidSemanticsException(org.neo4j.cypher.InvalidSemanticsException) AuthorizationViolationException(org.neo4j.graphdb.security.AuthorizationViolationException) WriteOperationsNotAllowedException(org.neo4j.graphdb.security.WriteOperationsNotAllowedException) Result(org.neo4j.graphdb.Result) WriteOperationsNotAllowedException(org.neo4j.graphdb.security.WriteOperationsNotAllowedException) Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) CypherException(org.neo4j.cypher.CypherException) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) KernelException(org.neo4j.kernel.api.exceptions.KernelException) AuthorizationViolationException(org.neo4j.graphdb.security.AuthorizationViolationException)

Example 8 with Neo4jError

use of org.neo4j.server.rest.transactional.error.Neo4jError in project neo4j by neo4j.

the class ExecutionResultSerializer method errors.

/**
     * Will get called once if any errors occurred, after {@link #statementResult(org.neo4j.graphdb.Result, boolean, ResultDataContent...)}  statementResults}
     * has been called This method is not allowed to throw exceptions. If there are network errors or similar, the
     * handler should take appropriate action, but never fail this method.
     * @param errors the errors to write
     */
public void errors(Iterable<? extends Neo4jError> errors) {
    try {
        ensureDocumentOpen();
        ensureResultsFieldClosed();
        out.writeArrayFieldStart("errors");
        try {
            for (Neo4jError error : errors) {
                try {
                    out.writeStartObject();
                    out.writeObjectField("code", error.status().code().serialize());
                    out.writeObjectField("message", error.getMessage());
                    if (error.shouldSerializeStackTrace()) {
                        out.writeObjectField("stackTrace", error.getStackTraceAsString());
                    }
                } finally {
                    out.writeEndObject();
                }
            }
        } finally {
            out.writeEndArray();
            currentState = State.ERRORS_WRITTEN;
        }
    } catch (IOException e) {
        loggedIOException(e);
    }
}
Also used : Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) IOException(java.io.IOException)

Example 9 with Neo4jError

use of org.neo4j.server.rest.transactional.error.Neo4jError in project neo4j by neo4j.

the class UserService method setPassword.

@POST
@Path("/{username}/password")
public Response setPassword(@PathParam("username") String username, @Context HttpServletRequest req, String payload) {
    Principal principal = req.getUserPrincipal();
    if (principal == null || !principal.getName().equals(username)) {
        return output.notFound();
    }
    final Map<String, Object> deserialized;
    try {
        deserialized = input.readMap(payload);
    } catch (BadInputException e) {
        return output.response(BAD_REQUEST, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, e.getMessage())));
    }
    Object o = deserialized.get(PASSWORD);
    if (o == null) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, String.format("Required parameter '%s' is missing.", PASSWORD))));
    }
    if (!(o instanceof String)) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, String.format("Expected '%s' to be a string.", PASSWORD))));
    }
    String newPassword = (String) o;
    try {
        SecurityContext securityContext = getSecurityContextFromUserPrincipal(principal);
        if (securityContext == null) {
            return output.notFound();
        } else {
            UserManager userManager = userManagerSupplier.getUserManager(securityContext);
            userManager.setUserPassword(username, newPassword, false);
        }
    } catch (IOException e) {
        return output.serverErrorWithoutLegacyStacktrace(e);
    } catch (InvalidArgumentsException e) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(e.status(), e.getMessage())));
    }
    return output.ok();
}
Also used : Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) ExceptionRepresentation(org.neo4j.server.rest.repr.ExceptionRepresentation) BadInputException(org.neo4j.server.rest.repr.BadInputException) UserManager(org.neo4j.kernel.api.security.UserManager) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) IOException(java.io.IOException) InvalidArgumentsException(org.neo4j.kernel.api.exceptions.InvalidArgumentsException) AuthorizedRequestWrapper.getSecurityContextFromUserPrincipal(org.neo4j.server.rest.dbms.AuthorizedRequestWrapper.getSecurityContextFromUserPrincipal) Principal(java.security.Principal) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 10 with Neo4jError

use of org.neo4j.server.rest.transactional.error.Neo4jError in project neo4j by neo4j.

the class StatementDeserializer method fetchNextOrNull.

@Override
protected Statement fetchNextOrNull() {
    try {
        if (errors != null) {
            return null;
        }
        switch(state) {
            case BEFORE_OUTER_ARRAY:
                if (!beginsWithCorrectTokens()) {
                    return null;
                }
                state = State.IN_BODY;
            case IN_BODY:
                String statement = null;
                Map<String, Object> parameters = null;
                List<Object> resultsDataContents = null;
                boolean includeStats = false;
                JsonToken tok;
                while ((tok = input.nextToken()) != null && tok != END_OBJECT) {
                    if (tok == END_ARRAY) {
                        // No more statements
                        state = State.FINISHED;
                        return null;
                    }
                    input.nextValue();
                    String currentName = input.getCurrentName();
                    switch(currentName) {
                        case "statement":
                            statement = input.readValueAs(String.class);
                            break;
                        case "parameters":
                            parameters = readMap(input);
                            break;
                        case "resultDataContents":
                            resultsDataContents = readArray(input);
                            break;
                        case "includeStats":
                            includeStats = input.getBooleanValue();
                            break;
                        default:
                            discardValue(input);
                    }
                }
                if (statement == null) {
                    addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException("No statement provided.")));
                    return null;
                }
                return new Statement(statement, parameters == null ? NO_PARAMETERS : parameters, includeStats, ResultDataContent.fromNames(resultsDataContents));
            case FINISHED:
                return null;
            default:
                break;
        }
        return null;
    } catch (JsonParseException | JsonMappingException e) {
        addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException("Unable to deserialize request", e)));
        return null;
    } catch (IOException e) {
        addError(new Neo4jError(Status.Network.CommunicationError, e));
        return null;
    } catch (Exception e) {
        addError(new Neo4jError(Status.General.UnknownError, e));
        return null;
    }
}
Also used : IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) JsonToken(org.codehaus.jackson.JsonToken)

Aggregations

Neo4jError (org.neo4j.server.rest.transactional.error.Neo4jError)14 IOException (java.io.IOException)8 Test (org.junit.Test)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 Neo4jJsonCodecTest (org.neo4j.server.rest.transactional.Neo4jJsonCodecTest)6 Result (org.neo4j.graphdb.Result)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 ThrowsException (org.mockito.internal.stubbing.answers.ThrowsException)4 JsonParseException (org.neo4j.server.rest.domain.JsonParseException)4 JsonToken (org.codehaus.jackson.JsonToken)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 JsonParseException (org.codehaus.jackson.JsonParseException)1 JsonMappingException (org.codehaus.jackson.map.JsonMappingException)1 CypherException (org.neo4j.cypher.CypherException)1 InvalidSemanticsException (org.neo4j.cypher.InvalidSemanticsException)1 AuthorizationViolationException (org.neo4j.graphdb.security.AuthorizationViolationException)1