Package com.tinkerpop.rexster.extension

Examples of com.tinkerpop.rexster.extension.ExtensionMethod


    @Test
    public void findExtensionMethodMultipleRootCheck() {
        List<RexsterExtension> rexsterExtensions = new ArrayList<RexsterExtension>();
        rexsterExtensions.add(new MockMultiRootRexsterExtension());
        ExtensionMethod m = this.mockResource.findExtensionMethodExposed(rexsterExtensions, ExtensionPoint.GRAPH, "", HttpMethod.GET);
        Assert.assertNotNull(m);

        Method methodFound = m.getMethod();
        Assert.assertNotNull(methodFound);
        Assert.assertEquals("doRootGet", methodFound.getName());

        // validates that the second method will get found
        m = this.mockResource.findExtensionMethodExposed(rexsterExtensions, ExtensionPoint.GRAPH, "", HttpMethod.POST);
        Assert.assertNotNull(m);

        methodFound = m.getMethod();
        Assert.assertNotNull(methodFound);
        Assert.assertEquals("doRootPost", methodFound.getName());
    }
View Full Code Here


    @Test
    public void findExtensionMethodFoundSpecificActionAndMethod() {
        List<RexsterExtension> rexsterExtensions = new ArrayList<RexsterExtension>();
        rexsterExtensions.add(new MockRexsterExtension());
        ExtensionMethod m = this.mockResource.findExtensionMethodExposed(rexsterExtensions, ExtensionPoint.GRAPH, "headonly", HttpMethod.HEAD);
        Assert.assertNotNull(m);

        Method methodFound = m.getMethod();
        Assert.assertNotNull(methodFound);
        Assert.assertEquals("headAccessOnly", methodFound.getName());
    }
View Full Code Here

        this.mockery.checking(new Expectations() {{
            allowing(extensionDefinition).tryIncludeRexsterAttributes();
            will(returnValue(false));
        }});

        ExtensionMethod extensionMethod = new ExtensionMethod(null, extensionDefinition, null, new MockRexsterExtension());
        ExtensionResponse extResponse = this.mockResource.tryAppendRexsterAttributesIfJsonExposed(
                responseFromExtension, extensionMethod, MediaType.APPLICATION_JSON);

        Assert.assertNotNull(extResponse);
        Assert.assertEquals(responseFromExtension, extResponse);
View Full Code Here

        this.mockery.checking(new Expectations() {{
            allowing(extensionDefinition).tryIncludeRexsterAttributes();
            will(returnValue(true));
        }});

        ExtensionMethod extensionMethod = new ExtensionMethod(null, extensionDefinition, null, new MockRexsterExtension());
        ExtensionResponse extResponse = this.mockResource.tryAppendRexsterAttributesIfJsonExposed(
                responseFromExtension, extensionMethod, MediaType.APPLICATION_JSON);

        Assert.assertNotNull(extResponse);
        Assert.assertEquals(responseFromExtension, extResponse);
View Full Code Here

        this.mockery.checking(new Expectations() {{
            allowing(extensionDefinition).tryIncludeRexsterAttributes();
            will(returnValue(true));
        }});

        ExtensionMethod extensionMethod = new ExtensionMethod(null, extensionDefinition, null, new MockRexsterExtension());
        ExtensionResponse extResponse = this.mockResource.tryAppendRexsterAttributesIfJsonExposed(
                responseFromExtension, extensionMethod, MediaType.APPLICATION_JSON);

        Assert.assertNotNull(extResponse);
