Search in sources :

Example 56 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContinuousIntegrationTest method testRunBuild.

@Test
public void testRunBuild() {
    //START SNIPPET: query-list-and-command
    crc.onResource(new ResultHandler<Resource>() {

        @Override
        public HandlerCommand handleResult(Resource result, ContextResourceClient client) {
            return query("runbuild");
        }
    }).onQuery("runbuild", new ResultHandler<Links>() {

        @Override
        public HandlerCommand handleResult(Links result, ContextResourceClient client) {
            Link link = LinksUtil.withId("any", result);
            return command(link);
        }
    }).onCommand("runbuild", new ResponseHandler() {

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            System.out.println("Done");
            return null;
        }
    });
    crc.start();
//END SNIPPET: query-list-and-command
}
Also used : HandlerCommand(org.qi4j.library.rest.client.api.HandlerCommand) Response(org.restlet.Response) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler) ContextResource(org.qi4j.library.rest.server.api.ContextResource) Resource(org.qi4j.library.rest.common.Resource) Links(org.qi4j.library.rest.common.link.Links) ResultHandler(org.qi4j.library.rest.client.spi.ResultHandler) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) Link(org.qi4j.library.rest.common.link.Link) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 57 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResource method resource.

private void resource() {
    Request request = Request.getCurrent();
    Response response = Response.getCurrent();
    if (!request.getMethod().equals(org.restlet.data.Method.GET)) {
        response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        return;
    }
    ObjectSelection objectSelection = current();
    // Check for interaction->method mappings
    if (ResourceDelete.class.isAssignableFrom(getClass())) {
        response.getAllowedMethods().add(org.restlet.data.Method.DELETE);
    }
    if (ResourceUpdate.class.isAssignableFrom(getClass())) {
        response.getAllowedMethods().add(org.restlet.data.Method.PUT);
    }
    // Construct resource
    ValueBuilder<Resource> builder = module.newValueBuilder(Resource.class);
    List<Link> queriesProperty = builder.prototype().queries().get();
    for (Method query : resourceQueries) {
        if (constraints.isValid(query, objectSelection, module)) {
            ValueBuilder<Link> linkBuilder = module.newValueBuilder(Link.class);
            Link prototype = linkBuilder.prototype();
            prototype.classes().set("query");
            prototype.text().set(humanReadable(query.getName()));
            prototype.href().set(query.getName().toLowerCase());
            prototype.rel().set(query.getName().toLowerCase());
            prototype.id().set(query.getName().toLowerCase());
            queriesProperty.add(linkBuilder.newInstance());
        }
    }
    List<Link> commandsProperty = builder.prototype().commands().get();
    for (Method command : resourceCommands) {
        if (constraints.isValid(command, objectSelection, module)) {
            ValueBuilder<Link> linkBuilder = module.newValueBuilder(Link.class);
            Link prototype = linkBuilder.prototype();
            prototype.classes().set("command");
            prototype.text().set(humanReadable(command.getName()));
            prototype.href().set(command.getName().toLowerCase());
            prototype.rel().set(command.getName().toLowerCase());
            prototype.id().set(command.getName().toLowerCase());
            commandsProperty.add(linkBuilder.newInstance());
        }
    }
    List<Link> resourcesProperty = builder.prototype().resources().get();
    for (Method subResource : subResources.values()) {
        if (constraints.isValid(subResource, objectSelection, module)) {
            ValueBuilder<Link> linkBuilder = module.newValueBuilder(Link.class);
            Link prototype = linkBuilder.prototype();
            prototype.classes().set("resource");
            prototype.text().set(humanReadable(subResource.getName()));
            prototype.href().set(subResource.getName().toLowerCase() + "/");
            prototype.rel().set(subResource.getName().toLowerCase());
            prototype.id().set(subResource.getName().toLowerCase());
            resourcesProperty.add(linkBuilder.newInstance());
        }
    }
    try {
        Method indexMethod = resourceMethodQueries.get("index");
        if (indexMethod != null) {
            Object index = convert(indexMethod.invoke(this));
            if (index != null && index instanceof ValueComposite) {
                builder.prototype().index().set((ValueComposite) index);
            }
        }
    } catch (Throwable e) {
    // Ignore
    }
    try {
        responseWriter.writeResponse(builder.newInstance(), response);
    } catch (Throwable e) {
        handleException(response, e);
    }
}
Also used : Response(org.restlet.Response) Request(org.restlet.Request) Resource(org.qi4j.library.rest.common.Resource) Method(java.lang.reflect.Method) ValueComposite(org.qi4j.api.value.ValueComposite) Link(org.qi4j.library.rest.common.link.Link)

Example 58 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResource method handleQuery.

