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:controllers.IndexServlet.java

private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    response.setContentType("text/plain");

    try {//  w ww  . j  a v  a 2s  . c o  m
        Part httpPostedFile = request.getPart("file");

        String fileName = "";
        for (String content : httpPostedFile.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                fileName = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }

        long curSize = httpPostedFile.getSize();
        if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0) {
            writer.write("{ \"error\": \"File size is incorrect\"}");
            return;
        }

        String curExt = FileUtility.GetFileExtension(fileName);
        if (!DocumentManager.GetFileExts().contains(curExt)) {
            writer.write("{ \"error\": \"File type is not supported\"}");
            return;
        }

        InputStream fileStream = httpPostedFile.getInputStream();

        fileName = DocumentManager.GetCorrectName(fileName);
        String fileStoragePath = DocumentManager.StoragePath(fileName, null);

        File file = new File(fileStoragePath);

        try (FileOutputStream out = new FileOutputStream(file)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = fileStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.flush();
        }

        writer.write("{ \"filename\": \"" + fileName + "\"}");

    } catch (IOException | ServletException e) {
        writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
    }
}

From source file:com.ewcms.component.util.Struts2Util.java

/**
 * ?contentTypeheaders./*from ww  w .  j  a v  a2s.c  o m*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            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) {
        ServletUtil.setNoCacheHeader(response);
    }

    return response;
}

From source file:com.ykun.commons.utils.excel.ExcelUtils.java

/**
 * xlscontent-type/*from  w  w w .j ava 2  s  . c  om*/
 *
 * @param response
 * @param fileName
 * @throws IOException
 */
private static void setContentType(HttpServletResponse response, String fileName) throws IOException {
    response.setContentType(CONTENT_TYPE);
    response.setHeader(HEADER_CONTENT_DISPOSITION,
            MessageFormat.format(PATTERN_DISPOSITION, URLEncoder.encode(fileName, CHARSET_UTF8)));
}

From source file:com.shallop.codedrill.common.web.struts2.Struts2Utils.java

/**
 * ?contentTypeheaders.//from w ww .  j  av  a2 s .  c om
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

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

    //      HttpServletResponse response = ServletActionContext.getResponse();
    HttpServletResponse response = null;

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

    return response;
}

From source file:net.sf.appstatus.web.pages.Resources.java

public static void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

    String location = null;/*w  w  w  .  j av  a 2s.  c o m*/
    String id = req.getParameter("resource");
    if (id == null) {
        id = req.getParameter("icon");
    }

    if (resources.containsKey(id)) {
        resp.setContentType(resources.get(id).getMimeType());
        location = resources.get(id).getLocation();
        InputStream is = Resources.class.getResourceAsStream(location);
        IOUtils.copy(is, resp.getOutputStream());
    } else {
        resp.sendError(404);
    }

}

From source file:fiftyone.mobile.detection.webapp.JavascriptProvider.java

static void sendJavaScript(HttpServletRequest request, HttpServletResponse response, Dataset dataSet,
        StringBuilder javascript) throws IOException {

    response.reset();//from   w  w  w  .  java 2s.  c o m
    response.setContentType("application/x-javascript");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Vary", "User-Agent");
    response.setHeader("Cache-Control", "public");
    response.setHeader("Expires", dataSet.nextUpdate.toString());
    response.setHeader("Last-Modified", dataSet.published.toString());
    try {
        response.setHeader("ETag", eTagHash(dataSet, request));
    } catch (Exception ex) {
        // The response doesn't support eTags. Nothing we can do.
    }
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Length", Integer.toString(javascript.length()));

    response.getOutputStream().println(javascript.toString());
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:com.sunway.cbm.util.web.ServletUtils.java

/**
 * ?xml?//from  w  ww.j a  v  a 2s.c o  m
 * 
 * @param response
 * @param object
 */
public static void responseXml(HttpServletResponse response, String xml) {
    try {
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(xml);
        response.getWriter().flush();
        response.getWriter().close();
    } catch (IOException e) {
        logger.debug(e.toString());
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CRUDUsuarios.java

protected static void leerUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UsuarioEntity e = CtrlAdmin.leerUsuario(request.getParameter("1")); // String nombre del usuario

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    JSONObject obj = new JSONObject();
    obj.put("id", e.getIdUsuario());
    obj.put("nombre", e.getNombres());
    obj.put("apellido", e.getApellidos());
    obj.put("tipoDocumento", e.gettDocumento());
    obj.put("documento", e.getDocumento());
    obj.put("contrasena", e.getPassword());
    obj.put("rol", e.getRol());
    out.print(obj);/*from ww  w . j a  v a 2  s . c  o  m*/
}

From source file:controllers.IndexServlet.java

private static void Convert(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    response.setContentType("text/plain");

    try {//from   ww w  .ja va 2s  .  c o  m
        String fileName = request.getParameter("filename");
        String fileUri = DocumentManager.GetFileUri(fileName);
        String fileExt = FileUtility.GetFileExtension(fileName);
        FileType fileType = FileUtility.GetFileType(fileName);
        String internalFileExt = DocumentManager.GetInternalExtension(fileType);

        if (DocumentManager.GetConvertExts().contains(fileExt)) {
            String key = ServiceConverter.GenerateRevisionId(fileUri);

            Pair<Integer, String> res = ServiceConverter.GetConvertedUri(fileUri, fileExt, internalFileExt, key,
                    true);

            int result = res.getKey();
            String newFileUri = res.getValue();

            if (result != 100) {
                writer.write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                return;
            }

            String correctName = DocumentManager
                    .GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + internalFileExt);

            URL url = new URL(newFileUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();

            if (stream == null) {
                throw new Exception("Stream is null");
            }

            File convertedFile = new File(DocumentManager.StoragePath(correctName, null));
            try (FileOutputStream out = new FileOutputStream(convertedFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
            }

            connection.disconnect();

            //remove source file ?
            //File sourceFile = new File(DocumentManager.StoragePath(fileName, null));
            //sourceFile.delete();

            fileName = correctName;
        }

        writer.write("{ \"filename\" : \"" + fileName + "\"}");

    } catch (Exception ex) {
        writer.write("{ \"error\": \"" + ex.getMessage() + "\"}");
    }
}

From source file:com.iyonger.apm.web.util.FileDownloadUtils.java

/**
 * Download the given file to the given {@link HttpServletResponse}.
 *
 * @param response {@link HttpServletResponse}
 * @param file     file path/*from  ww w  .ja v a 2s .c o m*/
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + file.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(file));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + file.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + file.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}