Search in sources :

Example 1 with WriterRepresentation

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

the class ValueCompositeRequestWriter method writeRequest.

@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException {
    if (requestObject instanceof ValueComposite) {
        // Value as parameter
        final ValueComposite valueObject = (ValueComposite) requestObject;
        if (request.getMethod().equals(Method.GET)) {
            StateHolder holder = spi.stateOf(valueObject);
            final ValueDescriptor descriptor = spi.valueDescriptorFor(valueObject);
            final Reference ref = request.getResourceRef();
            ref.setQuery(null);
            try {
                for (PropertyDescriptor propertyDescriptor : descriptor.state().properties()) {
                    Object value = holder.propertyFor(propertyDescriptor.accessor()).get();
                    String param;
                    if (value == null) {
                        param = null;
                    } else {
                        param = valueSerializer.serialize(value);
                    }
                    ref.addQueryParameter(propertyDescriptor.qualifiedName().name(), param);
                }
            } catch (ValueSerializationException e) {
                throw new ResourceException(e);
            }
        } else {
            request.setEntity(new WriterRepresentation(MediaType.APPLICATION_JSON) {

                @Override
                public void write(Writer writer) throws IOException {
                    setCharacterSet(CharacterSet.UTF_8);
                    valueSerializer.serialize(valueObject, new WriterOutputStream(writer));
                }
            });
        }
        return true;
    }
    return false;
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) Reference(org.restlet.data.Reference) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) IOException(java.io.IOException) WriterOutputStream(org.restlet.engine.io.WriterOutputStream) ValueComposite(org.qi4j.api.value.ValueComposite) WriterRepresentation(org.restlet.representation.WriterRepresentation) StateHolder(org.qi4j.api.property.StateHolder) ResourceException(org.restlet.resource.ResourceException) RequestWriter(org.qi4j.library.rest.client.spi.RequestWriter) Writer(java.io.Writer)

Example 2 with WriterRepresentation

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

the class ValueCompositeResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    if (result instanceof ValueComposite) {
        MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
        if (MediaType.APPLICATION_JSON.equals(type)) {
            StringRepresentation representation = new StringRepresentation(valueSerializer.serialize(result), 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 {
                    // Look for type specific template
                    Template template;
                    try {
                        template = cfg.getTemplate("/rest/template/" + result.getClass().getInterfaces()[0].getSimpleName() + ".htm");
                    } catch (Exception e) {
                        // Use default
                        template = cfg.getTemplate("value.htm");
                    }
                    Map<String, Object> context = new HashMap<String, Object>();
                    context.put("request", response.getRequest());
                    context.put("response", response);
                    context.put("result", result);
                    context.put("util", this);
                    try {
                        template.process(context, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }

                public boolean isSequence(Object obj) {
                    return obj instanceof Collection;
                }
            };
            response.setEntity(rep);
            return true;
        }
    }
    return false;
}
Also used : TemplateException(freemarker.template.TemplateException) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) ValueComposite(org.qi4j.api.value.ValueComposite) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ResourceException(org.restlet.resource.ResourceException) Template(freemarker.template.Template) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 3 with WriterRepresentation

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

the class EntityResource method representHtml.

private Representation representHtml(final EntityState entity) {
    return new WriterRepresentation(MediaType.TEXT_HTML) {

        @Override
        public void write(Writer writer) throws IOException {
            PrintWriter out = new PrintWriter(writer);
            out.println("<html><head><title>" + entity.identity() + "</title>" + "<link rel=\"alternate\" type=\"application/rdf+xml\" " + "href=\"" + entity.identity() + ".rdf\"/></head><body>");
            out.println("<h1>" + entity.identity() + "</h1>");
            out.println("<form method=\"post\" action=\"" + getRequest().getResourceRef().getPath() + "\">\n");
            out.println("<fieldset><legend>Properties</legend>\n<table>");
            final EntityDescriptor descriptor = entity.entityDescriptor();
            for (PropertyDescriptor persistentProperty : descriptor.state().properties()) {
                Object value = entity.propertyValueOf(persistentProperty.qualifiedName());
                out.println("<tr><td>" + "<label for=\"" + persistentProperty.qualifiedName() + "\" >" + persistentProperty.qualifiedName().name() + "</label></td>\n" + "<td><input " + "size=\"80\" " + "type=\"text\" " + (persistentProperty.isImmutable() ? "readonly=\"true\" " : "") + "name=\"" + persistentProperty.qualifiedName() + "\" " + "value=\"" + (value == null ? "" : valueSerialization.serialize(value)) + "\"/></td></tr>");
            }
            out.println("</table></fieldset>\n");
            out.println("<fieldset><legend>Associations</legend>\n<table>");
            for (AssociationDescriptor associationType : descriptor.state().associations()) {
                Object value = entity.associationValueOf(associationType.qualifiedName());
                if (value == null) {
                    value = "";
                }
                out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><input " + "type=\"text\" " + "size=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" " + "value=\"" + value + "\"/></td></tr>");
            }
            out.println("</table></fieldset>\n");
            out.println("<fieldset><legend>ManyAssociations</legend>\n<table>");
            for (AssociationDescriptor associationType : descriptor.state().manyAssociations()) {
                ManyAssociationState identities = entity.manyAssociationValueOf(associationType.qualifiedName());
                String value = "";
                for (EntityReference identity : identities) {
                    value += identity.identity() + "\n";
                }
                out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><textarea " + "rows=\"10\" " + "cols=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" >" + value + "</textarea></td></tr>");
            }
            out.println("</table></fieldset>\n");
            out.println("<fieldset><legend>NamedAssociations</legend>\n<table>");
            for (AssociationDescriptor associationType : descriptor.state().namedAssociations()) {
                NamedAssociationState identities = entity.namedAssociationValueOf(associationType.qualifiedName());
                String value = "";
                for (String name : identities) {
                    value += name + "\n" + identities.get(name).identity() + "\n";
                }
                out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><textarea " + "rows=\"10\" " + "cols=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" >" + value + "</textarea></td></tr>");
            }
            out.println("</table></fieldset>\n");
            out.println("<input type=\"submit\" value=\"Update\"/></form>\n");
            out.println("</body></html>\n");
        }
    };
}
Also used : EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) WriterRepresentation(org.restlet.representation.WriterRepresentation) NamedAssociationState(org.qi4j.spi.entity.NamedAssociationState) EntityReference(org.qi4j.api.entity.EntityReference) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) ManyAssociationState(org.qi4j.spi.entity.ManyAssociationState) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 4 with WriterRepresentation

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

