Example usage for javax.servlet.http HttpServletResponse getContentType

List of usage examples for javax.servlet.http HttpServletResponse getContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getContentType.

Prototype

public String getContentType();

Source Link

Document

Returns the content type used for the MIME body sent in this response.

Usage

From source file:de.mpg.mpdl.inge.pubman.web.viewItem.bean.FileBean.java

/**
 * Prepares the file the user wants to download
 * //from w  ww .j  a  v a 2 s .c o  m
 */
public String downloadFile() {

    try {
        LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication()
                .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper");

        String fileLocation = PropertyReader.getFrameworkUrl() + this.file.getContent();
        String filename = this.file.getName(); // Filename suggested in browser Save As dialog
        filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed
                                               // by the http-response (filename will be cutted after
                                               // the first empty space)
        String contentType = this.file.getMimeType(); // For dialog, try
        System.out.println("MIME: " + contentType);

        // application/x-download
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-disposition",
                "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        if (this.file.getDefaultMetadata() != null) {
            response.setContentLength(this.file.getDefaultMetadata().getSize());
        }

        response.setContentType(contentType);
        System.out.println("MIME: " + response.getContentType());

        byte[] buffer = null;
        if (this.file.getDefaultMetadata() != null) {
            try {
                GetMethod method = new GetMethod(fileLocation);
                method.setFollowRedirects(false);
                if (loginHelper.getESciDocUserHandle() != null) {
                    // downloading by account user
                    addHandleToMethod(method, loginHelper.getESciDocUserHandle());
                }

                // Execute the method with HttpClient.
                HttpClient client = new HttpClient();
                ProxyHelper.setProxy(client, fileLocation); // ????
                client.executeMethod(method);
                OutputStream out = response.getOutputStream();
                InputStream input = method.getResponseBodyAsStream();
                try {
                    if (this.file.getDefaultMetadata() != null) {
                        buffer = new byte[this.file.getDefaultMetadata().getSize()];
                        int numRead;
                        long numWritten = 0;
                        while ((numRead = input.read(buffer)) != -1) {
                            out.write(buffer, 0, numRead);
                            out.flush();
                            numWritten += numRead;
                        }
                        facesContext.responseComplete();
                    }
                } catch (IOException e1) {
                    logger.debug("Download IO Error: " + e1.toString());
                }
                input.close();
                out.close();
            } catch (FileNotFoundException e) {
                logger.debug("File not found: " + e.toString());
            }
        }
    } catch (Exception e) {
        logger.debug("File Download Error: " + e.toString());
        System.out.println(e.toString());
    }
    return null;
}

From source file:org.smigo.log.LogHandler.java

public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) {
    StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ")
            .append(request.getRequestURL()).append(separator);
    s.append("Auth type:").append(request.getAuthType()).append(separator);
    s.append("Principal:").append(request.getUserPrincipal()).append(separator);
    s.append(Log.create(request, response).toString()).append(separator);
    s.append("Headers:").append(separator);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator);
    }/*w ww. ja  v  a2  s .  c o m*/
    s.append(separator);
    s.append("####RESPONSE").append(separator);
    s.append("Status:").append(response.getStatus()).append(separator);
    s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator);
    s.append("Locale:").append(response.getLocale()).append(separator);
    s.append("Content type:").append(response.getContentType()).append(separator);

    s.append("Headers:").append(separator);
    s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh))
            .collect(Collectors.joining(separator)));

    final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER);
    if (start != null) {
        final long elapsedTime = System.nanoTime() - start;
        s.append(separator).append("####Request time elapsed:").append(elapsedTime);
        s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator);
    }
    return s.toString();
}

From source file:com.geemvc.view.DefaultStreamViewHandler.java

