Search in sources :

Example 6 with ResourceException

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

the class EntityResource method get.

@Override
protected Representation get(Variant variant) throws ResourceException {
    EntityStoreUnitOfWork uow = entityStore.newUnitOfWork(UsecaseBuilder.newUsecase("Get entity"), module, System.currentTimeMillis());
    try {
        EntityState entityState = getEntityState(uow);
        // Check modification date
        Date lastModified = getRequest().getConditions().getModifiedSince();
        if (lastModified != null) {
            if (lastModified.getTime() / 1000 == entityState.lastModified() / 1000) {
                throw new ResourceException(Status.REDIRECTION_NOT_MODIFIED);
            }
        }
        // Generate the right representation according to its media type.
        if (MediaType.APPLICATION_RDF_XML.equals(variant.getMediaType())) {
            return entityHeaders(representRdfXml(entityState), entityState);
        } else if (MediaType.TEXT_HTML.equals(variant.getMediaType())) {
            return entityHeaders(representHtml(entityState), entityState);
        } else if (MediaType.APPLICATION_JSON.equals(variant.getMediaType())) {
            return entityHeaders(representJson(entityState), entityState);
        }
    } catch (ResourceException ex) {
        uow.discard();
        throw ex;
    }
    throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
Also used : EntityStoreUnitOfWork(org.qi4j.spi.entitystore.EntityStoreUnitOfWork) ResourceException(org.restlet.resource.ResourceException) EntityState(org.qi4j.spi.entity.EntityState) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) Date(java.util.Date)

Example 7 with ResourceException

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

the class SPARQLResource method getQuery.

private Query getQuery(Repository repository, RepositoryConnection repositoryCon, String queryStr) throws ResourceException {
    Form form = getRequest().getResourceRef().getQueryAsForm();
    Query result;
    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;
    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = true;
    // build a dataset, if specified
    String[] defaultGraphURIs = form.getValuesArray(DEFAULT_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = form.getValuesArray(NAMED_GRAPH_PARAM_NAME);
    DatasetImpl dataset = null;
    if (defaultGraphURIs.length > 0 || namedGraphURIs.length > 0) {
        dataset = new DatasetImpl();
        if (defaultGraphURIs.length > 0) {
            for (String defaultGraphURI : defaultGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(defaultGraphURI);
                    dataset.addDefaultGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for default graph: " + defaultGraphURI);
                }
            }
        }
        if (namedGraphURIs.length > 0) {
            for (String namedGraphURI : namedGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(namedGraphURI);
                    dataset.addNamedGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
                }
            }
        }
    }
    try {
        result = repositoryCon.prepareQuery(queryLn, queryStr);
        result.setIncludeInferred(includeInferred);
        if (dataset != null) {
            result.setDataset(dataset);
        }
        // determine if any variable bindings have been set on this query.
        @SuppressWarnings("unchecked") Enumeration<String> parameterNames = Collections.enumeration(form.getValuesMap().keySet());
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = parseValueParam(repository, form, parameterName);
                result.setBinding(bindingName, bindingValue);
            }
        }
    } catch (UnsupportedQueryLanguageException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (MalformedQueryException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (RepositoryException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
    }
    return result;
}
Also used : Form(org.restlet.data.Form) RepositoryException(org.openrdf.repository.RepositoryException) DatasetImpl(org.openrdf.query.impl.DatasetImpl) URI(org.openrdf.model.URI) Value(org.openrdf.model.Value) ResourceException(org.restlet.resource.ResourceException)

Example 8 with ResourceException

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

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

the class EntitiesResource method representAtom.

private Representation representAtom() throws ResourceException {
    try {
        Feed feed = new Feed();
        feed.setTitle(new Text(MediaType.TEXT_PLAIN, "All entities"));
        List<Entry> entries = feed.getEntries();
        final Iterable<EntityReference> query = entityFinder.findEntities(EntityComposite.class, null, null, null, null, Collections.<String, Object>emptyMap());
        for (EntityReference entityReference : query) {
            Entry entry = new Entry();
            entry.setTitle(new Text(MediaType.TEXT_PLAIN, entityReference.toString()));
            Link link = new Link();
            link.setHref(getRequest().getResourceRef().clone().addSegment(entityReference.identity()));
            entry.getLinks().add(link);
            entries.add(entry);
        }
        return feed;
    } catch (Exception e) {
        throw new ResourceException(e);
    }
}
Also used : Entry(org.restlet.ext.atom.Entry) EntityReference(org.qi4j.api.entity.EntityReference) Text(org.restlet.ext.atom.Text) ResourceException(org.restlet.resource.ResourceException) Link(org.restlet.ext.atom.Link) ResourceException(org.restlet.resource.ResourceException) IOException(java.io.IOException) EntityFinderException(org.qi4j.spi.query.EntityFinderException) Feed(org.restlet.ext.atom.Feed)

Example 10 with ResourceException

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

the class RootResource method administration.

@SubResource
public void administration() {
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if (challenge == null) {
        Response.getCurrent().setChallengeRequests(Collections.singletonList(new ChallengeRequest(ChallengeScheme.HTTP_BASIC, "Forum")));
        throw new ResourceException(Status.CLIENT_ERROR_UNAUTHORIZED);
    }
    User user = module.currentUnitOfWork().newQuery(module.newQueryBuilder(User.class).where(QueryExpressions.eq(QueryExpressions.templateFor(User.class).name(), challenge.getIdentifier()))).find();
    if (user == null || !user.isCorrectPassword(new String(challenge.getSecret()))) {
        throw new ResourceException(Status.CLIENT_ERROR_UNAUTHORIZED);
    }
    current().select(user);
    subResource(AdministrationResource.class);
}
Also used : User(org.qi4j.samples.forum.data.entity.User) ResourceException(org.restlet.resource.ResourceException) ChallengeRequest(org.restlet.data.ChallengeRequest) ChallengeResponse(org.restlet.data.ChallengeResponse) SubResource(org.qi4j.library.rest.server.api.SubResource)

Aggregations

ResourceException (org.restlet.resource.ResourceException)44 Representation (org.restlet.representation.Representation)15 IOException (java.io.IOException)13 Reference (org.restlet.data.Reference)8 Writer (java.io.Writer)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 ArrayList (java.util.ArrayList)6 Response (org.restlet.Response)6 StringRepresentation (org.restlet.representation.StringRepresentation)6 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)5 EntitlementException (com.sun.identity.entitlement.EntitlementException)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4 NoSuchEntityException (org.qi4j.api.unitofwork.NoSuchEntityException)4 Form (org.restlet.data.Form)4 MediaType (org.restlet.data.MediaType)4 SSOException (com.iplanet.sso.SSOException)3 IdRepoException (com.sun.identity.idm.IdRepoException)3