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:org.apache.shindig.gadgets.servlet.ProxyBase.java

/**
 * Sets cache control headers for the response.
 */// w  w  w.ja va2  s .  co m
@SuppressWarnings("boxing")
protected void setResponseHeaders(HttpServletRequest request, HttpServletResponse response,
        HttpResponse results) throws GadgetException {
    int refreshInterval = 0;
    if (results.isStrictNoCache() || "1".equals(request.getParameter(IGNORE_CACHE_PARAM))) {
        refreshInterval = 0;
    } else if (request.getParameter(REFRESH_PARAM) != null) {
        try {
            refreshInterval = Integer.valueOf(request.getParameter(REFRESH_PARAM));
        } catch (NumberFormatException nfe) {
            throw new GadgetException(GadgetException.Code.INVALID_PARAMETER,
                    "refresh parameter is not a number");
        }
    } else {
        refreshInterval = Math.max(60 * 60, (int) (results.getCacheTtl() / 1000L));
    }
    HttpUtil.setCachingHeaders(response, refreshInterval);

    // We're skipping the content disposition header for flash due to an issue with Flash player 10
    // This does make some sites a higher value phishing target, but this can be mitigated by
    // additional referer checks.
    if (!"application/x-shockwave-flash".equalsIgnoreCase(results.getHeader("Content-Type"))
            && !"application/x-shockwave-flash".equalsIgnoreCase(response.getContentType())) {
        response.setHeader("Content-Disposition", "attachment;filename=p.txt");
    }
    if (results.getHeader("Content-Type") == null) {
        response.setHeader("Content-Type", "application/octet-stream");
    }
}

From source file:org.apache.struts2.views.freemarker.FreemarkerResult.java

/**
 * Called before the execution is passed to template.process().
 * This is a generic hook you might use in subclasses to perform a specific
 * action before the template is processed. By default does nothing.
 * A typical action to perform here is to inject application-specific
 * objects into the model root/* w  w w . j  a v a  2 s  . co m*/
 *
 * @return true to process the template, false to suppress template processing.
 */
protected boolean preTemplateProcess(Template template, TemplateModel model) throws IOException {
    Object attrContentType = template.getCustomAttribute("content_type");

    HttpServletResponse response = ServletActionContext.getResponse();
    if (response.getContentType() == null) {
        if (attrContentType != null) {
            response.setContentType(attrContentType.toString());
        } else {
            String contentType = getContentType();

            if (contentType == null) {
                contentType = "text/html";
            }

            String encoding = template.getEncoding();

            if (encoding != null) {
                contentType = contentType + "; charset=" + encoding;
            }

            response.setContentType(contentType);
        }
    } else if (isInsideActionTag()) {
        //trigger com.opensymphony.module.sitemesh.filter.PageResponseWrapper.deactivateSiteMesh()
        response.setContentType(response.getContentType());
    }

    return true;
}

From source file:org.beanfuse.utils.web.DownloadHelper.java

public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inStream,
        String name, String display) {
    String attch_name = "";
    byte[] b = new byte[1024];
    int len = 0;//from   w w w  . j  a va  2s  .c  o m
    try {
        String ext = StringUtils.substringAfterLast(name, ".");
        if (StringUtils.isBlank(display)) {
            attch_name = getAttachName(name);
        } else {
            attch_name = display;
            if (!attch_name.endsWith("." + ext)) {
                attch_name += "." + ext;
            }
        }
        response.reset();
        String contentType = response.getContentType();
        if (null == contentType) {
            if (StringUtils.isEmpty(ext)) {
                contentType = "application/x-msdownload";
            } else {
                contentType = contentTypes.getProperty(ext, "application/x-msdownload");
            }
            response.setContentType(contentType);
            logger.debug("set content type {} for {}", contentType, attch_name);
        }
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + encodeAttachName(request, attch_name) + "\"");
        while ((len = inStream.read(b)) > 0) {
            response.getOutputStream().write(b, 0, len);
        }
        inStream.close();
    } catch (Exception e) {
        logger.warn("download file error=" + attch_name, e);
    }
}

From source file:org.beangle.web.io.DefaultStreamDownloader.java

protected void addContent(HttpServletRequest request, HttpServletResponse response, String attach) {
    String contentType = response.getContentType();
    if (null == contentType) {
        contentType = mimeTypeProvider.getMimeType(StringUtils.substringAfterLast(attach, "."),
                "application/x-msdownload");
        response.setContentType(contentType);
        logger.debug("set content type {} for {}", contentType, attach);
    }/*from  w w  w . j a v a  2s .c o m*/
    String encodeName = encodeAttachName(request, attach);
    response.setHeader("Content-Disposition", "attachment; filename=" + encodeName);
    response.setHeader("Location", encodeName);
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given
 * {@link HttpServletResponse}./*from  w  w w  .ja v  a  2 s .  com*/
 *
 * @param httpMethodProxyRequest    An object representing the proxy request to be made
 * @param httpServletResponse       An object by which we can send the proxied response back to the client
 * @throws IOException              Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException         Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    //        String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */ ) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + HEADER_LOCATION + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            httpServletResponse
                    .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling. See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(HEADER_CONTENT_LENGTH, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) {
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

    if (isBodyParameterGzipped(responseHeaders)) {
        LOGGER.trace("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(HEADER_LOCATION, response);
            httpServletResponse.setContentLength(response.length());
        } else {
            bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody());
            httpServletResponse.setContentLength(bodyBytes.length);
        }
    }

    if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) {
        LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
        LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
        httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
        httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
        IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
}

From source file:org.codehaus.groovy.grails.web.metaclass.RenderDynamicMethod.java

private void setContentType(HttpServletResponse response, String contentType, String encoding,
        boolean contentTypeIsDefault) {
    if (response.getContentType() == null || !contentTypeIsDefault) {
        response.setContentType(GrailsWebUtil.getContentType(contentType, encoding));
    }//from   w  ww  .  ja v a 2 s.  c  o  m
}

From source file:org.codehaus.groovy.grails.web.metaclass.RenderDynamicMethod.java

private boolean isJSONResponse(HttpServletResponse response) {
    String contentType = response.getContentType();
    return contentType != null
            && (contentType.indexOf("application/json") > -1 || contentType.indexOf("text/json") > -1);
}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/download")
public String download(Model model, @RequestHeader("User-Agent") String userAgent,
        @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception {
    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    StringBuilder sb = new StringBuilder();

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {//  w w w .  ja va2 s.  c o m

        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            sb.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                sb.append(File.separator);
            }
            sb.append(uniqueFilename);
            File file = new File(sb.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);

        response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
        sb.setLength(0);
        if (userAgent.indexOf("MSIE5.5") > -1) {
            sb.append("filename=");
        } else {
            sb.append("attachment; filename=");
        }
        sb.append(encodedRealFilename);
        response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());
        logger.debug("header: {}", sb.toString());
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/view")
public String view(Model model, @RequestParam("fileId") String fileId, HttpServletResponse response)
        throws Exception {
    StringBuilder stringBuilder = null;

    FileDTO fileDTO;/*from  w w w  .j  a va  2 s.c  o  m*/
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;

    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();
    try {
        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            stringBuilder = new StringBuilder();
            stringBuilder.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                stringBuilder.append(File.separator);
            }
            stringBuilder.append(uniqueFilename);
            File file = new File(stringBuilder.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        response.setContentType(fileDTO.getContentType());

        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ?? ??.//from www. j  ava 2 s  .  c o  m
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}