Search in sources :

Example 81 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.

the class EntityhubRootResource method getSymbolMappings.

@GET
@Path("mapping/symbol")
@Produces({ APPLICATION_JSON, RDF_XML, N3, TURTLE, X_TURTLE, RDF_JSON, N_TRIPLE, TEXT_HTML })
public Response getSymbolMappings(@QueryParam("id") String symbol, @Context HttpHeaders headers) throws WebApplicationException {
    log.debug("getSymbolMappings() POST Request > symbol: {} > accept: {}", symbol, headers.getAcceptableMediaTypes());
    Set<String> supported = new HashSet<String>(JerseyUtils.REPRESENTATION_SUPPORTED_MEDIA_TYPES);
    supported.add(TEXT_HTML);
    MediaType acceptedMediaType = getAcceptableMediaType(headers, supported, APPLICATION_JSON_TYPE);
    if (symbol == null || symbol.isEmpty()) {
        //if HTML -> print the docu of the restfull service
        if (TEXT_HTML_TYPE.isCompatible(acceptedMediaType)) {
            ResponseBuilder rb = Response.ok(new Viewable("mapping_symbol", this));
            rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
            //addCORSOrigin(servletContext, rb, headers);
            return rb.build();
        } else {
            return Response.status(Status.BAD_REQUEST).entity("No symbol given. Missing parameter id.\n").header(HttpHeaders.ACCEPT, acceptedMediaType).build();
        }
    }
    //Entityhub entityhub = ContextHelper.getServiceFromContext(Entityhub.class, servletContext);
    Collection<Entity> mappings;
    try {
        mappings = entityhub.getMappingsByTarget(symbol);
    } catch (EntityhubException e) {
        throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
    }
    if (mappings == null || mappings.isEmpty()) {
        return Response.status(Status.NOT_FOUND).entity("No mapping found for symbol '" + symbol + "'.\n").header(HttpHeaders.ACCEPT, acceptedMediaType).build();
    } else {
        // TODO: Implement Support for list of Signs, Representations and Strings
        // For now use a pseudo QueryResultList
        QueryResultList<Entity> mappingResultList = new QueryResultListImpl<Entity>(null, mappings, Entity.class);
        ResponseBuilder rb = Response.ok(mappingResultList);
        rb.header(HttpHeaders.CONTENT_TYPE, acceptedMediaType + "; charset=utf-8");
        //addCORSOrigin(servletContext, rb, headers);
        return rb.build();
    }
}
Also used : Entity(org.apache.stanbol.entityhub.servicesapi.model.Entity) WebApplicationException(javax.ws.rs.WebApplicationException) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) QueryResultListImpl(org.apache.stanbol.entityhub.core.query.QueryResultListImpl) MediaType(javax.ws.rs.core.MediaType) MediaTypeUtil.getAcceptableMediaType(org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType) EntityhubException(org.apache.stanbol.entityhub.servicesapi.EntityhubException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 82 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.

the class EntityhubRootResource method executeQuery.

/**
     * Executes the query parsed by {@link #queryEntities(String, File, HttpHeaders)}
     * or created based {@link #findEntity(String, String, String, String, HttpHeaders)
     * @param query The query to execute
     * @param headers The headers used to determine the media types
     * @return the response (results of error)
     */
private Response executeQuery(FieldQuery query, HttpHeaders headers, MediaType acceptedMediaType) throws WebApplicationException {
    //Entityhub entityhub = ContextHelper.getServiceFromContext(Entityhub.class, servletContext);
    if (query instanceof LDPathSelect && ((LDPathSelect) query).getLDPathSelect() != null) {
        //use the LDPath variant to process this query
        return executeLDPathQuery(entityhub, query, ((LDPathSelect) query).getLDPathSelect(), acceptedMediaType, headers);
    } else {
        //use the default query execution
        QueryResultList<Representation> result;
        try {
            result = entityhub.find(query);
        } catch (EntityhubException e) {
            String message = String.format("Exception while performing the " + "FieldQuery on the EntityHub (message: %s)", e.getMessage());
            log.error(message, e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build();
        }
        ResponseBuilder rb = Response.ok(result);
        rb.header(HttpHeaders.CONTENT_TYPE, acceptedMediaType + "; charset=utf-8");
        //addCORSOrigin(servletContext, rb, headers);
        return rb.build();
    }
}
Also used : EntityhubException(org.apache.stanbol.entityhub.servicesapi.EntityhubException) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) LDPathSelect(org.apache.stanbol.entityhub.ldpath.query.LDPathSelect) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 83 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.

the class EntityhubRootResource method findEntity.

@POST
@Path("/find")
@Produces({ APPLICATION_JSON, RDF_XML, N3, TURTLE, X_TURTLE, RDF_JSON, N_TRIPLE, TEXT_HTML })
public Response findEntity(@FormParam(value = "name") String name, @FormParam(value = "field") String parsedField, @FormParam(value = "lang") String language, @FormParam(value = "limit") Integer limit, @FormParam(value = "offset") Integer offset, // solution!
@FormParam(value = "select") String select, @FormParam(value = "ldpath") String ldpath, @Context HttpHeaders headers) {
    log.debug("/find Request");
    final MediaType acceptedMediaType = getAcceptableMediaType(headers, ENTITY_SUPPORTED_MEDIA_TYPE_INCL_HTML, MediaType.APPLICATION_JSON_TYPE);
    if (name == null || name.isEmpty()) {
        if (acceptedMediaType.isCompatible(TEXT_HTML_TYPE)) {
            //return HTML docu
            ResponseBuilder rb = Response.ok(new Viewable("find", this));
            rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
            //addCORSOrigin(servletContext, rb, headers);
            return rb.build();
        } else {
            return Response.status(Status.BAD_REQUEST).entity("The name must not be null nor empty for find requests. Missing parameter name.\n").header(HttpHeaders.ACCEPT, acceptedMediaType).build();
        }
    } else {
        final String property;
        if (parsedField == null) {
            property = DEFAULT_FIND_FIELD;
        } else {
            parsedField = parsedField.trim();
            if (parsedField.isEmpty()) {
                property = DEFAULT_FIND_FIELD;
            } else {
                property = nsPrefixService.getFullName(parsedField);
                if (property == null) {
                    String messsage = String.format("The prefix '%s' of the parsed field '%' is not " + "mapped to any namespace. Please parse the full URI instead!\n", NamespaceMappingUtils.getPrefix(parsedField), parsedField);
                    return Response.status(Status.BAD_REQUEST).entity(messsage).header(HttpHeaders.ACCEPT, acceptedMediaType).build();
                }
            }
        }
        FieldQuery query = JerseyUtils.createFieldQueryForFindRequest(name, property, language, limit == null || limit < 1 ? DEFAULT_FIND_RESULT_LIMIT : limit, offset, ldpath);
        // For the Entityhub we support to select additional fields for results
        // of find requests. For the Sites and {site} endpoint this is currently
        // deactivated because of very bad performance with OPTIONAL graph patterns
        // in SPARQL queries.
        Collection<String> additionalSelectedFields = new ArrayList<String>();
        if (select != null && !select.isEmpty()) {
            for (String selected : select.trim().split(" ")) {
                if (selected != null && !selected.isEmpty()) {
                    additionalSelectedFields.add(selected);
                }
            }
        }
        query.addSelectedFields(additionalSelectedFields);
        return executeQuery(query, headers, acceptedMediaType);
    }
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ArrayList(java.util.ArrayList) MediaType(javax.ws.rs.core.MediaType) MediaTypeUtil.getAcceptableMediaType(org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 84 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.

the class EntityhubRootResource method executeLDPathQuery.

/**
     * Execute a Query that uses LDPath to process results.
     * @param query the query
     * @param mediaType the mediaType for the response
     * @param headers the http headers of the request
     * @return the response
     */
private Response executeLDPathQuery(Entityhub entityhub, FieldQuery query, String ldpathProgramString, MediaType mediaType, HttpHeaders headers) {
    QueryResultList<Representation> result;
    ValueFactory vf = new RdfValueFactory(new IndexedGraph());
    EntityhubBackend backend = new EntityhubBackend(entityhub);
    EntityhubLDPath ldPath = new EntityhubLDPath(backend, vf);
    //copy the selected fields, because we might need to delete some during
    //the preparation phase
    Set<String> selectedFields = new HashSet<String>(query.getSelectedFields());
    //first prepare (only execute the query if the parameters are valid)
    Program<Object> program;
    try {
        program = prepareQueryLDPathProgram(ldpathProgramString, selectedFields, backend, ldPath);
    } catch (LDPathParseException e) {
        log.warn("Unable to parse LDPath program used as select for Query:");
        log.warn("FieldQuery: \n {}", query);
        log.warn("LDPath: \n {}", ((LDPathSelect) query).getLDPathSelect());
        log.warn("Exception:", e);
        return Response.status(Status.BAD_REQUEST).entity(("Unable to parse LDPath program (Messages: " + getLDPathParseExceptionMessage(e) + ")!\n")).header(HttpHeaders.ACCEPT, mediaType).build();
    } catch (IllegalStateException e) {
        log.warn("parsed LDPath program is not compatible with parsed Query!", e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).header(HttpHeaders.ACCEPT, mediaType).build();
    }
    //2. execute the query
    Iterator<Representation> resultIt;
    try {
        // go directly to the yard and query there for Representations
        resultIt = entityhub.getYard().findRepresentation(query).iterator();
    } catch (EntityhubException e) {
        String message = String.format("Exception while performing the " + "FieldQuery on the EntityHub (message: %s)", e.getMessage());
        log.error(message, e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).header(HttpHeaders.ACCEPT, mediaType).build();
    }
    //process the results
    Collection<Representation> transformedResults = transformQueryResults(resultIt, program, selectedFields, ldPath, backend, vf);
    result = new QueryResultListImpl<Representation>(query, transformedResults, Representation.class);
    ResponseBuilder rb = Response.ok(result);
    rb.header(HttpHeaders.CONTENT_TYPE, mediaType + "; charset=utf-8");
    //addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : EntityhubBackend(org.apache.stanbol.entityhub.ldpath.backend.EntityhubBackend) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) ValueFactory(org.apache.stanbol.entityhub.servicesapi.model.ValueFactory) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) LDPathSelect(org.apache.stanbol.entityhub.ldpath.query.LDPathSelect) EntityhubException(org.apache.stanbol.entityhub.servicesapi.EntityhubException) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) LDPathParseException(org.apache.marmotta.ldpath.exception.LDPathParseException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath) HashSet(java.util.HashSet)

Example 85 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.

the class ReferencedSiteRootResource method deleteEntity.

@DELETE
@Path("entity/")
public Response deleteEntity(@PathParam(value = "site") String siteId, @QueryParam(value = "id") String id, @Context HttpHeaders headers) {
    MediaType accepted = getAcceptableMediaType(headers, JerseyUtils.ENTITY_SUPPORTED_MEDIA_TYPES, MediaType.APPLICATION_JSON_TYPE);
    ManagedSite managedSite;
    Site site = getSite(siteId);
    if (site instanceof ManagedSite) {
        managedSite = (ManagedSite) site;
    } else {
        ResponseBuilder builder = Response.status(Status.FORBIDDEN).entity(String.format("The Site '%s' is not managed and does not support " + "create/update nor delete operations", site.getId())).header(HttpHeaders.ACCEPT, accepted);
        //addCORSOrigin(servletContext, builder, headers);
        return builder.build();
    }
    if (id == null || id.isEmpty()) {
        ResponseBuilder builder = Response.status(Status.BAD_REQUEST).entity("The Request does" + "not provide the id of the Entity to delete (parameter 'id').").header(HttpHeaders.ACCEPT, accepted);
        //addCORSOrigin(servletContext, builder, headers);
        return builder.build();
    }
    ResponseBuilder builder;
    try {
        if ("*".equals(id)) {
            managedSite.deleteAll();
            builder = Response.ok();
        } else {
            Entity entity = managedSite.getEntity(id);
            if (entity != null) {
                //delete the entity
                managedSite.delete(id);
                //return the deleted data
                final MediaType acceptedMediaType = getAcceptableMediaType(headers, new HashSet<String>(JerseyUtils.ENTITY_SUPPORTED_MEDIA_TYPES), MediaType.APPLICATION_JSON_TYPE);
                builder = Response.ok(entity).header(HttpHeaders.CONTENT_TYPE, acceptedMediaType + "; charset=utf-8");
            } else {
                builder = Response.status(Status.NOT_FOUND).entity("No Entity with the parsed Id '" + id + "' is present on the ManagedSite '" + managedSite.getId() + "'!").header(HttpHeaders.ACCEPT, accepted);
            }
        }
    } catch (SiteException e) {
        String message = "Exception while deleting '" + id + "' from ManagedSite '" + managedSite.getId() + "'!";
        log.error(message, e);
        builder = Response.status(Status.INTERNAL_SERVER_ERROR).entity(message + ' ' + e.getClass().getSimpleName() + ": " + e.getMessage()).header(HttpHeaders.ACCEPT, accepted);
    }
    //addCORSOrigin(servletContext, builder, headers);
    return builder.build();
}
Also used : ManagedSite(org.apache.stanbol.entityhub.servicesapi.site.ManagedSite) Site(org.apache.stanbol.entityhub.servicesapi.site.Site) Entity(org.apache.stanbol.entityhub.servicesapi.model.Entity) MediaType(javax.ws.rs.core.MediaType) MediaTypeUtil.getAcceptableMediaType(org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) SiteException(org.apache.stanbol.entityhub.servicesapi.site.SiteException) ManagedSiteException(org.apache.stanbol.entityhub.servicesapi.site.ManagedSiteException) ManagedSite(org.apache.stanbol.entityhub.servicesapi.site.ManagedSite) Path(javax.ws.rs.Path) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath) DELETE(javax.ws.rs.DELETE)

Aggregations

ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)175 GET (javax.ws.rs.GET)84 Produces (javax.ws.rs.Produces)81 Path (javax.ws.rs.Path)69 WebApplicationException (javax.ws.rs.WebApplicationException)47 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)40 IOException (java.io.IOException)30 MediaType (javax.ws.rs.core.MediaType)29 POST (javax.ws.rs.POST)23 IRI (org.semanticweb.owlapi.model.IRI)22 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)21 Response (javax.ws.rs.core.Response)20 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)19 URI (java.net.URI)18 Consumes (javax.ws.rs.Consumes)18 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)18 ByteArrayInputStream (java.io.ByteArrayInputStream)16 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)16 HashSet (java.util.HashSet)14 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)12