Search in sources :

Example 11 with Viewable

use of org.apache.stanbol.commons.web.viewable.Viewable in project stanbol by apache.

the class RootResource method performLoadOntology.

protected ResponseBuilder performLoadOntology(MultiPartBody data, HttpHeaders headers, Origin<?>... keys) {
    log.debug(" post(MultiPartBody data)");
    ResponseBuilder rb = null;
    IRI location = null;
    // If found, it takes precedence over location.
    byte[] file = null;
    String format = null;
    List<OWLOntologyID> aliases = new ArrayList<OWLOntologyID>();
    if (data.getFormFileParameterValues("file").length > 0) {
        file = data.getFormFileParameterValues("file")[0].getContent();
    }
    // else {
    if (data.getTextParameterValues("format").length > 0) {
        String value = data.getTextParameterValues("format")[0];
        if (!value.equals("auto")) {
            format = value;
        }
    }
    if (data.getTextParameterValues("url").length > 0) {
        String value = data.getTextParameterValues("url")[0];
        try {
            // To throw 400 if malformed.
            URI.create(value);
            location = IRI.create(value);
        } catch (Exception ex) {
            log.error("Malformed IRI for " + value, ex);
            throw new WebApplicationException(ex, BAD_REQUEST);
        }
    }
    if (data.getTextParameterValues("alias").length > 0) {
        for (String value : data.getTextParameterValues("alias")) {
            if (!"null".equals(value)) {
                try {
                    aliases.add(OntologyUtils.decode(value));
                } catch (Exception ex) {
                    log.error("Malformed public key for " + value, ex);
                    throw new WebApplicationException(ex, BAD_REQUEST);
                }
            }
        }
    }
    log.debug("Parameters:");
    log.debug("file: {}", file != null && file.length > 0 ? "NOT-NULL" : "null");
    log.trace("file data: {}", file);
    log.debug("url: {}", location);
    log.debug("format: {}", format);
    log.debug("alias: {}", aliases);
    // Then add the file
    OWLOntologyID key = null;
    if (file != null && file.length > 0) {
        /*
             * Because the ontology provider's load method could fail after only one attempt without resetting
             * the stream, we might have to do that ourselves.
             */
        List<String> formats;
        if (format != null && !format.trim().isEmpty()) {
            formats = Collections.singletonList(format);
        } else // The RESTful API has its own list of preferred formats
        {
            formats = Arrays.asList(RDF_XML, TURTLE, X_TURTLE, N3, N_TRIPLE, OWL_XML, FUNCTIONAL_OWL, MANCHESTER_OWL, RDF_JSON);
        }
        log.debug("Will try {} supported formats", formats.size());
        int unsupported = 0, failed = 0;
        Iterator<String> itf = formats.iterator();
        if (!itf.hasNext()) {
            throw new OntologyLoadingException("No suitable format found or defined.");
        }
        do {
            String f = itf.next();
            try {
                // Re-instantiate the stream on every attempt
                InputStream content = new BufferedInputStream(new ByteArrayInputStream(file));
                // ClerezzaOWLUtils.guessOntologyID(new FileInputStream(file), Parser.getInstance(), f);
                OWLOntologyID guessed = OWLUtils.guessOntologyID(content, Parser.getInstance(), f);
                if (guessed != null && !guessed.isAnonymous() && ontologyProvider.hasOntology(guessed)) {
                    rb = Response.status(Status.CONFLICT);
                    this.submitted = guessed;
                    if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) {
                        rb.entity(new Viewable("/imports/409.ftl", this));
                        rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
                    }
                    break;
                } else {
                    content = new BufferedInputStream(new ByteArrayInputStream(file));
                    key = ontologyProvider.loadInStore(content, f, true, keys);
                }
            } catch (UnsupportedFormatException e) {
                log.warn("POST method failed for media type {}. This should not happen (should fail earlier)", headers.getMediaType());
                // rb = Response.status(UNSUPPORTED_MEDIA_TYPE);
                unsupported++;
            } catch (IOException e) {
                log.debug(">>> FAILURE format {} (I/O error)", f);
                failed++;
            } catch (ConcurrentModificationException e) {
                log.error("Exception logged", e);
                failed++;
            } catch (Exception e) {
                // SAXParseException and others
                log.debug(">>> FAILURE format {} (parse error)", f);
                log.debug("Caught exception {} : {}", e.getClass(), e.getLocalizedMessage());
                log.trace("Exception logged", e);
                failed++;
            }
        } while ((key == null) && itf.hasNext());
        if ((key == null || key.isAnonymous()) && rb == null) {
            if (failed > 0) {
                throw new WebApplicationException(BAD_REQUEST);
            } else if (unsupported > 0) {
                throw new WebApplicationException(UNSUPPORTED_MEDIA_TYPE);
            }
        }
    } else if (location != null) {
        try {
            // Here we try every format supported by the Java API
            key = ontologyProvider.loadInStore(location, null, true, keys);
        } catch (Exception e) {
            log.error("Failed to load ontology from " + location, e);
            Throwable cause = e.getCause();
            String html = "<h1>400 Bad Request</h1>" + "<p>Failed to load ontology from <a href=\"" + location + "\" target=\"_blank\">" + location + "</a></p>";
            if (cause != null)
                html += "<p>logged cause was: " + cause.getLocalizedMessage().replace("<", "&lt;").replace(">", "&gt;") + "</p>";
            return Response.status(BAD_REQUEST).type(TEXT_HTML).entity(html);
        }
    } else if (// No content but there are aliases.
    !aliases.isEmpty()) {
        for (Origin<?> origin : keys) {
            if (origin.getReference() instanceof OWLOntologyID) {
                OWLOntologyID primary = ((OWLOntologyID) origin.getReference());
                if (ontologyProvider.getStatus(primary) != org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyProvider.Status.NO_MATCH) {
                    for (OWLOntologyID alias : aliases) {
                        try {
                            if (ontologyProvider.addAlias(primary, alias) && key == null) {
                                key = alias;
                            }
                        } catch (IllegalArgumentException ex) {
                            log.warn("Cannot add alias");
                            log.warn(" ... ontology key: {}", primary);
                            log.warn(" ... alias: {}", alias);
                            log.warn(" ... reason: ", ex);
                            continue;
                        }
                    }
                }
            }
        }
    } else {
        log.error("Bad request");
        log.error(" file is: {}", file);
        throw new WebApplicationException(BAD_REQUEST);
    }
    if (key != null && !key.isAnonymous()) {
        String uri = OntologyUtils.encode(key);
        if (uri != null && !uri.isEmpty()) {
            rb = Response.ok();
            if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) {
                rb.entity(new Viewable("index", this));
                rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
            }
        } else {
            rb = Response.ok();
        }
    } else if (rb == null) {
        rb = Response.status(Status.INTERNAL_SERVER_ERROR);
    }
    return rb;
}
Also used : IRI(org.semanticweb.owlapi.model.IRI) ConcurrentModificationException(java.util.ConcurrentModificationException) WebApplicationException(javax.ws.rs.WebApplicationException) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException) WebApplicationException(javax.ws.rs.WebApplicationException) ConcurrentModificationException(java.util.ConcurrentModificationException) IOException(java.io.IOException) OntologyLoadingException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyLoadingException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OntologyHandleException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyHandleException) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) OrphanOntologyKeyException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OrphanOntologyKeyException) OntologyLoadingException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyLoadingException) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 12 with Viewable

