Search in sources :

Example 21 with MediaType

use of org.restlet.data.MediaType 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)

Example 22 with MediaType

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

the class ContextResourceClientFactory method setAcceptedMediaTypes.

public void setAcceptedMediaTypes(MediaType... acceptedMediaTypes) {
    List<Preference<MediaType>> mediatypes = new ArrayList<Preference<MediaType>>();
    for (MediaType mediaType : acceptedMediaTypes) {
        mediatypes.add(new Preference<MediaType>(mediaType));
    }
    info.setAcceptedMediaTypes(mediatypes);
}
Also used : Preference(org.restlet.data.Preference) ArrayList(java.util.ArrayList) MediaType(org.restlet.data.MediaType)

Example 23 with MediaType

use of org.restlet.data.MediaType 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 24 with MediaType

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

the class DefaultResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
    if (MediaType.APPLICATION_JSON.equals(type)) {
        if (result instanceof String || result instanceof Number || result instanceof Boolean) {
            StringRepresentation representation = new StringRepresentation(result.toString(), MediaType.APPLICATION_JSON);
            response.setEntity(representation);
            return true;
        }
    }
    return false;
}
Also used : StringRepresentation(org.restlet.representation.StringRepresentation) MediaType(org.restlet.data.MediaType)

Example 25 with MediaType

use of org.restlet.data.MediaType 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)

Aggregations

MediaType (org.restlet.data.MediaType)29 StringRepresentation (org.restlet.representation.StringRepresentation)11 Representation (org.restlet.representation.Representation)10 IOException (java.io.IOException)9 Map (java.util.Map)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 Writer (java.io.Writer)6 TemplateException (freemarker.template.TemplateException)5 HashMap (java.util.HashMap)5 Form (org.restlet.data.Form)5 ArrayList (java.util.ArrayList)4 Preference (org.restlet.data.Preference)4 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)4 ResourceException (org.restlet.resource.ResourceException)4 Template (freemarker.template.Template)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 ParseException (java.text.ParseException)3 InputRepresentation (org.restlet.representation.InputRepresentation)3 Representation (org.restlet.resource.Representation)3