Search in sources :

Example 91 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project ice by JBEI.

the class ICEExceptionMapper method toResponse.

@Override
public Response toResponse(Exception exception) {
    Response response;
    if (exception instanceof WebApplicationException) {
        WebApplicationException webEx = (WebApplicationException) exception;
        response = webEx.getResponse();
    } else {
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 92 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project ice by JBEI.

the class RestResource method requireUserIdOrWebPartner.

/**
     * Requires either a valid user request or request from a web partner
     *
     * @param logMessage log message for request
     */
protected void requireUserIdOrWebPartner(String logMessage) {
    String userId = getUserId();
    if (StringUtils.isNotEmpty(userId)) {
        log(userId, logMessage);
        return;
    }
    // try web partner
    RegistryPartner partner = getWebPartner();
    if (partner == null)
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    log(partner.getUrl(), logMessage);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RegistryPartner(org.jbei.ice.lib.dto.web.RegistryPartner)

Example 93 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project indy by Commonjava.

the class DiagnosticsResource method getBundle.

@ApiOperation("Retrieve a ZIP-compressed file containing log files and a thread dump for Indy.")
@ApiResponses({ @ApiResponse(code = 200, response = File.class, message = "ZIP bundle"), @ApiResponse(code = 500, message = "Log files could not be found / accessed") })
@GET
@Path("/bundle")
@Produces(application_zip)
public Response getBundle() {
    try {
        File bundle = diagnosticsManager.getDiagnosticBundle();
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.info("Returning diagnostic bundle: {}", bundle);
        return Response.ok(bundle).header(ApplicationHeader.content_disposition.key(), "attachment; filename=indy-diagnostic-bundle-" + System.currentTimeMillis() + ".zip").build();
    } catch (IOException e) {
        throw new WebApplicationException("Cannot retrieve log files, or failed to write logs + thread dump to bundle zip.", e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) Logger(org.slf4j.Logger) File(java.io.File) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 94 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project stanbol by apache.

the class ContentItemReader method readFrom.

@Override
public ContentItem readFrom(Class<ContentItem> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    //boolean withMetadata = withMetadata(httpHeaders);
    ContentItem contentItem = null;
    IRI contentItemId = getContentItemId();
    if (log.isTraceEnabled()) {
        //NOTE: enabling TRACE level logging will copy the parsed content
        //      into a BYTE array
        log.trace("Parse ContentItem from");
        log.trace("  - MediaType: {}", mediaType);
        log.trace("  - Headers:");
        for (Entry<String, List<String>> header : httpHeaders.entrySet()) {
            log.trace("      {}: {}", header.getKey(), header.getValue());
        }
        byte[] content = IOUtils.toByteArray(entityStream);
        log.trace("content: \n{}", new String(content, "UTF-8"));
        IOUtils.closeQuietly(entityStream);
        entityStream = new ByteArrayInputStream(content);
    }
    Set<String> parsedContentIds = new HashSet<String>();
    if (mediaType.isCompatible(MULTIPART)) {
        log.debug(" - parse Multipart MIME ContentItem");
        //try to read ContentItem from "multipart/from-data"
        Graph metadata = null;
        FileItemIterator fileItemIterator;
        try {
            fileItemIterator = fu.getItemIterator(new MessageBodyReaderContext(entityStream, mediaType));
            while (fileItemIterator.hasNext()) {
                FileItemStream fis = fileItemIterator.next();
                if (fis.getFieldName().equals("metadata")) {
                    if (contentItem != null) {
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("The Multipart MIME part with the 'metadata' " + "MUST BE before the MIME part containing the " + "'content'!").build());
                    }
                    //only used if not parsed as query param
                    if (contentItemId == null && fis.getName() != null && !fis.getName().isEmpty()) {
                        contentItemId = new IRI(fis.getName());
                    }
                    metadata = new IndexedGraph();
                    try {
                        getParser().parse(metadata, fis.openStream(), fis.getContentType());
                    } catch (Exception e) {
                        throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(String.format("Unable to parse Metadata " + "from Multipart MIME part '%s' (" + "contentItem: %s| contentType: %s)", fis.getFieldName(), fis.getName(), fis.getContentType())).build());
                    }
                } else if (fis.getFieldName().equals("content")) {
                    contentItem = createContentItem(contentItemId, metadata, fis, parsedContentIds);
                } else if (fis.getFieldName().equals("properties") || fis.getFieldName().equals(REQUEST_PROPERTIES_URI.getUnicodeString())) {
                    //parse the RequestProperties
                    if (contentItem == null) {
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts for " + "Request Properties MUST BE after the " + "MIME parts for 'metadata' AND 'content'").build());
                    }
                    MediaType propMediaType = MediaType.valueOf(fis.getContentType());
                    if (!APPLICATION_JSON_TYPE.isCompatible(propMediaType)) {
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Request Properties (Multipart MIME parts" + "with the name '" + fis.getFieldName() + "') MUST " + "BE encoded as 'appicaltion/json' (encountered: '" + fis.getContentType() + "')!").build());
                    }
                    String propCharset = propMediaType.getParameters().get("charset");
                    if (propCharset == null) {
                        propCharset = "UTF-8";
                    }
                    Map<String, Object> reqProp = ContentItemHelper.initRequestPropertiesContentPart(contentItem);
                    try {
                        reqProp.putAll(toMap(new JSONObject(IOUtils.toString(fis.openStream(), propCharset))));
                    } catch (JSONException e) {
                        throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity("Unable to parse Request Properties from" + "Multipart MIME parts with the name 'properties'!").build());
                    }
                } else {
                    //additional metadata as serialised RDF
                    if (contentItem == null) {
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts for additional " + "contentParts MUST BE after the MIME " + "parts for 'metadata' AND 'content'").build());
                    }
                    if (fis.getFieldName() == null || fis.getFieldName().isEmpty()) {
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Multipart MIME parts representing " + "ContentParts for additional RDF metadata" + "MUST define the contentParts URI as" + "'name' of the MIME part!").build());
                    }
                    Graph graph = new IndexedGraph();
                    try {
                        getParser().parse(graph, fis.openStream(), fis.getContentType());
                    } catch (Exception e) {
                        throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(String.format("Unable to parse RDF " + "for ContentPart '%s' ( contentType: %s)", fis.getName(), fis.getContentType())).build());
                    }
                    IRI contentPartId = new IRI(fis.getFieldName());
                    contentItem.addPart(contentPartId, graph);
                }
            }
            if (contentItem == null) {
                throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("The parsed multipart content item does not contain " + "any content. The content is expected to be contained " + "in a MIME part with the name 'content'. This part can " + " be also a 'multipart/alternate' if multiple content " + "parts need to be included in requests.").build());
            }
        } catch (FileUploadException e) {
            throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
        }
    } else {
        //normal content
        ContentItemFactory ciFactory = getContentItemFactory();
        contentItem = ciFactory.createContentItem(contentItemId, new StreamSource(entityStream, mediaType.toString()));
        //add the URI of the main content
        parsedContentIds.add(contentItem.getPartUri(0).getUnicodeString());
    }
    //set the parsed contentIDs to the EnhancementProperties
    Map<String, Object> ep = ContentItemHelper.initRequestPropertiesContentPart(contentItem);
    parseEnhancementPropertiesFromParameters(ep);
    ep.put(PARSED_CONTENT_URIS, Collections.unmodifiableSet(parsedContentIds));
    //STANBOL-660: set the language of the content if explicitly parsed in the request
    String contentLanguage = getContentLanguage();
    if (!StringUtils.isBlank(contentLanguage)) {
        //language codes are case insensitive ... so we convert to lower case
        contentLanguage = contentLanguage.toLowerCase(Locale.ROOT);
        createParsedLanguageAnnotation(contentItem, contentLanguage);
    // previously only the dc:language property was set to the contentItem. However this
    // information is only used as fallback if no Language annotation is present. However
    // if a user explicitly parses the language he expects this language to be used
    // so this was change with STANBOL-1417
    //            EnhancementEngineHelper.set(contentItem.getMetadata(), contentItem.getUri(), 
    //                DC_LANGUAGE, new PlainLiteralImpl(contentLanguage));
    }
    return contentItem;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) ContentItemFactory(org.apache.stanbol.enhancer.servicesapi.ContentItemFactory) WebApplicationException(javax.ws.rs.WebApplicationException) StreamSource(org.apache.stanbol.enhancer.servicesapi.impl.StreamSource) JSONException(org.codehaus.jettison.json.JSONException) URISyntaxException(java.net.URISyntaxException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) FileUploadException(org.apache.commons.fileupload.FileUploadException) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) JSONObject(org.codehaus.jettison.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) FileItemStream(org.apache.commons.fileupload.FileItemStream) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) ArrayList(java.util.ArrayList) JSONObject(org.codehaus.jettison.json.JSONObject) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) ContentItem(org.apache.stanbol.enhancer.servicesapi.ContentItem) FileUploadException(org.apache.commons.fileupload.FileUploadException) HashSet(java.util.HashSet)