use of org.apache.stanbol.commons.web.viewable.Viewable in project stanbol by apache.

the class ScopeManagerResource method getHtmlInfo.

@GET
@Produces(TEXT_HTML)
public Response getHtmlInfo(@Context HttpHeaders headers) {
    ResponseBuilder rb = Response.ok(new Viewable("index", this));
    rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
    //        addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 13 with Viewable

use of org.apache.stanbol.commons.web.viewable.Viewable in project stanbol by apache.

the class RegistryManagerResource method getHtmlInfo.

@GET
@Produces(value = MediaType.TEXT_HTML)
public Response getHtmlInfo(@Context HttpHeaders headers) {
    ResponseBuilder rb = Response.ok(new Viewable("index", this));
    rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
    //        addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 14 with Viewable

use of org.apache.stanbol.commons.web.viewable.Viewable in project stanbol by apache.

the class RulesResource method showRecipe.

@GET
@Path("/recipe/{recipe:.+}")
@Produces(value = { MediaType.TEXT_HTML })
public Response showRecipe(@PathParam("recipe") String recipeID, @QueryParam("rule") String ruleID, @Context HttpHeaders headers) {
    Recipe recipe;
    Rule rule;
    ResponseBuilder responseBuilder;
    try {
        URI uri = new URI(recipeID);
        if (uri.getScheme() == null) {
            recipeID = "urn:" + recipeID;
            log.info("The recipe ID is a URI without scheme. The ID is set to " + recipeID);
        }
        recipe = ruleStore.getRecipe(new IRI(recipeID));
        if (ruleID != null && !ruleID.isEmpty()) {
            rule = ruleStore.getRule(recipe, new IRI(ruleID));
            RuleList ruleList = new RuleList();
            ruleList.add(rule);
            recipe = new RecipeImpl(recipe.getRecipeID(), recipe.getRecipeDescription(), ruleList);
        }
        responseBuilder = Response.ok(new Viewable("rules", new RulesPrettyPrintResource(uriInfo, recipe)));
    } catch (NoSuchRecipeException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_FOUND);
    } catch (RecipeConstructionException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NO_CONTENT);
    } catch (NoSuchRuleInRecipeException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_FOUND);
    } catch (URISyntaxException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_ACCEPTABLE);
    }
    //        addCORSOrigin(servletContext, responseBuilder, headers);
    return responseBuilder.build();
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) RuleList(org.apache.stanbol.rules.base.api.util.RuleList) Recipe(org.apache.stanbol.rules.base.api.Recipe) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) NoSuchRuleInRecipeException(org.apache.stanbol.rules.base.api.NoSuchRuleInRecipeException) RecipeImpl(org.apache.stanbol.rules.manager.RecipeImpl) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) Rule(org.apache.stanbol.rules.base.api.Rule) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 15 with Viewable

