Search in sources :

Example 26 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class RestletRealmRouter method getRealmFromServerName.

private RealmInfo getRealmFromServerName(Request request) {
    String serverName = request.getHostRef().getHostDomain();
    try {
        SSOToken adminToken = coreWrapper.getAdminToken();
        String orgDN = coreWrapper.getOrganization(adminToken, serverName);
        return new RealmInfo(coreWrapper.convertOrgNameToRealmName(orgDN));
    } catch (IdRepoException | SSOException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
    }
}
Also used : RealmInfo(org.forgerock.openam.core.RealmInfo) SSOToken(com.iplanet.sso.SSOToken) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) ResourceException(org.restlet.resource.ResourceException)

Example 27 with ResourceException

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

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

the class ResourceTemplateResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
    if (type != null) {
        // Try to find template for this specific resource
        StringBuilder templateBuilder = (StringBuilder) response.getRequest().getAttributes().get("template");
        String templateName = templateBuilder.toString();
        if (result instanceof ValueDescriptor) {
            templateName += "_form";
        }
        final String extension = metadataService.getExtension(type);
        templateName += "." + extension;
        // Have we failed on this one before, then don't try again
        if (skip.contains(templateName)) {
            return false;
        }
        try {
            final Template template = cfg.getTemplate(templateName);
            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 {
                        template.process(context, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        } catch (Exception e) {
            skip.add(templateName);
        // Ignore
        }
    }
    return false;
}
Also used : HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ResourceException(org.restlet.resource.ResourceException) Template(freemarker.template.Template) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Writer(java.io.Writer)

Example 29 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 30 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)60 Representation (org.restlet.representation.Representation)19 VCellApiApplication (org.vcell.rest.VCellApiApplication)16 PermissionException (org.vcell.util.PermissionException)16 IOException (java.io.IOException)13 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)11 ArrayList (java.util.ArrayList)10 StringRepresentation (org.restlet.representation.StringRepresentation)9 Reference (org.restlet.data.Reference)8 Writer (java.io.Writer)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 JSONObject (org.json.JSONObject)6 Response (org.restlet.Response)6 User (org.vcell.util.document.User)6 HashMap (java.util.HashMap)5 JsonRepresentation (org.restlet.ext.json.JsonRepresentation)5 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)5 JSONException (org.json.JSONException)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4