View Full Code Here

    }

    private Response executeGraphExtension(final String graphName, final HttpMethod httpMethodRequested) {

        ExtensionResponse extResponse;
        ExtensionMethod methodToCall;
        final ExtensionSegmentSet extensionSegmentSet = parseUriForExtensionSegment(graphName, ExtensionPoint.GRAPH);

        // determine if the namespace and extension are enabled for this graph
        final RexsterApplicationGraph rag = this.getRexsterApplicationGraph(graphName);

        if (rag.isExtensionAllowed(extensionSegmentSet)) {

            Object returnValue = null;

            // namespace was allowed so try to run the extension
            try {

                // look for the extension as loaded through serviceloader
                List<RexsterExtension> rexsterExtensions = null;
                try {
                    rexsterExtensions = findExtensionClasses(extensionSegmentSet);
                } catch (ServiceConfigurationError sce) {
                    logger.error("ServiceLoader could not find a class referenced in com.tinkerpop.rexster.extension.RexsterExtension.");
                    final JSONObject error = generateErrorObject(
                            "Class specified in com.tinkerpop.rexster.extension.RexsterExtension could not be found.",
                            sce);
                    throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity(error).build());
                }

                if (rexsterExtensions == null || rexsterExtensions.size() == 0) {
                    // extension was not found for some reason
                    logger.error("The [" + extensionSegmentSet + "] extension was not found for [" + graphName + "].  Check com.tinkerpop.rexster.extension.RexsterExtension file in META-INF.services.");
                    final JSONObject error = generateErrorObject(
                            "The [" + extensionSegmentSet + "] extension was not found for [" + graphName + "]");
                    throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity(error).build());
                }

                // look up the method on the extension that needs to be called.
                methodToCall = findExtensionMethod(rexsterExtensions, ExtensionPoint.GRAPH, extensionSegmentSet.getExtensionMethod(), httpMethodRequested);

                if (methodToCall == null) {
                    // extension method was not found for some reason
                    if (httpMethodRequested == HttpMethod.OPTIONS) {
                        // intercept the options call and return the standard business
                        // no need to stop the transaction here
                        return buildOptionsResponse();
                    }

                    logger.error("The [" + extensionSegmentSet + "] extension was not found for [" + graphName + "] with a HTTP method of [" + httpMethodRequested.name() + "].  Check com.tinkerpop.rexster.extension.RexsterExtension file in META-INF.services.");
                    final JSONObject error = generateErrorObject(
                            "The [" + extensionSegmentSet + "] extension was not found for [" + graphName + "] with a HTTP method of [" + httpMethodRequested.name() + "]");
                    throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity(error).build());
                }

                // found the method...time to do work
                returnValue = invokeExtension(rag, methodToCall);
                rag.tryCommit();

            } catch (WebApplicationException wae) {
                // already logged this...just throw it  up.
                rag.tryRollback();
                throw wae;
            } catch (Exception ex) {
                logger.error("Dynamic invocation of the [" + extensionSegmentSet + "] extension failed.", ex);

                if (ex.getCause() != null) {
                    final Throwable cause = ex.getCause();
                    logger.error("It would be smart to trap this this exception within the extension and supply a good response to the user:" + cause.getMessage(), cause);
                }

                rag.tryRollback();

                final JSONObject error = generateErrorObjectJsonFail(ex);
                throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build());
            }

            if (returnValue instanceof ExtensionResponse) {
                extResponse = (ExtensionResponse) returnValue;

                if (extResponse.isErrorResponse()) {
                    // an error was raised within the extension.  pass it back out as an error.
                    logger.warn("The [" + extensionSegmentSet + "] extension raised an error response.");

                    if (methodToCall.getExtensionDefinition().autoCommitTransaction()) {
                        rag.tryRollback();
                    }

                    throw new WebApplicationException(Response.fromResponse(extResponse.getJerseyResponse()).build());
                }

                if (methodToCall.getExtensionDefinition().autoCommitTransaction()) {
                    rag.tryCommit();
                }
            } else {
                // extension method is not returning the correct type...needs to be an ExtensionResponse
                logger.error("The [" + extensionSegmentSet + "] extension does not return an ExtensionResponse.");
                final JSONObject error = generateErrorObject(
                        "The [" + extensionSegmentSet + "] extension does not return an ExtensionResponse.");
                throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build());
            }

        } else {
            // namespace was not allowed
            logger.error("The [" + extensionSegmentSet + "] extension was not configured for [" + graphName + "]");
            final JSONObject error = generateErrorObject(
                    "The [" + extensionSegmentSet + "] extension was not configured for [" + graphName + "]");
            throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build());
        }

        String mediaType = MediaType.APPLICATION_JSON;
        if (methodToCall != null) {
            mediaType = methodToCall.getExtensionDefinition().produces();
            extResponse = tryAppendRexsterAttributesIfJson(extResponse, methodToCall, mediaType);
        }

        return Response.fromResponse(extResponse.getJerseyResponse()).type(mediaType).build();
    }