the class EntityResource method representRdfXml.

private Representation representRdfXml(final EntityState entity) throws ResourceException {
    Representation representation = new WriterRepresentation(MediaType.APPLICATION_RDF_XML) {

        @Override
        public void write(Writer writer) throws IOException {
            try {
                Iterable<Statement> statements = entitySerializer.serialize(entity);
                new RdfXmlSerializer().serialize(statements, writer);
            } catch (RDFHandlerException e) {
                throw new IOException(e);
            }
        }
    };
    representation.setCharacterSet(CharacterSet.UTF_8);
    return representation;
}
Also used : RDFHandlerException(org.openrdf.rio.RDFHandlerException) WriterRepresentation(org.restlet.representation.WriterRepresentation) Statement(org.openrdf.model.Statement) RdfXmlSerializer(org.qi4j.library.rdf.serializer.RdfXmlSerializer) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) Representation(org.restlet.representation.Representation) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer)

Example 5 with WriterRepresentation

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

the class DomainEventSourceResource method handle.

@Override
public void handle(Request request, Response response) {
    long eventCount = source.count();
    long pageSize = 10;
    long startEvent = -1;
    long endEvent = -1;
    long limit = pageSize;
    final List<UnitOfWorkDomainEventsValue> eventsValues = new ArrayList<UnitOfWorkDomainEventsValue>();
    final Feed feed = new Feed();
    feed.setBaseReference(request.getResourceRef().getParentRef());
    List<Link> links = feed.getLinks();
    String remainingPart = request.getResourceRef().getRemainingPart();
    if (remainingPart.equals("/")) {
        // Current set - always contains the last "pageSize" events
        startEvent = Math.max(0, eventCount - pageSize - 1);
        feed.setTitle(new Text("Current set"));
        if (startEvent > 0) {
            long previousStart = Math.max(0, startEvent - pageSize);
            long previousEnd = startEvent - 1;
            Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
            link.setTitle("Previous page");
            links.add(link);
        }
    } else {
        // Archive
        String[] indices = remainingPart.substring(1).split(",");
        if (indices.length == 1) {
            // Working set
            startEvent = Long.parseLong(indices[0]);
            endEvent = startEvent + pageSize - 1;
            limit = pageSize;
            feed.setTitle(new Text("Working set"));
        } else if (indices.length == 2) {
            feed.setTitle(new Text("Archive page"));
            startEvent = Long.parseLong(indices[0]);
            endEvent = Long.parseLong(indices[1]);
            limit = 1 + endEvent - startEvent;
        } else
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        if (startEvent > 0) {
            long previousStart = Math.max(0, startEvent - pageSize);
            long previousEnd = startEvent - 1;
            Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
            link.setTitle("Previous page");
            links.add(link);
        }
        long nextStart = endEvent + 1;
        long nextEnd = nextStart + pageSize - 1;
        if (nextStart < eventCount)
            if (nextEnd >= eventCount) {
                Link next = new Link(new Reference(nextStart + ""), new Relation("next"), MediaType.APPLICATION_ATOM);
                next.setTitle("Working set");
                links.add(next);
            } else {
                Link next = new Link(new Reference(nextStart + "," + nextEnd), new Relation("next"), MediaType.APPLICATION_ATOM);
                next.setTitle("Next page");
                links.add(next);
            }
    }
    try {
        source.events(startEvent, limit).transferTo(Outputs.collection(eventsValues));
    } catch (Throwable throwable) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, throwable);
    }
    Link last = new Link(new Reference("0," + (pageSize - 1)), new Relation("last"), MediaType.APPLICATION_ATOM);
    last.setTitle("Last archive page");
    links.add(last);
    Link first = new Link(new Reference("."), new Relation("first"), MediaType.APPLICATION_ATOM);
    first.setTitle("Current set");
    links.add(first);
    /*
        if (previousPage != -1)
        {
            Link link = new Link( new Reference( ""+previousPage ), new Relation( "prev-archive" ), MediaType.APPLICATION_ATOM );
            link.setTitle( "Previous archive page" );
            links.add( link );
        }
        if (nextPage != -1)
        {
            Link link = new Link( new Reference( "" + nextPage ), new Relation( "next-archive" ), MediaType.APPLICATION_ATOM );
            link.setTitle( "Next archive page" );
            links.add( link );
        }
        else if (startEvent != workingSetOffset)
        {
            Link next = new Link( new Reference( "" ), new Relation( "next" ), MediaType.APPLICATION_ATOM );
            next.setTitle( "Next page" );
            links.add( next );
        }
*/
    Date lastModified = null;
    for (UnitOfWorkDomainEventsValue eventsValue : eventsValues) {
        Entry entry = new Entry();
        entry.setTitle(new Text(eventsValue.usecase().get() + "(" + eventsValue.user().get() + ")"));
        entry.setPublished(new Date(eventsValue.timestamp().get()));
        entry.setModificationDate(lastModified = new Date(eventsValue.timestamp().get()));
        entry.setId(Long.toString(startEvent + 1));
        startEvent++;
        Content content = new Content();
        content.setInlineContent(new StringRepresentation(eventsValue.toString(), MediaType.APPLICATION_JSON));
        entry.setContent(content);
        feed.getEntries().add(entry);
    }
    feed.setModificationDate(lastModified);
    MediaType mediaType = request.getClientInfo().getPreferredMediaType(Iterables.toList(iterable(MediaType.TEXT_HTML, MediaType.APPLICATION_ATOM)));
    if (MediaType.APPLICATION_ATOM.equals(mediaType)) {
        WriterRepresentation representation = new WriterRepresentation(MediaType.APPLICATION_ATOM) {

            @Override
            public void write(final Writer writer) throws IOException {
                feed.write(writer);
            }
        };
        representation.setCharacterSet(CharacterSet.UTF_8);
        response.setEntity(representation);
    } else {
        WriterRepresentation representation = new WriterRepresentation(MediaType.TEXT_HTML) {

            @Override
            public void write(Writer writer) throws IOException {
                writer.append("<html><head><title>Events</title></head><body>");
                for (Link link : feed.getLinks()) {
                    writer.append("<a href=\"").append(link.getHref().getPath()).append("\">");
                    writer.append(link.getTitle());
                    writer.append("</a><br/>");
                }
                writer.append("<ol>");
                for (Entry entry : feed.getEntries()) {
                    writer.append("<li>").append(entry.getTitle().toString()).append("</li>");
                }
                writer.append("</ol></body>");
            }
        };
        representation.setCharacterSet(CharacterSet.UTF_8);
        response.setEntity(representation);
    }
