Search in sources :

Example 1 with ContainerException

use of org.glassfish.jersey.server.ContainerException in project jersey by jersey.

the class FreemarkerViewProcessor method writeTo.

@Override
public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
    try {
        Object model = viewable.getModel();
        if (!(model instanceof Map)) {
            model = new HashMap<String, Object>() {

                {
                    put("model", viewable.getModel());
                }
            };
        }
        Charset encoding = setContentType(mediaType, httpHeaders);
        template.process(model, new OutputStreamWriter(out, encoding));
    } catch (TemplateException te) {
        throw new ContainerException(te);
    }
}
Also used : TemplateException(freemarker.template.TemplateException) ContainerException(org.glassfish.jersey.server.ContainerException) Charset(java.nio.charset.Charset) OutputStreamWriter(java.io.OutputStreamWriter) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 2 with ContainerException

use of org.glassfish.jersey.server.ContainerException in project jersey by jersey.

the class ResponseWriter method callSendError.

/**
     * According to configuration and response processing status it calls {@link HttpServletResponse#sendError(int, String)} over
     * common {@link HttpServletResponse#setStatus(int)}.
     */
private void callSendError() {
    // - property ServletProperties#FILTER_FORWARD_ON_404 == false (default)
    if (!configSetStatusOverSendError && !response.isCommitted()) {
        final ContainerResponse responseContext = getResponseContext();
        final boolean hasEntity = responseContext.hasEntity();
        final Response.StatusType status = responseContext.getStatusInfo();
        if (!hasEntity && status != null && status.getStatusCode() >= 400 && !(useSetStatusOn404 && status == Response.Status.NOT_FOUND)) {
            final String reason = status.getReasonPhrase();
            try {
                if (reason == null || reason.isEmpty()) {
                    response.sendError(status.getStatusCode());
                } else {
                    response.sendError(status.getStatusCode(), reason);
                }
            } catch (final IOException ex) {
                throw new ContainerException(LocalizationMessages.EXCEPTION_SENDING_ERROR_RESPONSE(status, reason != null ? reason : "--"), ex);
            }
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) Response(javax.ws.rs.core.Response) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerException(org.glassfish.jersey.server.ContainerException) IOException(java.io.IOException)

Example 3 with ContainerException

use of org.glassfish.jersey.server.ContainerException in project jersey by jersey.

the class ServletContainer method init.

// Filter
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    init(new WebFilterConfig(filterConfig));
    final String regex = (String) getConfiguration().getProperty(ServletProperties.FILTER_STATIC_CONTENT_REGEX);
    if (regex != null && !regex.isEmpty()) {
        try {
            staticContentPattern = Pattern.compile(regex);
        } catch (final PatternSyntaxException ex) {
            throw new ContainerException(LocalizationMessages.INIT_PARAM_REGEX_SYNTAX_INVALID(regex, ServletProperties.FILTER_STATIC_CONTENT_REGEX), ex);
        }
    }
    this.filterContextPath = filterConfig.getInitParameter(ServletProperties.FILTER_CONTEXT_PATH);
    if (filterContextPath != null) {
        if (filterContextPath.isEmpty()) {
            filterContextPath = null;
        } else {
            if (!filterContextPath.startsWith("/")) {
                filterContextPath = '/' + filterContextPath;
            }
            if (filterContextPath.endsWith("/")) {
                filterContextPath = filterContextPath.substring(0, filterContextPath.length() - 1);
            }
        }
    }
    // get the url-pattern defined (e.g.) in the filter-mapping section of web.xml
    final FilterUrlMappingsProvider filterUrlMappingsProvider = getFilterUrlMappingsProvider();
    if (filterUrlMappingsProvider != null) {
        filterUrlMappings = filterUrlMappingsProvider.getFilterUrlMappings(filterConfig);
    }
    // not work (won't be accessible)
    if (filterUrlMappings == null && filterContextPath == null) {
        LOGGER.warning(LocalizationMessages.FILTER_CONTEXT_PATH_MISSING());
    }
}
Also used : ContainerException(org.glassfish.jersey.server.ContainerException) FilterUrlMappingsProvider(org.glassfish.jersey.servlet.spi.FilterUrlMappingsProvider) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 4 with ContainerException

use of org.glassfish.jersey.server.ContainerException in project Payara by payara.

the class PayaraClientUtil method getResponseMap.

private Map<String, Object> getResponseMap(Response response) {
    Map<String, Object> responseMap = new HashMap<>();
    String message = "";
    final String xmlDoc = response.readEntity(String.class);
    // Marshalling the XML format response to a java Map
    if (xmlDoc != null && !xmlDoc.isEmpty()) {
        responseMap = xmlToMap(xmlDoc);
        message = "exit_code: " + responseMap.get("exit_code") + ", message: " + responseMap.get("message");
    }
    StatusType status = response.getStatusInfo();
    if (status.getFamily() == SUCCESSFUL) {
        // O.K. the jersey call was successful, what about the Payara server response?
        if (responseMap.get("exit_code") == null) {
            throw new PayaraClientException(message);
        } else if (WARNING.equals(responseMap.get("exit_code"))) {
            // Warning is not a failure - some warnings in Payara are inevitable (i.e. persistence-related: ARQ-606)
            log.warning("Deployment resulted in a warning: " + message);
        } else if (!SUCCESS.equals(responseMap.get("exit_code"))) {
            // Response is not a warning nor success - it's surely a failure.
            throw new PayaraClientException(message);
        }
    } else if (status.getReasonPhrase() == "Not Found") {
        // the REST resource can not be found (for optional resources it can be O.K.)
        message += " [status: " + status.getFamily() + " reason: " + status.getReasonPhrase() + "]";
        log.warning(message);
    } else {
        message += " [status: " + status.getFamily() + " reason: " + status.getReasonPhrase() + "]";
        log.severe(message);
        throw new ContainerException(message);
    }
    return responseMap;
}
Also used : HashMap(java.util.HashMap) ContainerException(org.glassfish.jersey.server.ContainerException) StatusType(javax.ws.rs.core.Response.StatusType)

Example 5 with ContainerException

use of org.glassfish.jersey.server.ContainerException in project jersey by jersey.

the class ServletContainer method doFilter.

private void doFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final String requestURI, final String servletPath, final String queryString) throws IOException, ServletException {
    // if we match the static content regular expression lets delegate to
    // the filter chain to use the default container servlets & handlers
    final Pattern p = getStaticContentPattern();
    if (p != null && p.matcher(servletPath).matches()) {
        chain.doFilter(request, response);
        return;
    }
    if (filterContextPath != null) {
        if (!servletPath.startsWith(filterContextPath)) {
            throw new ContainerException(LocalizationMessages.SERVLET_PATH_MISMATCH(servletPath, filterContextPath));
        //TODO:
        //            } else if (servletPath.length() == filterContextPath.length()) {
        //                // Path does not end in a slash, may need to redirect
        //                if (webComponent.getResourceConfig().getFeature(ResourceConfig.FEATURE_REDIRECT)) {
        //                    URI l = UriBuilder.fromUri(request.getRequestURL().toString()).
        //                            path("/").
        //                            replaceQuery(queryString).build();
        //
        //                    response.setStatus(307);
        //                    response.setHeader("Location", l.toASCIIString());
        //                    return;
        //                } else {
        //                    requestURI += "/";
        //                }
        }
    }
    final URI baseUri;
    final URI requestUri;
    try {
        final UriBuilder absoluteUriBuilder = UriBuilder.fromUri(request.getRequestURL().toString());
        // depending on circumstances, use the correct path to replace in the absolute request URI
        final String pickedUrlMapping = pickUrlMapping(request.getRequestURL().toString(), filterUrlMappings);
        final String replacingPath = pickedUrlMapping != null ? pickedUrlMapping : (filterContextPath != null ? filterContextPath : "");
        baseUri = absoluteUriBuilder.replacePath(request.getContextPath()).path(replacingPath).path("/").build();
        requestUri = absoluteUriBuilder.replacePath(requestURI).replaceQuery(ContainerUtils.encodeUnsafeCharacters(queryString)).build();
    } catch (final IllegalArgumentException iae) {
        setResponseForInvalidUri(response, iae);
        return;
    }
    final ResponseWriter responseWriter = serviceImpl(baseUri, requestUri, request, response);
    if (webComponent.forwardOn404 && !response.isCommitted()) {
        boolean hasEntity = false;
        Response.StatusType status = null;
        if (responseWriter.responseContextResolved()) {
            final ContainerResponse responseContext = responseWriter.getResponseContext();
            hasEntity = responseContext.hasEntity();
            status = responseContext.getStatusInfo();
        }
        if (!hasEntity && status == Response.Status.NOT_FOUND) {
            // lets clear the response to OK before we forward to the next in the chain
            // as OK is the default set by servlet containers before filters/servlets do any work
            // so lets hide our footsteps and pretend we were never in the chain at all and let the
            // next filter or servlet return the 404 if they can't find anything to return
            //
            // We could add an optional flag to disable this step if anyone can ever find a case where
            // this causes a problem, though I suspect any problems will really be with downstream
            // servlets not correctly setting an error status if they cannot find something to return
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) Response(javax.ws.rs.core.Response) ServletResponse(javax.servlet.ServletResponse) Pattern(java.util.regex.Pattern) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerException(org.glassfish.jersey.server.ContainerException) ResponseWriter(org.glassfish.jersey.servlet.internal.ResponseWriter) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI)

Aggregations

ContainerException (org.glassfish.jersey.server.ContainerException)8 IOException (java.io.IOException)4 OutputStreamWriter (java.io.OutputStreamWriter)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)2 Response (javax.ws.rs.core.Response)2 ContainerResponse (org.glassfish.jersey.server.ContainerResponse)2 TemplateException (freemarker.template.TemplateException)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 URI (java.net.URI)1 Charset (java.nio.charset.Charset)1 List (java.util.List)1 Pattern (java.util.regex.Pattern)1 PatternSyntaxException (java.util.regex.PatternSyntaxException)1 RequestDispatcher (javax.servlet.RequestDispatcher)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 ServletResponse (javax.servlet.ServletResponse)1