Search in sources :

Example 96 with Representation

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

the class ResourceResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    if (result instanceof Resource) {
        Resource resourceValue = (Resource) result;
        // Allowed methods
        response.getAllowedMethods().add(Method.GET);
        if (Iterables.matchesAny(LinksUtil.withRel("delete"), resourceValue.commands().get())) {
            response.getAllowedMethods().add(Method.DELETE);
        }
        if (Iterables.matchesAny(LinksUtil.withRel("update"), resourceValue.commands().get())) {
            response.getAllowedMethods().add(Method.PUT);
        }
        // Response according to what client accepts
        MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
        if (MediaType.APPLICATION_JSON.equals(type)) {
            response.setEntity(new StringRepresentation(resourceValue.toString(), MediaType.APPLICATION_JSON));
            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("resource.htm").process(context, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        }
    }
    return false;
}
Also used : TemplateException(freemarker.template.TemplateException) Resource(org.qi4j.library.rest.common.Resource) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 97 with Representation

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

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

Example 99 with Representation

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

the class ContextRestlet method handle.

@Override
public void handle(Request request, Response response) {
    super.handle(request, response);
    MDC.put("url", request.getResourceRef().toString());
    try {
        int tries = 0;
        // TODO Make this number configurable
        while (tries < 10) {
            tries++;
            // Root of the call
            Reference ref = request.getResourceRef();
            List<String> segments = ref.getScheme().equals("riap") ? ref.getRelativeRef(new Reference("riap://application/")).getSegments() : ref.getRelativeRef().getSegments();
            // Handle conversion of verbs into standard interactions
            if (segments.get(segments.size() - 1).equals("")) {
                if (request.getMethod().equals(Method.DELETE)) {
                    // Translate DELETE into command "delete"
                    segments.set(segments.size() - 1, "delete");
                } else if (request.getMethod().equals(Method.PUT)) {
                    // Translate PUT into command "update"
                    segments.set(segments.size() - 1, "update");
                }
            }
            request.getAttributes().put("segments", segments);
            request.getAttributes().put("template", new StringBuilder("/rest/"));
            Usecase usecase = UsecaseBuilder.buildUsecase(getUsecaseName(request)).withMetaInfo(request.getMethod().isSafe() ? CacheOptions.ALWAYS : CacheOptions.NEVER).newUsecase();
            UnitOfWork uow = module.newUnitOfWork(usecase);
            ObjectSelection.newSelection();
            try {
                // Start handling the build-up for the context
                Uniform resource = createRoot(request, response);
                resource.handle(request, response);
                if (response.getEntity() != null) {
                    if (response.getEntity().getModificationDate() == null) {
                        ResourceValidity validity = (ResourceValidity) Request.getCurrent().getAttributes().get(ContextResource.RESOURCE_VALIDITY);
                        if (validity != null) {
                            validity.updateResponse(response);
                        }
                    }
                    // Check if characterset is set
                    if (response.getEntity().getCharacterSet() == null) {
                        response.getEntity().setCharacterSet(CharacterSet.UTF_8);
                    }
                    // Check if language is set
                    if (response.getEntity().getLanguages().isEmpty()) {
                        response.getEntity().getLanguages().add(Language.ENGLISH);
                    }
                    uow.discard();
                } else {
                    // Check if last modified and tag is set
                    ResourceValidity validity = null;
                    try {
                        validity = ObjectSelection.type(ResourceValidity.class);
                    } catch (IllegalArgumentException e) {
                    // Ignore
                    }
                    uow.complete();
                    Object result = commandResult.getResult();
                    if (result != null) {
                        if (result instanceof Representation) {
                            response.setEntity((Representation) result);
                        } else {
                            if (!responseWriter.writeResponse(result, response)) {
                                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not write result of type " + result.getClass().getName());
                            }
                        }
                        if (response.getEntity() != null) {
                            // Check if characterset is set
                            if (response.getEntity().getCharacterSet() == null) {
                                response.getEntity().setCharacterSet(CharacterSet.UTF_8);
                            }
                            // Check if language is set
                            if (response.getEntity().getLanguages().isEmpty()) {
                                response.getEntity().getLanguages().add(Language.ENGLISH);
                            }
                            // Check if last modified and tag should be set
                            if (validity != null) {
                                UnitOfWork lastModifiedUoW = module.newUnitOfWork();
                                try {
                                    validity.updateEntity(lastModifiedUoW);
                                    validity.updateResponse(response);
                                } finally {
                                    lastModifiedUoW.discard();
                                }
                            }
                        }
                    }
                    return;
                }
                return;
            } catch (ConcurrentEntityModificationException ex) {
                uow.discard();
                // Try again
                ObjectSelection.newSelection();
            } catch (Throwable e) {
                uow.discard();
                handleException(response, e);
                return;
            }
        }
    // Try again
    } finally {
        MDC.clear();
    }
}
Also used : UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) Reference(org.restlet.data.Reference) Uniform(org.restlet.Uniform) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) ConcurrentEntityModificationException(org.qi4j.api.unitofwork.ConcurrentEntityModificationException) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase)

Example 100 with Representation

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

the class FormResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    if (result instanceof Form) {
        MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
        if (MediaType.APPLICATION_JSON.equals(type)) {
            JSONObject json = new JSONObject();
            Form form = (Form) result;
            try {
                for (Parameter parameter : form) {
                    String value = parameter.getValue();
                    if (value == null) {
                        json.put(parameter.getName(), JSONObject.NULL);
                    } else {
                        json.put(parameter.getName(), value);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            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> root = new HashMap<String, Object>();
                    root.put("request", response.getRequest());
                    root.put("response", response);
                    root.put("result", result);
                    try {
                        Template formHtmlTemplate = cfg.getTemplate("form.htm");
                        formHtmlTemplate.process(root, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        }
    }
    return false;
}
Also used : Form(org.restlet.data.Form) TemplateException(freemarker.template.TemplateException) JSONException(org.json.JSONException) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) Template(freemarker.template.Template) JSONObject(org.json.JSONObject) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Parameter(org.restlet.data.Parameter) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

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