Search in sources :

Example 91 with Representation

use of org.restlet.representation.Representation in project helix by apache.

the class TestHelixAdminScenariosRest method getUrl.

String getUrl(String url) throws IOException {
    Reference resourceRef = new Reference(url);
    Request request = new Request(Method.GET, resourceRef);
    Response response = _gClient.handle(request);
    Representation result = response.getEntity();
    StringWriter sw = new StringWriter();
    result.write(sw);
    return sw.toString();
}
Also used : Response(org.restlet.Response) StringWriter(java.io.StringWriter) Reference(org.restlet.data.Reference) Request(org.restlet.Request) Representation(org.restlet.representation.Representation)

Example 92 with Representation

use of org.restlet.representation.Representation in project helix by apache.

the class TestHelixAdminScenariosRest method assertSuccessPostOperation.

static String assertSuccessPostOperation(String url, Map<String, String> jsonParameters, Map<String, String> extraForm, boolean hasException) throws IOException {
    Reference resourceRef = new Reference(url);
    int numRetries = 0;
    while (numRetries <= MAX_RETRIES) {
        Request request = new Request(Method.POST, resourceRef);
        if (extraForm != null) {
            String entity = JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(jsonParameters);
            for (String key : extraForm.keySet()) {
                entity = entity + "&" + (key + "=" + extraForm.get(key));
            }
            request.setEntity(entity, MediaType.APPLICATION_ALL);
        } else {
            request.setEntity(JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(jsonParameters), MediaType.APPLICATION_ALL);
        }
        Response response = _gClient.handle(request);
        Representation result = response.getEntity();
        StringWriter sw = new StringWriter();
        if (result != null) {
            result.write(sw);
        }
        int code = response.getStatus().getCode();
        boolean successCode = code == Status.SUCCESS_NO_CONTENT.getCode() || code == Status.SUCCESS_OK.getCode();
        if (successCode || numRetries == MAX_RETRIES) {
            Assert.assertTrue(successCode);
            Assert.assertTrue(hasException == sw.toString().toLowerCase().contains("exception"));
            return sw.toString();
        }
        numRetries++;
    }
    Assert.fail("Request failed after all retries");
    return null;
}
Also used : Response(org.restlet.Response) StringWriter(java.io.StringWriter) Reference(org.restlet.data.Reference) Request(org.restlet.Request) Representation(org.restlet.representation.Representation)

Example 93 with Representation

use of org.restlet.representation.Representation 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 94 with Representation

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

the class ContextResource method handleCommand.