@Override
public void handle(Result result, RequestContext requestCtx) throws ServletException, IOException {
    HttpServletResponse response = (HttpServletResponse) requestCtx.getResponse();

    if (result.length() > 0) {
        response.setContentLength((int) result.length());
    }//from www. j a v a 2s .c o  m

    if (result.filename() != null) {
        if (result.attachment()) {
            response.setHeader("Content-disposition", "attachment; filename=" + result.filename());
        } else {
            response.setHeader("Content-disposition", "filename=" + result.filename());
        }
    }

    if (result.contentType() != null) {
        response.setContentType(result.contentType());
    }

    if (result.rangeSupport()) {
        // TODO: range-support
    }

    if (result.result() != null) {
        RequestHandler requestHandler = requestCtx.requestHandler();
        Method handlerMethod = requestHandler.handlerMethod();

        if (configuration.isJaxRsEnabled()) {
            MessageBodyWriter mbw = injector.getInstance(Providers.class).getMessageBodyWriter(
                    handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                    handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()));

            if (mbw != null
                    && mbw.isWriteable(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                            handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()))) {
                MultivaluedMap<String, Object> httpResponseHeaders = injector.getInstance(MultivaluedMap.class);

                mbw.writeTo(result.result(), handlerMethod.getReturnType(),
                        handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(),
                        MediaType.valueOf(response.getContentType()), httpResponseHeaders,
                        response.getOutputStream());
            } else {
                response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            }
        } else {
            log.info(
                    "Unable to convert the result object of type '{}' to the media type '{}' as the JAX-RS runtime has been disabled.",
                    () -> result.result().getClass().getName(), () -> response.getContentType());
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

        return;
    }

    if (result.stream() != null) {
        IOUtils.copy(result.stream(), response.getOutputStream());
    } else if (result.reader() != null) {
        IOUtils.copy(result.reader(), response.getOutputStream(), result.characterEncoding());
    } else if (result.output() != null) {
        response.getOutputStream().write(result.output().getBytes());
    } else {
        throw new IllegalStateException(
                "You must provide either a stream, a reader or a string output when using Results.stream(). ");
    }
}

From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java

@Override
@SuppressWarnings("squid:S3776")
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;/*from  www.  ja v  a 2  s  .c  om*/
    }

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!this.accepts(request)) {
        filterChain.doFilter(request, response);
        return;
    }

    final BufferingResponse capturedResponse = new BufferingResponse(response);

    filterChain.doFilter(request, capturedResponse);

    boolean doInclude = true;
    if (ArrayUtils.isNotEmpty(excludedWCMModes)) {
        // Test for configured WCM modes, where the indicators are not displayed
        WCMMode wcmmode = extractFromRequest(request);

        if (wcmmode != null) {
            for (String m : excludedWCMModes) {
                if (StringUtils.equalsIgnoreCase(wcmmode.name(), m)) {
                    doInclude = false;
                    break;
                }
            }
        } else {
            // No wcmmode could be extracted from the request
        }
    }

    // Get contents
    final String contents = capturedResponse.getContents();

    if (doInclude && contents != null && StringUtils.contains(response.getContentType(), "html")) {

        final int bodyIndex = contents.indexOf("</body>");

        if (bodyIndex != -1) {
            final PrintWriter printWriter = response.getWriter();

            printWriter.write(contents.substring(0, bodyIndex));

            if (StringUtils.isNotBlank(css)) {
                printWriter.write("<style>" + css + " </style>");
                printWriter.write("<div id=\"" + DIV_ID + "\">" + innerHTML + "</div>");
            }

            if (StringUtils.isNotBlank(titlePrefix)) {
                printWriter.printf(TITLE_UPDATE_SCRIPT, titlePrefix);
            }

            printWriter.write(contents.substring(bodyIndex));
            return;
        }
    }

    if (contents != null) {
        response.getWriter().write(contents);
    }
}

From source file:com.laxser.blitz.web.impl.thread.ActionEngine.java

private void applyHttpFeatures(final Invocation inv) throws UnsupportedEncodingException {
    HttpServletResponse response = inv.getResponse();
    if (StringUtils.isNotBlank(httpFeatures.charset())) {
        response.setCharacterEncoding(httpFeatures.charset());
        if (logger.isDebugEnabled()) {
            logger.debug("set response.characterEncoding by HttpFeatures:" + httpFeatures.charset());
        }/*  w ww  . j av  a 2  s. c o m*/
    }
    if (StringUtils.isNotBlank(httpFeatures.contentType())) {
        String contentType = httpFeatures.contentType();
        if (contentType.equals("json")) {
            contentType = "application/json";
        } else if (contentType.equals("xml")) {
            contentType = "text/xml";
        } else if (contentType.equals("html")) {
            contentType = "text/html";
        } else if (contentType.equals("plain") || contentType.equals("text")) {
            contentType = "text/plain";
        }
        response.setContentType(contentType);
        if (logger.isDebugEnabled()) {
            logger.debug("set response.contentType by HttpFeatures:" + response.getContentType());
        }
    }
}

From source file:architecture.ee.web.servlet.ViewRendererServlet.java

