Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

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

Introduction

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

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:com.github.thorqin.webapi.FileManager.java

/**
 * Download file by specified file id// www  . j a  v a 2 s.  c  om
 *
 * @param response Servlet response
 * @param request Pass request parameter to provide user agent information
 * to properly process utf-8 filename
 * @param fileId File ID which generated by uploaded or manually created
 * file
 * @throws ServletException
 * @throws IOException
 */
public void downloadFile(String fileId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");

    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (!dataFile.exists()) {
        Dispatcher.send(response, HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    FileInfo info;
    try {
        String jsonFile = uploadDir + "/" + fileId + ".json";
        info = Serializer.loadJsonFile(jsonFile, FileInfo.class);
    } catch (Exception ex) {
        Dispatcher.send(response, HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    String filename;
    try {
        if (info.fileName != null) {
            filename = URLEncoder.encode(info.fileName, "utf-8").replace("+", "%20");
        } else {
            filename = "download.dat";
        }
    } catch (UnsupportedEncodingException e1) {
        filename = "download.dat";
        e1.printStackTrace();
    }
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType(info.mimeType == null ? unknowMimeType : info.mimeType);

    UserAgentInfo uaInfo = UserAgentUtil.parse(request);
    if (uaInfo.browser == BrowserType.FIREFOX) {
        response.addHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "\"");
    } else {
        response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    }
    try (OutputStream os = response.getOutputStream()) {
        try (InputStream is = new FileInputStream(dataFile)) {
            int length;
            byte[] buffer = new byte[4096];
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
        }
    }
}

From source file:com.ucap.uccc.cmis.impl.webservices.CmisWebServicesServlet.java

private void printError(HttpServletRequest request, HttpServletResponse response, String message)
        throws ServletException, IOException {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.setContentType("text/xml");
    response.setCharacterEncoding(IOUtils.UTF8);

    PrintWriter pw = response.getWriter();

    String messageEscaped = StringEscapeUtils.escapeXml(message);

    pw.println("<?xml version='1.0' encoding='UTF-8'?>");
    pw.println("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    pw.println("<S:Body>");
    pw.println("<S:Fault>");
    pw.println("<faultcode>S:Client</faultcode>");
    pw.println("<faultstring>" + messageEscaped + "</faultstring>");
    pw.println("<detail>");
    pw.println("<cmisFault xmlns=\"http://docs.oasis-open.org/ns/cmis/messaging/200908/\">");
    pw.println("<type>runtime</type>");
    pw.println("<code>0</code>");
    pw.println("<message>" + messageEscaped + "</message>");
    pw.println("</cmisFault>");
    pw.println("</detail>");
    pw.println("</S:Fault>");
    pw.println("</S:Body>");
    pw.println("</S:Envelope>");

    pw.flush();//from   w  w w .j  ava  2 s  .co  m
}

From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java

/**
 * Download file by specified file id/*from  w  ww  . j ava 2  s. c o m*/
 *
 * @param response Servlet response
 * @param request Pass request parameter to provide user agent information
 * to properly process utf-8 filename
 * @param fileId File ID which generated by uploaded or manually created
 * file
 * @throws ServletException When send response failed
 * @throws java.io.IOException When cannot download file
 */
public void downloadFile(String fileId, String fileName, String mimeType, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    FileInfo info = getFileInfo(fileId);
    if (info == null) {
        ServletUtils.send(response, HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    String filePath = fileIdToPath(fileId);
    File dataFile = new File(filePath + ".data");
    if (fileName == null)
        fileName = info.fileName;
    if (mimeType == null)
        mimeType = info.mimeType;
    ServletUtils.download(request, response, dataFile, fileName, mimeType);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.json.JsonArrayProducer.java

public final void process(HttpServletResponse resp) throws IOException {
    JSONArray jsonArray = null;/*from  www  .  j  a  v a  2s  . c  o m*/
    try {
        jsonArray = process();
    } catch (Exception e) {
        log.error("Failed to create JSON response" + e);
        resp.setStatus(500 /* HttpURLConnection.HTTP_SERVER_ERROR */);
    }

    if (jsonArray == null) {
        jsonArray = new JSONArray();
    }

    log.debug("Response to JSON request: " + jsonArray.toString());

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("application/json;charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(jsonArray.toString());
}

From source file:org.osmsurround.ae.search.SearchController.java

@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody List<Amenity> get(BoundingBox boundingBox, HttpServletRequest request,
        HttpServletResponse resp) throws IOException {
    long time = System.currentTimeMillis();

    String[] show = request.getParameterValues("show");
    String[] hide = request.getParameterValues("hide");

    List<Amenity> amenities = searchService.findAmenities(boundingBox, new FilterSet(show, hide));
    log.info("found: " + amenities.size() + " in " + (System.currentTimeMillis() - time) + " ms");

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");
    resp.addHeader("Cache-Control", "no-cache");
    resp.addHeader("Pragma", "no-cache");
    return amenities;
}

From source file:com.lecheng.cms.servlet.ConnectorServlet.java

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * //from   w w  w .  j  a  v a2s.c o  m
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    // logger.debug("Parameter Command: {}", commandStr);
    // logger.debug("Parameter Type: {}", typeStr);
    // logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {
                // String newFolderStr =
                // UtilsFile.sanitizeFolderName(request.getParameter("NewFolderName"));
                /*
                 * liwei 
                 */
                String tempStr = request.getParameter("NewFolderName");
                tempStr = new String(tempStr.getBytes("iso8859-1"), "utf-8");
                String newFolderStr = UtilsFile.sanitizeFolderName(tempStr);

                // logger.debug("Parameter NewFolderName: {}",
                // newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }

    out.print(xr);
    out.flush();
    out.close();
    // logger.debug("Exiting ConnectorServlet#doGet");
}

From source file:com.rabbitstewdio.build.maven.tomcat.AbstractContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getPathInfo();

    InputStream in = findResource(filename);
    if (in == null) {
        log.warn("Unable to find [" + filename + "] on " + getServletName());
        response.setStatus(404);/* w ww  . j a va 2 s. c  o m*/
        return;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(in, bout);

    response.setCharacterEncoding("UTF-8");

    String mimeType = getServletContext().getMimeType(filename);
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    response.addDateHeader("Expires", 0L);
    response.setDateHeader(LAST_MODIFIED, new Date().getTime());
    response.setContentLength(bout.size());
    response.getOutputStream().write(bout.toByteArray());
    response.flushBuffer();
}

From source file:com.joliciel.jochre.search.web.JochreSearchServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from ww  w . ja v  a2 s  .  c o  m*/
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");

        JochreSearchProperties props = JochreSearchProperties.getInstance(this.getServletContext());

        String command = req.getParameter("command");
        if (command == null) {
            command = "search";
        }

        if (command.equals("purge")) {
            JochreSearchProperties.purgeInstance();
            searcher = null;
            return;
        }

        Map<String, String> argMap = new HashMap<String, String>();
        @SuppressWarnings("rawtypes")
        Enumeration params = req.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = (String) params.nextElement();
            String value = req.getParameter(paramName);
            argMap.put(paramName, value);
        }

        SearchServiceLocator searchServiceLocator = SearchServiceLocator.getInstance();
        SearchService searchService = searchServiceLocator.getSearchService();

        double minWeight = 0;
        int titleSnippetCount = 1;
        int snippetCount = 3;
        int snippetSize = 80;
        boolean includeText = false;
        boolean includeGraphics = false;
        String snippetJson = null;
        Set<Integer> docIds = null;

        Set<String> handledArgs = new HashSet<String>();
        for (Entry<String, String> argEntry : argMap.entrySet()) {
            String argName = argEntry.getKey();
            String argValue = argEntry.getValue();
            argValue = URLDecoder.decode(argValue, "UTF-8");
            LOG.debug(argName + ": " + argValue);

            boolean handled = true;
            if (argName.equals("minWeight")) {
                minWeight = Double.parseDouble(argValue);
            } else if (argName.equals("titleSnippetCount")) {
                titleSnippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetCount")) {
                snippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetSize")) {
                snippetSize = Integer.parseInt(argValue);
            } else if (argName.equals("includeText")) {
                includeText = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("includeGraphics")) {
                includeGraphics = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("snippet")) {
                snippetJson = argValue;
            } else if (argName.equalsIgnoreCase("docIds")) {
                if (argValue.length() > 0) {
                    String[] idArray = argValue.split(",");
                    docIds = new HashSet<Integer>();
                    for (String id : idArray)
                        docIds.add(Integer.parseInt(id));
                }
            } else {
                handled = false;
            }
            if (handled) {
                handledArgs.add(argName);
            }
        }
        for (String argName : handledArgs)
            argMap.remove(argName);

        if (searcher == null) {
            String indexDirPath = props.getIndexDirPath();
            File indexDir = new File(indexDirPath);
            LOG.info("Index dir: " + indexDir.getAbsolutePath());
            searcher = searchService.getJochreIndexSearcher(indexDir);
        }

        if (command.equals("search")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            searcher.search(query, out);
            out.flush();
        } else if (command.equals("highlight") || command.equals("snippets")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            if (docIds == null)
                throw new RuntimeException("Command " + command + " requires docIds");

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(minWeight);
            highlightManager.setIncludeText(includeText);
            highlightManager.setIncludeGraphics(includeGraphics);
            highlightManager.setTitleSnippetCount(titleSnippetCount);
            highlightManager.setSnippetCount(snippetCount);
            highlightManager.setSnippetSize(snippetSize);

            Set<String> fields = new HashSet<String>();
            fields.add("text");

            if (command.equals("highlight"))
                highlightManager.highlight(highlighter, docIds, fields, out);
            else
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            out.flush();
        } else if (command.equals("imageSnippet")) {
            String mimeType = "image/png";
            response.setContentType(mimeType);
            if (snippetJson == null)
                throw new RuntimeException("Command " + command + " requires a snippet");
            Snippet snippet = new Snippet(snippetJson);

            if (LOG.isDebugEnabled()) {
                Document doc = searcher.getIndexSearcher().doc(snippet.getDocId());
                LOG.debug("Snippet in " + doc.get("id") + ", path: " + doc.get("path"));
            }

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            ImageSnippet imageSnippet = highlightManager.getImageSnippet(snippet);
            OutputStream os = response.getOutputStream();
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            BufferedImage image = imageSnippet.getImage();
            ImageReader imageReader = ImageIO.getImageReadersByMIMEType(mimeType).next();
            ImageWriter imageWriter = ImageIO.getImageWriter(imageReader);
            imageWriter.setOutput(ios);
            imageWriter.write(image);
            ios.flush();
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    }
}

From source file:ru.org.linux.spring.AbstractRomeView.java

@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    SyndFeed feed = new SyndFeedImpl();
    feed.setEncoding("utf-8");
    String feedType = (String) model.get("feed-type");
    if (StringUtils.isEmpty(feedType)) {
        feedType = "rss";
    }//w  ww .j a v a2 s.  co  m
    feed.setFeedType(feedTypes.get(feedType));
    createFeed(feed, model);
    response.setContentType(contentTypes.get(feedType));
    response.setCharacterEncoding("UTF-8");
    SyndFeedOutput output = new SyndFeedOutput();
    output.output(feed, response.getWriter());
}

From source file:com.shangde.common.util.FCKConnectorServlet.java

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * //w  w  w .  j a  v  a2s . c  o m
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {
                String newFolderStr = UtilsFile.sanitizeFolderName(request.getParameter("NewFolderName"));
                logger.debug("Parameter NewFolderName: {}", newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }

    out.print(xr);
    out.flush();
    out.close();
    logger.debug("Exiting ConnectorServlet#doGet");
}