Example usage for javax.servlet.http HttpServletResponse setContentType

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

Introduction

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

Prototype


public void setContentType(String type);

Source Link

Document

Sets the content type of the response being sent to the client, if the response has not been committed yet.

Usage

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static void sendBytes(byte[] bytes, String filename, String contentType) {
    if (bytes != null) {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType(contentType);
        response.addHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", String.valueOf(bytes.length));
        ServletOutputStream os = null;/*from  www . j a v  a 2  s . co m*/
        try {
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException e) {
            LOGGER.error("Sending content failed {0}", filename, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close stream after sending", e);
                }
            }
        }
    }
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * .//from   w  w  w .  jav a 2s  .co  m
 * 
 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain",
 * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK",
 * "no-cache:false");
 * 
 * @param headers
 *            header"encoding:""no-cache:",UTF-8true.
 */
public static void render(final String contentType, final String content, final String... headers) {
    try {
        // headers
        String encoding = ENCODING_DEFAULT;
        boolean noCache = NOCACHE_DEFAULT;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else
                throw new IllegalArgumentException(headerName + "header");
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        // headers
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
            WebUtils.setNoCacheHeader(response);
        }

        response.getWriter().write(content);
        response.getWriter().flush();

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

/**
 * Call the HttpMethod and write all results and status to the HTTP response
 * object.//from   w  ww  .  ja  v  a  2 s .com
 * 
 * THIS IS THE REQUEST WE NEED TO DUPLICATE GET
 * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080
 * Connection: keep-alive Accept:
 * application/xml,application/xhtml+xml,text/
 * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0
 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
 * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch
 * Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D
 * 
 * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1
 * Accept:
 * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q
 * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding:
 * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta
 * Commons-HttpClient/3.1 Host: localhost:8080
 * 
 * @param proxyCommand
 * @param response
 * @param authenicate true to set Preemptive authentication
 */
public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) {
    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(proxyCommand);

    setDefaultHeaders(method);

    setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            /**
             * Copy all headers, except Transfer-Encoding which is getting set
             * set elsewhere. At this point response.containsHeader(
             * "Transfer-Encoding" ) is false, however it is getting set twice
             * according to wireshark, therefore we do not set it here.
             */
            if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) {
                response.setHeader(header.getName(), header.getValue());
            }
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        StringBuffer sb = new StringBuffer();
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            response.getOutputStream().write(bytes, 0, count);
            count = bis.read(bytes);
        }

        bis.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * //www  .  j  ava 2  s  .  c o  m
 * 
 * @param content
 * @param fileName
 * @param response
 */
public static void download(byte[] content, String fileName, HttpServletResponse response) {
    try {
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + content.length);
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(content);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a response to the client.// www  .  ja v  a2s .  c  o  m
 */
protected static void renderMessage(HttpServletResponse response, String message, String contentType)
        throws IOException {
    response.setContentType(contentType + "; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.print(message);
    out.flush();
    out.close();
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void registrarUsuarioConvocatoria(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    /*Enumeration<String> parameterNames = request.getParameterNames();
    String param;//from   w  ww.j a  va2  s  . com
    while(parameterNames.hasMoreElements()){
        param = parameterNames.nextElement();
        System.out.print(param);
        System.out.print(": ");
        System.out.print(request.getParameter(param));
    }*/

    ArrayList r = CtrlUsuario.registrarAConvocatoriaUsuario(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2"))); // parameter 1: idUsuario param2: idConv

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        obj.put("isError", true);
        obj.put("errorDescrip", r.get(1));
        out.print(obj);
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else {
        Util.errordeRespuesta(r, out);
    }
}

From source file:com.struts2ext.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }//from w  ww.  ja v a  2 s.c  o m

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:ispyb.client.common.util.FileUtil.java

/**
 * downloadFile//from  w ww.  j ava2  s  . c  om
 * 
 * @param fullFilePath
 * @param mimeType
 * @param response
 */
public static void DownloadFile(String fullFilePath, String mimeType, String attachmentFilename,
        HttpServletResponse response) {
    try {
        byte[] imageBytes = FileUtil.readBytes(fullFilePath);
        response.setContentLength(imageBytes.length);
        ServletOutputStream out = response.getOutputStream();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

        out.write(imageBytes);
        out.flush();
        out.close();

    } catch (FileNotFoundException fnf) {
        LOG.debug("[DownloadFile] File not found: " + fullFilePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ikon.util.WebUtils.java

/**
 * Prepare to send the file./* w ww .jav  a2s.c  om*/
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String agent = request.getHeader("USER-AGENT");

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (null != agent && -1 != agent.indexOf("MSIE")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

From source file:com.hbs.common.josn.JSONUtil.java

public static void writeJSONToResponse(HttpServletResponse response, String encoding, boolean wrapWithComments,
        String serializedJSON, boolean smd, boolean gzip, String contentType) throws IOException {
    String json = serializedJSON == null ? "" : serializedJSON;
    if (wrapWithComments) {
        StringBuilder sb = new StringBuilder("/* ");
        sb.append(json);//ww w  .  j a va 2 s .c  o  m
        sb.append(" */");
        json = sb.toString();
    }
    if (log.isDebugEnabled()) {
        log.debug("[JSON]" + json);
    }

    if (contentType == null) {
        contentType = "application/json";
    }
    response.setContentType((smd ? "application/json-rpc;charset=" : contentType + ";charset=") + encoding);
    if (gzip) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes());
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(encoding).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}