View Full Code Here

        placeParametersOnBinding(requestObject, bindings, showTypes);

        // get the list of "stored procedures" to run
        final RexsterApplicationGraph rag = rexsterResourceContext.getRexsterApplicationGraph();

        final ExtensionMethod extensionMethod = rexsterResourceContext.getExtensionMethod();
        Map configurationMap = null;

        Iterator<String> scriptsToRun = null;
        try {
            final ExtensionConfiguration extensionConfiguration = rag != null ? rag.findExtensionConfiguration(EXTENSION_NAMESPACE, EXTENSION_NAME) : null;
            if (extensionConfiguration != null) {
                configurationMap = extensionConfiguration.tryGetMapFromConfiguration();
                scriptsToRun = getScriptsToRun(requestObject, configurationMap);
            }
        } catch (IOException ioe) {
            return ExtensionResponse.error(ioe,
                    generateErrorJson(extensionMethod.getExtensionApiAsJson()));
        }

        if ((script == null || script.isEmpty()) && scriptsToRun == null) {
            return ExtensionResponse.badRequest(
                    "no scripts provided",
                    generateErrorJson(extensionMethod.getExtensionApiAsJson()));
        }

        final Timer.Context context = scriptTimer.time();
        try {
            // result is either the ad-hoc script on the query string or the last "stored procedure"
            Object result = null;
            if (scriptsToRun != null) {
                while (scriptsToRun.hasNext()) {
                    result = engineHolder.getEngine().eval(scriptsToRun.next(), bindings);
                }
            }

            if (isClientScriptAllowed(configurationMap) && script != null && !script.isEmpty()) {
                result = engineHolder.getEngine().eval(script, bindings);
            }

            final Pair<JSONArray, Long> convertedResults = new JSONResultConverter(mode, offsetStart, offsetEnd, returnKeys).convert(result, returnTotal);
            final JSONArray results = convertedResults.getA();

            final HashMap<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put(Tokens.SUCCESS, true);
            resultMap.put(Tokens.RESULTS, results);
            if (returnTotal)
                resultMap.put(Tokens.COUNT, convertedResults.getB());

            final JSONObject resultObject = new JSONObject(resultMap);
            extensionResponse = ExtensionResponse.ok(resultObject);

            successfulExecutions.inc();

        } catch (Exception e) {
            logger.error(String.format("Gremlin Extension: %s", e.getMessage()), e);
            extensionResponse = ExtensionResponse.error(e,
                    generateErrorJson(extensionMethod.getExtensionApiAsJson()));

            failedExecutions.inc();
        } finally {
            context.stop();
        }
View Full Code Here

            })
    public ExtensionResponse evaluateSparql(@RexsterContext final RexsterResourceContext context,
                                            @RexsterContext final Graph graph,
                                            @ExtensionRequestParameter(name = "query", description = API_QUERY) final String queryString) {
        if (queryString == null || queryString.isEmpty()) {
            final ExtensionMethod extMethod = context.getExtensionMethod();
            return ExtensionResponse.error(
                    "the query parameter cannot be empty",
                    null,
                    Response.Status.BAD_REQUEST.getStatusCode(),
                    null,
                    generateErrorJson(extMethod.getExtensionApiAsJson()));
        }

        final JSONObject requestObject = context.getRequestObject();
        final boolean showTypes = RequestObjectHelper.getShowTypes(requestObject);
        final GraphSONMode mode = showTypes ? GraphSONMode.EXTENDED : GraphSONMode.NORMAL;
        final Set<String> returnKeys = RequestObjectHelper.getReturnKeys(requestObject, WILDCARD);

        if (!(graph instanceof SailGraph)) {
            final ExtensionMethod extMethod = context.getExtensionMethod();
            return ExtensionResponse.error(
                    "the graph to which this extension is applied is not a SailGraph implementation",
                    null,
                    Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                    null,
                    generateErrorJson(extMethod.getExtensionApiAsJson()));
        }

        try {

            final SailGraph sailGraph = (SailGraph) graph;
View Full Code Here

    @ExtensionDescriptor(description = "a simple ping extension.")
    public ExtensionResponse evaluatePing(@RexsterContext RexsterResourceContext context,
                                          @RexsterContext Graph graph,
                                          @ExtensionRequestParameter(name = "reply", defaultValue = "pong (default)", description = "a value to reply with") String reply) {
        if (reply == null || reply.isEmpty()) {
            ExtensionMethod extMethod = context.getExtensionMethod();
            return ExtensionResponse.error(
                    "the reply parameter cannot be empty",
                    null,
                    Response.Status.BAD_REQUEST.getStatusCode(),
                    null,
                    generateErrorJson(extMethod.getExtensionApiAsJson()));
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("ping", reply);
        return ExtensionResponse.ok(map);
View Full Code Here

    @ExtensionDescriptor(description = "a simple ping extension.")
    public ExtensionResponse evaluatePing(@RexsterContext RexsterResourceContext context,
                                          @RexsterContext Graph graph,
                                          @ExtensionRequestParameter(name = "reply", description = "a value to reply with") String reply) {
        if (reply == null || reply.isEmpty()) {
            ExtensionMethod extMethod = context.getExtensionMethod();
            return ExtensionResponse.error(
                    "the reply parameter cannot be empty",
                    null,
                    Response.Status.BAD_REQUEST.getStatusCode(),
                    null,
                    generateErrorJson(extMethod.getExtensionApiAsJson()));
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("ping-add-on", reply);
        return ExtensionResponse.ok(map);
View Full Code Here

TOP

Related Classes of com.tinkerpop.rexster.extension.ExtensionMethod

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.