private void handleCommand(String segment) {
    Request request = Request.getCurrent();
    Response response = Response.getCurrent();
    // Check if this is a request to show the form for this command
    Method interactionMethod = resourceMethodCommands.get(segment);
    if (shouldShowCommandForm(interactionMethod)) {
        // Show form
        // TODO This should check if method is idempotent
        response.getAllowedMethods().add(org.restlet.data.Method.POST);
        try {
            // Check if there is a query with this name - if so invoke it
            Method queryMethod = resourceMethodQueries.get(segment);
            if (queryMethod != null) {
                result(queryMethod.invoke(this));
            } else {
                request.setMethod(org.restlet.data.Method.POST);
                response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
                result(formForMethod(interactionMethod));
            }
        } 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(interactionMethod, current(), module)) {
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        }
        // Create argument
        Object[] arguments = requestReader.readRequest(Request.getCurrent(), interactionMethod);
        Request.getCurrent().getAttributes().put(ARGUMENTS, arguments);
        // Invoke method
        try {
            Object result = interactionMethod.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) 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 95 with Representation

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

the class DefaultRequestReader method readRequest.

@Override
public Object[] readRequest(Request request, Method method) throws ResourceException {
    if (request.getMethod().equals(org.restlet.data.Method.GET)) {
        Object[] args = new Object[method.getParameterTypes().length];
        Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
        Form entityAsForm = null;
        Representation representation = Request.getCurrent().getEntity();
        if (representation != null && !EmptyRepresentation.class.isInstance(representation)) {
            entityAsForm = new Form(representation);
        } else {
            entityAsForm = new Form();
        }
        if (queryAsForm.isEmpty() && entityAsForm.isEmpty()) {
            // Nothing submitted yet - show form
            return null;
        }
        if (args.length == 1) {
            if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
                Class<?> valueType = method.getParameterTypes()[0];
                args[0] = getValueFromForm((Class<ValueComposite>) valueType, queryAsForm, entityAsForm);
                return args;
            } else if (Form.class.equals(method.getParameterTypes()[0])) {
                args[0] = queryAsForm.isEmpty() ? entityAsForm : queryAsForm;
                return args;
            } else if (Response.class.equals(method.getParameterTypes()[0])) {
                args[0] = Response.getCurrent();
                return args;
            }
        }
        parseMethodArguments(method, args, queryAsForm, entityAsForm);
        return args;
    } else {
        Object[] args = new Object[method.getParameterTypes().length];
        Class<? extends ValueComposite> commandType = (Class<? extends ValueComposite>) method.getParameterTypes()[0];
        if (method.getParameterTypes()[0].equals(Response.class)) {
            return new Object[] { Response.getCurrent() };
        }
        Representation representation = Request.getCurrent().getEntity();
        MediaType type = representation.getMediaType();
        if (type == null) {
            Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm(CharacterSet.UTF_8);
            if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
                args[0] = getValueFromForm(commandType, queryAsForm, new Form());
            } else {
                parseMethodArguments(method, args, queryAsForm, new Form());
            }
            return args;
        } else {
            if (method.getParameterTypes()[0].equals(Representation.class)) {
                // Command method takes Representation as input
                return new Object[] { representation };
            } else if (method.getParameterTypes()[0].equals(Form.class)) {
                // Command method takes Form as input
                return new Object[] { new Form(representation) };
            } else if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
                // Need to parse input into ValueComposite
                if (type.equals(MediaType.APPLICATION_JSON)) {
                    String json = Request.getCurrent().getEntityAsText();
                    if (json == null) {
                        LoggerFactory.getLogger(getClass()).error("Restlet bugg http://restlet.tigris.org/issues/show_bug.cgi?id=843 detected. Notify developers!");
                        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Bug in Tomcat encountered; notify developers!");
                    }
                    Object command = module.newValueFromSerializedState(commandType, json);
                    args[0] = command;
                    return args;
                } else if (type.equals(MediaType.TEXT_PLAIN)) {
                    String text = Request.getCurrent().getEntityAsText();
                    if (text == null) {
                        LoggerFactory.getLogger(getClass()).error("Restlet bugg http://restlet.tigris.org/issues/show_bug.cgi?id=843 detected. Notify developers!");
                        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Bug in Tomcat encountered; notify developers!");
                    }
                    args[0] = text;
                    return args;
                } else if (type.equals((MediaType.APPLICATION_WWW_FORM))) {
                    Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                    Form entityAsForm;
                    if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
                        entityAsForm = new Form(representation);
                    } else {
                        entityAsForm = new Form();
                    }
                    Class<?> valueType = method.getParameterTypes()[0];
                    args[0] = getValueFromForm((Class<ValueComposite>) valueType, queryAsForm, entityAsForm);
                    return args;
                } else {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Command has to be in JSON format");
                }
            } else if (method.getParameterTypes()[0].isInterface() && method.getParameterTypes().length == 1) {
                Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                Form entityAsForm;
                if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
                    entityAsForm = new Form(representation);
                } else {
                    entityAsForm = new Form();
                }
                args[0] = module.currentUnitOfWork().get(method.getParameterTypes()[0], getValue("entity", queryAsForm, entityAsForm));
                return args;
            } else {
                Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
                Form entityAsForm;
                if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
                    entityAsForm = new Form(representation);
                } else {
                    entityAsForm = new Form();
                }
                parseMethodArguments(method, args, queryAsForm, entityAsForm);
                return args;
            }
        }
    }
}
Also used : Form(org.restlet.data.Form) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) MediaType(org.restlet.data.MediaType) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) Representation(org.restlet.representation.Representation) ResourceException(org.restlet.resource.ResourceException) ValueComposite(org.qi4j.api.value.ValueComposite)

Aggregations

Representation (org.restlet.representation.Representation)101 HashMap (java.util.HashMap)28 Test (org.testng.annotations.Test)27 StringRepresentation (org.restlet.representation.StringRepresentation)24 Request (org.restlet.Request)23 Response (org.restlet.Response)23 JacksonRepresentation (org.restlet.ext.jackson.JacksonRepresentation)23 ResourceException (org.restlet.resource.ResourceException)21 Reference (org.restlet.data.Reference)19 StringWriter (java.io.StringWriter)17 JsonRepresentation (org.restlet.ext.json.JsonRepresentation)16 IOException (java.io.IOException)14 Map (java.util.Map)14 Form (org.restlet.data.Form)14 VCellApiApplication (org.vcell.rest.VCellApiApplication)14 User (org.vcell.util.document.User)13 Configuration (freemarker.template.Configuration)10 StringReader (java.io.StringReader)10 ZNRecord (org.apache.helix.ZNRecord)10 TypeReference (org.codehaus.jackson.type.TypeReference)10