Search in sources :

Example 46 with ResourceException

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

the class ResourceValidity method checkRequest.

public void checkRequest() throws ResourceException {
    // Check command rules
    Date modificationDate = request.getConditions().getUnmodifiedSince();
    if (modificationDate != null) {
        EntityState state = spi.entityStateOf(entity);
        // Cut off milliseconds
        Date lastModified = new Date((state.lastModified() / 1000) * 1000);
        if (lastModified.after(modificationDate)) {
            throw new ResourceException(Status.CLIENT_ERROR_CONFLICT);
        }
    }
    // Check query rules
    modificationDate = request.getConditions().getModifiedSince();
    if (modificationDate != null) {
        EntityState state = spi.entityStateOf(entity);
        // Cut off milliseconds
        Date lastModified = new Date((state.lastModified() / 1000) * 1000);
        if (!lastModified.after(modificationDate)) {
            throw new ResourceException(Status.REDIRECTION_NOT_MODIFIED);
        }
    }
}
Also used : ResourceException(org.restlet.resource.ResourceException) EntityState(org.qi4j.spi.entity.EntityState) Date(java.util.Date)

Example 47 with ResourceException

use of org.restlet.resource.ResourceException 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 48 with ResourceException

use of org.restlet.resource.ResourceException 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)

Example 49 with ResourceException

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

the class ValueDescriptorResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    if (result instanceof ValueDescriptor) {
        MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
        if (MediaType.APPLICATION_JSON.equals(type)) {
            JSONObject json = new JSONObject();
            ValueDescriptor vd = (ValueDescriptor) result;
            try {
                for (PropertyDescriptor propertyDescriptor : vd.state().properties()) {
                    Object o = propertyDescriptor.initialValue(module);
                    if (o == null) {
                        json.put(propertyDescriptor.qualifiedName().name(), JSONObject.NULL);
                    } else {
                        json.put(propertyDescriptor.qualifiedName().name(), o.toString());
                    }
                }
            } catch (JSONException e) {
                throw new ResourceException(e);
            }
            StringRepresentation representation = new StringRepresentation(json.toString(), MediaType.APPLICATION_JSON);
            response.setEntity(representation);
            return true;
        } else if (MediaType.TEXT_HTML.equals(type)) {
            Representation rep = new WriterRepresentation(MediaType.TEXT_HTML) {

                @Override
                public void write(Writer writer) throws IOException {
                    Map<String, Object> context = new HashMap<String, Object>();
                    context.put("request", response.getRequest());
                    context.put("response", response);
                    context.put("result", result);
                    try {
                        cfg.getTemplate("form.htm").process(context, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        }
    }
    return false;
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) TemplateException(freemarker.template.TemplateException) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) JSONException(org.json.JSONException) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) JSONObject(org.json.JSONObject) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) JSONObject(org.json.JSONObject) ResourceException(org.restlet.resource.ResourceException) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 50 with ResourceException

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

the class EntitiesResource method representHtml.

private Representation representHtml() throws ResourceException {
    try {
        final Iterable<EntityReference> query = entityFinder.findEntities(EntityComposite.class, null, null, null, null, Collections.<String, Object>emptyMap());
        Representation representation = new WriterRepresentation(MediaType.TEXT_HTML) {

            @Override
            public void write(Writer buf) throws IOException {
                PrintWriter out = new PrintWriter(buf);
                out.println("<html><head><title>All entities</title></head><body><h1>All entities</h1><ul>");
                for (EntityReference entity : query) {
                    out.println("<li><a href=\"" + getRequest().getResourceRef().clone().addSegment(entity.identity() + ".html") + "\">" + entity.identity() + "</a></li>");
                }
                out.println("</ul></body></html>");
            }
        };
        representation.setCharacterSet(CharacterSet.UTF_8);
        return representation;
    } catch (EntityFinderException e) {
        throw new ResourceException(e);
    }
}
Also used : WriterRepresentation(org.restlet.representation.WriterRepresentation) EntityFinderException(org.qi4j.spi.query.EntityFinderException) EntityReference(org.qi4j.api.entity.EntityReference) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) OutputRepresentation(org.restlet.representation.OutputRepresentation) Representation(org.restlet.representation.Representation) ResourceException(org.restlet.resource.ResourceException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Aggregations

ResourceException (org.restlet.resource.ResourceException)70 Representation (org.restlet.representation.Representation)20 PermissionException (org.vcell.util.PermissionException)20 VCellApiApplication (org.vcell.rest.VCellApiApplication)18 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)15 IOException (java.io.IOException)13 StringRepresentation (org.restlet.representation.StringRepresentation)12 ArrayList (java.util.ArrayList)10 Reference (org.restlet.data.Reference)8 BioModel (cbit.vcell.biomodel.BioModel)7 Writer (java.io.Writer)7 HashMap (java.util.HashMap)7 JSONObject (org.json.JSONObject)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 XMLSource (cbit.vcell.xml.XMLSource)6 Response (org.restlet.Response)6 User (org.vcell.util.document.User)6 EntitlementException (com.sun.identity.entitlement.EntitlementException)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4