use of org.apache.stanbol.commons.web.viewable.Viewable in project stanbol by apache.

the class JobsResource method get.

/**
     * GET info about a Background Job
     * 
     * @param id
     * @return Response
     */
@GET
@Path("/{jid}")
public Response get(@PathParam("jid") String id) {
    log.info("Called get() with id {}", id);
    // No id
    if (id == null || id.equals("")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    JobManager m = jobManager;
    // If the job exists
    if (m.hasJob(id)) {
        log.info("Found job with id {}", id);
        Future<?> f = m.ping(id);
        //this.info = new JobInfoImpl();
        final JobInfo info = new JobInfoImpl();
        if (f.isDone()) {
            // The job is finished
            if (f.isCancelled()) {
                // NOTE: Canceled jobs should never exist. 
                // The web service remove any deleted process from the manager
                // If a process have been canceled programmatically, it cannot be managed by the service anymore 
                // (except for DELETE)
                log.warn("Job with id {} have been canceled. Returning 404 Not found.", id);
                return Response.status(Response.Status.NOT_FOUND).build();
            } else {
                // Job is complete
                info.setFinished();
                info.addMessage("You can remove this job using DELETE");
            }
        } else {
            // the job exists but it is not complete
            info.setRunning();
            info.addMessage("You can interrupt this job using DELETE");
        }
        // Returns 200, the job exists
        info.setOutputLocation(getPublicBaseUri() + m.getResultLocation(id));
        if (isHTML()) {
            // Result as HTML
            return Response.ok(new Viewable("info", new JobsResultData(info))).build();
        } else {
            // Result as application/json, text/plain
            return Response.ok(info).build();
        }
    } else {
        log.info("No job found with id {}", id);
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
Also used : JobInfo(org.apache.stanbol.commons.jobs.api.JobInfo) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) JobManager(org.apache.stanbol.commons.jobs.api.JobManager) JobInfoImpl(org.apache.stanbol.commons.jobs.impl.JobInfoImpl) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

Viewable (org.apache.stanbol.commons.web.viewable.Viewable)43 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)40 GET (javax.ws.rs.GET)30 Produces (javax.ws.rs.Produces)26 Path (javax.ws.rs.Path)20 WebApplicationException (javax.ws.rs.WebApplicationException)15 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)14 MediaType (javax.ws.rs.core.MediaType)12 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)12 HashSet (java.util.HashSet)11 Entity (org.apache.stanbol.entityhub.servicesapi.model.Entity)7 POST (javax.ws.rs.POST)6 EntityhubException (org.apache.stanbol.entityhub.servicesapi.EntityhubException)6 IRI (org.semanticweb.owlapi.model.IRI)5 Consumes (javax.ws.rs.Consumes)4 OWLOntologyStorageException (org.semanticweb.owlapi.model.OWLOntologyStorageException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3