/*
        } else
        {
            throw new ResourceException( Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE );
        }
*/
}
Also used : Reference(org.restlet.data.Reference) ArrayList(java.util.ArrayList) Date(java.util.Date) UnitOfWorkDomainEventsValue(org.qi4j.library.eventsourcing.domain.api.UnitOfWorkDomainEventsValue) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) ResourceException(org.restlet.resource.ResourceException) Writer(java.io.Writer)

Aggregations

Writer (java.io.Writer)13 WriterRepresentation (org.restlet.representation.WriterRepresentation)13 IOException (java.io.IOException)9 TemplateException (freemarker.template.TemplateException)7 HashMap (java.util.HashMap)7 Representation (org.restlet.representation.Representation)7 ResourceException (org.restlet.resource.ResourceException)7 MediaType (org.restlet.data.MediaType)6 StringRepresentation (org.restlet.representation.StringRepresentation)6 PrintWriter (java.io.PrintWriter)4 Map (java.util.Map)4 Template (freemarker.template.Template)3 EntityReference (org.qi4j.api.entity.EntityReference)3 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)3 ValueDescriptor (org.qi4j.api.value.ValueDescriptor)3 JSONException (org.json.JSONException)2 JSONObject (org.json.JSONObject)2 ValueComposite (org.qi4j.api.value.ValueComposite)2 EntityFinderException (org.qi4j.spi.query.EntityFinderException)2 Reference (org.restlet.data.Reference)2