private void handleQuery(String segment) {
    Request request = Request.getCurrent();
    Response response = Response.getCurrent();
    // Query
    // Try to locate either the query method or command method that should be used
    Method queryMethod = resourceMethodQueries.get(segment);
    if (queryMethod == null) {
        queryMethod = resourceMethodCommands.get(segment);
    }
    if (queryMethod == null) {
        // Not found as interaction, try SubResource
        Method resourceMethod = subResources.get(segment);
        if (resourceMethod != null && resourceMethod.getAnnotation(SubResource.class) != null) {
            // Found it! Redirect to it
            response.setStatus(Status.REDIRECTION_FOUND);
            response.setLocationRef(new Reference(request.getResourceRef().toString() + "/").toString());
            return;
        } else {
            // 404
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        }
    }
    // Check if this is a request to show the form for this interaction
    if ((request.getMethod().isSafe() && queryMethod.getParameterTypes().length != 0 && request.getResourceRef().getQuery() == null) || (!request.getMethod().isSafe() && queryMethod.getParameterTypes().length != 0 && !(request.getEntity().isAvailable() || request.getResourceRef().getQuery() != null || queryMethod.getParameterTypes()[0].equals(Response.class)))) {
        // Show form
        try {
            // Tell client to try again
            response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
            response.getAllowedMethods().add(org.restlet.data.Method.GET);
            response.getAllowedMethods().add(org.restlet.data.Method.POST);
            result(formForMethod(queryMethod));
        } catch (Exception e) {
            handleException(response, e);
        }
    } else {
        // Check timestamps
        ResourceValidity validity = (ResourceValidity) request.getAttributes().get(RESOURCE_VALIDITY);
        if (validity != null) {
            validity.checkRequest();
        }
        // Check method constraints
        if (!constraints.isValid(queryMethod, current(), module)) {
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        }
        try {
            // Create argument
            Object[] arguments;
            if (queryMethod.getParameterTypes().length > 0) {
                try {
                    arguments = requestReader.readRequest(Request.getCurrent(), queryMethod);
                    if (arguments == null) {
                        // Show form
                        result(formForMethod(queryMethod));
                        return;
                    }
                } catch (IllegalArgumentException e) {
                    // Still missing some values - show form
                    result(formForMethod(queryMethod));
                    return;
                }
            } else {
                // No arguments to this query
                arguments = new Object[0];
            }
            // Invoke method
            Request.getCurrent().getAttributes().put(ARGUMENTS, arguments);
            Object result = queryMethod.invoke(this, arguments);
            if (result != null) {
                if (result instanceof Representation) {
                    response.setEntity((Representation) result);
                } else {
                    result(convert(result));
                }
            }
        } catch (Throwable e) {
            handleException(response, e);
        }
    }
}
Also used : Response(org.restlet.Response) Reference(org.restlet.data.Reference) Request(org.restlet.Request) ResourceException(org.restlet.resource.ResourceException) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) Method(java.lang.reflect.Method) EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) ResourceException(org.restlet.resource.ResourceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchEntityException(org.qi4j.api.unitofwork.NoSuchEntityException) ConstraintViolationException(org.qi4j.api.constraint.ConstraintViolationException)

Example 59 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResourceClient method onCommand.

public <T> ContextResourceClient onCommand(String relation, final ResultHandler<T> handler) {
    final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.map(((ParameterizedType) handler.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0]);
    commandHandlers.put(relation, new ResponseHandler() {

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            T result = contextResourceFactory.readResponse(response, resultType);
            return handler.handleResult(result, client);
        }
    });
    return this;
}
Also used : ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) NullResponseHandler(org.qi4j.library.rest.client.spi.NullResponseHandler) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler)

Example 60 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResourceClient method delete.

// Delete
public HandlerCommand delete(ResponseHandler responseHandler, ResponseHandler processingErrorHandler) throws ResourceException {
    if (responseHandler == null)
        responseHandler = deleteHandler;
    Request request = new Request(Method.DELETE, new Reference(reference.toUri()).toString());
    contextResourceFactory.updateCommandRequest(request);
    int tries = 3;
    while (true) {
        Response response = new Response(request);
        try {
            contextResourceFactory.getClient().handle(request, response);
            if (!response.getStatus().isSuccess()) {
                return errorHandler.handleResponse(response, this);
            } else {
                // Reset modification date
                contextResourceFactory.updateCache(response);
                return responseHandler.handleResponse(response, this);
            }
        } catch (ResourceException e) {
            if (e.getStatus().equals(Status.CONNECTOR_ERROR_COMMUNICATION) || e.getStatus().equals(Status.CONNECTOR_ERROR_CONNECTION)) {
                if (tries == 0) {
                    // Give up
                    throw e;
                } else {
                    // Try again
                    tries--;
                    continue;
                }
            } else {
                // Abort
                throw e;
            }
        } finally {
            try {
                response.getEntity().exhaust();
            } catch (Throwable e) {
            // Ignore
            }
        }
    }
}
Also used : ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Reference(org.restlet.data.Reference) Request(org.restlet.Request) ResourceException(org.restlet.resource.ResourceException)

Aggregations

Response (org.restlet.Response)62 Request (org.restlet.Request)44 Test (org.testng.annotations.Test)26 Status (org.restlet.data.Status)17 ChallengeResponse (org.restlet.data.ChallengeResponse)15 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)12 ResponseHandler (org.qi4j.library.rest.client.spi.ResponseHandler)12 Map (java.util.Map)10 Test (org.junit.Test)10 Client (org.restlet.Client)9 Representation (org.restlet.representation.Representation)9 Reference (org.restlet.data.Reference)8 ContextResourceClient (org.qi4j.library.rest.client.api.ContextResourceClient)7 HandlerCommand (org.qi4j.library.rest.client.api.HandlerCommand)7 JacksonRepresentation (org.restlet.ext.jackson.JacksonRepresentation)7 AccessToken (org.forgerock.oauth2.core.AccessToken)6 ResourceException (org.restlet.resource.ResourceException)6 Resource (org.qi4j.library.rest.common.Resource)5 Link (org.qi4j.library.rest.common.link.Link)5 AbstractQi4jTest (org.qi4j.test.AbstractQi4jTest)5