Example 95 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project stanbol by apache.

the class ContentItemWriter method getIncludedMediaTypes.

/**
     * @param properties
     * @return
     */
private Set<MediaType> getIncludedMediaTypes(Map<String, Object> properties) throws WebApplicationException {
    Collection<String> includeMediaTypeStrings = getOutputContent(properties);
    if (includeMediaTypeStrings == null) {
        return null;
    }
    Set<MediaType> includeMediaTypes = new HashSet<MediaType>(includeMediaTypeStrings.size());
    for (String includeString : includeMediaTypeStrings) {
        if (includeString != null) {
            includeString = includeString.trim();
            if (!includeString.isEmpty()) {
                if ("*".equals(includeString)) {
                    //also support '*' for '*/*'
                    includeMediaTypes.add(WILDCARD_TYPE);
                } else {
                    try {
                        includeMediaTypes.add(MediaType.valueOf(includeString));
                    } catch (IllegalArgumentException e) {
                        throw new WebApplicationException("The parsed outputContent " + "parameter " + includeMediaTypeStrings + " contain an " + "illegal formated MediaType!", Response.Status.BAD_REQUEST);
                    }
                }
            }
        }
    }
    if (includeMediaTypes.contains(WILDCARD_TYPE)) {
        includeMediaTypes = Collections.singleton(WILDCARD_TYPE);
    }
    return includeMediaTypes;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) MediaType(javax.ws.rs.core.MediaType) HashSet(java.util.HashSet)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14