protected View resolvingView(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) {
    /**/*  w ww.  ja  v  a2 s  .c  o m*/
     * ? VIEW    ContentType ?  ?? ?  .
     */
    View view = (View) httpservletrequest.getAttribute(WebApplicatioinConstants.VIEW_ATTRIBUTE);
    if (view == null) {
        try {
            String viewName = translator.getViewName(httpservletrequest);
            ViewResolver viewresolver = getViewResolver(viewResolverName);
            view = viewresolver.resolveViewName(viewName, httpservletrequest.getLocale());
        } catch (Exception exception) {
            log.error(exception);
        }

        if (view != null && view instanceof AbstractView) {

            OutputFormat format = ServletUtils.getOutputFormat(httpservletrequest, httpservletresponse);
            if (log.isDebugEnabled())
                log.debug("architecture.ee.web.community.content: " + format);
            if (format == OutputFormat.XML) {
                httpservletresponse.setContentType(null);
                ((AbstractView) view).setContentType("text/xml;charset=UTF-8");
            } else if (format == OutputFormat.HTML) {
                httpservletresponse.setContentType(null);
                ((AbstractView) view).setContentType("text/html;charset=UTF-8");
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(
                "response architecture.ee.web.community.content type: " + httpservletresponse.getContentType());
        log.debug("architecture.ee.web.community.content type : " + view.getContentType());
    }
    return view;
}

From source file:com.groupon.odo.Proxy.java

/**
 * Log original response//www .ja va2s  . com
 *
 * @param httpServletResponse
 * @param history
 * @throws URIException
 */
private void logOriginalResponseHistory(HttpServletResponse httpServletResponse, History history,
        OutputStream outStream) throws URIException {
    RequestInformation requestInfo = requestInformation.get();
    if (requestInfo.handle && requestInfo.client.getIsActive()) {
        logger.info("Storing original response history");
        history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));
        history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));
        history.setOriginalResponseContentType(httpServletResponse.getContentType());
        history.setOriginalResponseData(outStream.toString());
        logger.info("Done storing");
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*  w w w . ja  v a 2  s  . c  o m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.groupon.odo.Proxy.java

/**
 * Log modified request/*from   w w w  .j a v a 2 s  .c om*/
 *
 * @param httpMethodProxyRequest
 * @param httpServletResponse
 * @param history
 */
private void logRequestHistory(HttpMethod httpMethodProxyRequest, HttpServletResponse httpServletResponse,
        History history) {
    try {
        if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {
            logger.info("Storing history");
            String createdDate;
            SimpleDateFormat sdf = new SimpleDateFormat();
            sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
            sdf.applyPattern("dd MMM yyyy HH:mm:ss");
            createdDate = sdf.format(new Date()) + " GMT";

            history.setCreatedAt(createdDate);
            history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));
            history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? ""
                    : httpMethodProxyRequest.getQueryString());
            history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));
            history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));
            history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));
            history.setResponseContentType(httpServletResponse.getContentType());
            history.setResponseData(requestInformation.get().outputString);
            HistoryService.getInstance().addHistory(history);
            logger.info("Done storing");
        }
    } catch (URIException e) {
        e.printStackTrace();
    }
}

From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java

protected PageInfo buildPage(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Invoke the next entity in the chain
    SerializableByteArrayOutputStream out = new SerializableByteArrayOutputStream();
    GenericResponseWrapper wrapper = new GenericResponseWrapper(response, out);
    Map<String, Serializable> cacheableRequestAttributes = new HashMap<String, Serializable>();

    // TODO: split the special include handling out into a separate method
    HttpServletResponse originalResponse = null;
    boolean isInclude = WebUtils.isIncludeRequest(request);
    if (isInclude) {
        originalResponse = WrappedResponseHolder.getWrappedResponse();
        WrappedResponseHolder.setWrappedResponse(wrapper);
    }//from w ww.  java  2s  .  c  o  m
    try {
        List<String> attributesBefore = toList(request.getAttributeNames());
        chain.doFilter(request, wrapper);
        List<String> attributesAfter = toList(request.getAttributeNames());
        attributesAfter.removeAll(attributesBefore);
        for (String attrName : attributesAfter) {
            Object value = request.getAttribute(attrName);
            if (value instanceof Serializable) {
                cacheableRequestAttributes.put(attrName, (Serializable) value);
            }
        }
    } finally {
        if (isInclude) {
            WrappedResponseHolder.setWrappedResponse(originalResponse);
        }
    }
    wrapper.flush();

    long timeToLiveSeconds = Integer.MAX_VALUE; // TODO cacheManager.getEhcache(context.cacheName).cacheConfiguration.timeToLiveSeconds;

    String contentType = wrapper.getContentType();
    if (!StringUtils.hasLength(contentType)) {
        contentType = response.getContentType();
    }

    return new PageInfo(wrapper.getStatus(), contentType, out.toByteArray(), false, timeToLiveSeconds,
            wrapper.getAllHeaders(), wrapper.getCookies(), cacheableRequestAttributes);
}