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:org.nsesa.editor.gwt.an.amendments.server.service.XMLExportService.java

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) throws IOException {
    try {/*from w w w .j av  a 2  s.  co m*/
        response.setContentType("text/xml");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + object.getAmendmentContainerID() + ".xml");
        response.setCharacterEncoding("UTF8");

        byte[] bytes = object.getBody().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setContentLength(bytes.length);
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException("Failed to xml export", e);
    }
}

From source file:fr.ippon.wip.http.reponse.Response.java

/**
 * Print the response content to and HttpServletResponse
 * /*from   w  ww  .j av  a  2s . c  o m*/
 * Set appropriate Content-Type, Charset and HTTP status code. Force
 * Content-Disposition to "attachment". Can handle binary content.
 * 
 * @param httpServletResponse
 * @throws IOException
 */
public void sendResponse(HttpServletResponse httpServletResponse) throws IOException {
    httpServletResponse.setContentType(mimeType);
    httpServletResponse.setCharacterEncoding(charset.name());
    httpServletResponse.setStatus(responseCode);
    if (isBinary()) {
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + getFileName() + "\"");
        OutputStream os = httpServletResponse.getOutputStream();
        IOUtils.copy(new ByteArrayInputStream(content), os);
        os.close();
    } else {
        String textContent = new String(content, charset);
        httpServletResponse.setContentLength(textContent.length());
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(textContent);
    }
}

From source file:no.dusken.aranea.view.FeedView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setContentType("application/rss+xml");
    response.setCharacterEncoding("UTF-8");
    List<Page> pages = (List<Page>) map.get("pages");
    Section section = (Section) map.get("section");
    feedtype = (String) map.get("feedType");
    log.debug("Feedtype is {}", feedtype);
    if (feedtype == null)
        feedtype = DEFAULT_FEEDTYPE;/*from  w  w w . ja  v  a2 s .c om*/
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(feedtype);
    feed.setEncoding("UTF-8");
    if (section != null) {
        feed.setTitle(section.getName() + " | Under Dusken");
    } else {
        feed.setTitle("Under Dusken");
    }
    feed.setLink("http://" + hostname);
    feed.setDescription("Nyheter fra Under Dusken, studentavisa i Trondheim");
    // log.debug(pages);
    if (pages != null) {
        for (Page page : pages) {
            SyndEntry entry = new SyndEntryImpl();
            entry.setTitle(page.getTitle());
            entry.setPublishedDate(page.getTimePublished().getTime());
            if (page instanceof Article) {
                Article article = (Article) page;
                if (article.getIssue() != null) {
                    entry.setLink("http://" + hostname + request.getContextPath() + "/"
                            + article.getParent().getName().toLowerCase() + "/"
                            + article.getIssue().getFromDate().get(Calendar.YEAR) + "/"
                            + article.getIssue().getIssue() + "/" + article.getID() + "/"
                            + article.getSafeTitle());
                } else {
                    entry.setLink("http://" + hostname + request.getContextPath() + "/"
                            + article.getParent().getName().toLowerCase() + "/" + article.getID() + "/"
                            + article.getSafeTitle());
                }
            } else {
                entry.setLink("http://" + hostname + request.getContextPath() + "/"
                        + page.getClass().getSimpleName() + "/" + page.getID() + "/" + page.getSafeTitle());
            }

            // does not validate in feedvalidator:
            // http://feedvalidator.org/check.cgi?url=http%3A%2F%2Fwww.underdusken.no%2Fdusken%2Ffeed%2Fud.xml
            // entry.setUpdatedDate(page.getModified().getTime());

            // people
            List<SyndPerson> authors = new ArrayList<SyndPerson>();
            for (Person p : page.getAuthors()) {
                SyndPerson sp = new SyndPersonImpl();
                sp.setName(p.getFirstname() + " " + p.getSurname());
                sp.setEmail(p.getUsername() + "@underdusken.no");
                authors.add(sp);
            }
            entry.setAuthors(authors);

            // description:
            SyndContent description = new SyndContentImpl();
            description.setType("text/html");
            //remove htmltags
            description
                    .setValue(page.getSummary() == null ? "" : page.getSummary().replaceAll("\\<.*?\\>", ""));
            entry.setDescription(description);
            entries.add(entry);
        }
    }
    feed.setEntries(entries);

    Writer writer = response.getWriter();
    SyndFeedOutput output = new SyndFeedOutput();
    output.output(feed, writer);
    writer.close();
}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  ww.j  ava 2s  .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:com.mirth.connect.server.servlets.ChannelServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*from   ww  w  . jav a 2s  .  co  m*/
        try {
            ChannelController channelController = ControllerFactory.getFactory().createChannelController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            ServerEventContext context = new ServerEventContext();
            context.setUserId(getCurrentUserId(request));

            if (operation.equals(Operations.CHANNEL_GET)) {
                response.setContentType(APPLICATION_XML);
                List<Channel> channels = null;
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                parameterMap.put("channel", channel);

                if (!isUserAuthorized(request, parameterMap)) {
                    channels = new ArrayList<Channel>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channels = redactChannels(request, channelController.getChannel(channel));
                } else {
                    channels = channelController.getChannel(channel);
                }

                serializer.toXML(channels, out);
            } else if (operation.equals(Operations.CHANNEL_UPDATE)) {
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                boolean override = Boolean.valueOf(request.getParameter("override")).booleanValue();
                parameterMap.put("channel", channel);
                parameterMap.put("override", override);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    // NOTE: This needs to be print rather than println to
                    // avoid the newline
                    out.print(channelController.updateChannel(channel, context, override));
                }
            } else if (operation.equals(Operations.CHANNEL_REMOVE)) {
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                parameterMap.put("channel", channel);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelController.removeChannel(channel, context);
                }
            } else if (operation.equals(Operations.CHANNEL_GET_SUMMARY)) {
                response.setContentType(APPLICATION_XML);
                List<ChannelSummary> channelSummaries = null;
                Map<String, Integer> cachedChannels = (Map<String, Integer>) serializer
                        .fromXML(request.getParameter("cachedChannels"));
                parameterMap.put("cachedChannels", cachedChannels);

                if (!isUserAuthorized(request, parameterMap)) {
                    channelSummaries = new ArrayList<ChannelSummary>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channelSummaries = redactChannelSummaries(request,
                            channelController.getChannelSummary(cachedChannels));
                } else {
                    channelSummaries = channelController.getChannelSummary(cachedChannels);
                }

                serializer.toXML(channelSummaries, out);
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:mml.handler.get.MMLResourceHandler.java

/**
 * Handle the request/*from w w w.  j a v  a  2 s .  c o  m*/
 * @param request the request
 * @param response the response
 * @param urn the remaining urn of the request
 * @throws MMLException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        String bodyStr = getDefaultResource(urn);
        setEncoding(request);
        response.setContentType("text/plain");
        response.setCharacterEncoding(encoding);
        response.getWriter().println(bodyStr);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    String email = request.getParameter("email");
    String activationKey = request.getParameter("activationKey");
    try {/* w  ww. java2 s .c  o  m*/
        if (email != null && activationKey != null) {
            Map<String, Object> user = userDirectory.useActivationKey(email, activationKey);

            if (user != null) {
                HttpSession session = request.getSession(true);
                session.setAttribute(USER, user);
            }

            // redirect always, if user is not logged in,
            // there will be a login screen
            response.sendRedirect("/member"); //TODO target make configurable
        } else {
            HttpSession session = request.getSession(false);
            String etag = request.getHeader("If-None-Match");
            @SuppressWarnings("unchecked")
            Map<String, Object> user = (session != null) ? (Map<String, Object>) session.getAttribute(USER)
                    : null;
            String userEtag = getEtag(user);

            if (etag != null && etag.equals(userEtag)) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.setHeader("ETag", userEtag);
                response.setHeader("Cache-Control", "private");
                response.setHeader("Vary", "Cookie");

                writeUserJSON(user, response);
            }
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

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

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

    // Setup response
    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");

    // Get Health checks
    List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale());
    int status = STATUS_OK;
    for (ICheckResult r : results) {

        if (r.getCode() != ICheckResult.OK && !r.isFatal() && status == STATUS_OK) {
            status = STATUS_WARN;/*from w w w . j  av a 2s  . c o  m*/
        }

        if (r.getCode() != ICheckResult.OK && r.isFatal()) {
            status = STATUS_ERROR;
            break;
        }
    }

    String btnClass = "btn-success";
    if (status == STATUS_WARN) {
        btnClass = "btn-warning";
    }

    if (status == STATUS_ERROR) {
        btnClass = "btn-danger";
    }

    // Get batchs status.
    IBatchManager manager = webHandler.getAppStatus().getBatchManager();

    String batchStatus = " progress-success ";
    String active = StringUtils.EMPTY;
    int width = 0;

    if (manager != null) {
        batchStatus = manager.getErrorBatches().size() > 0 ? " progress-danger " : " progress-success ";
        active = manager.getRunningBatches().size() > 0 ? " progress-striped active " : "";
        width = manager.getRunningBatches().size() + manager.getFinishedBatches().size() > 0 ? 100 : 0;
    }

    Writer w = resp.getWriter();
    w.append("<html>");
    w.append("<head>");
    w.append("<meta http-equiv=\"refresh\" content=\"60;\">");
    w.append("<link href=\"?resource=appstatus.css\" rel=\"stylesheet\">");
    w.append("</head>");
    w.append("<body style=\"background: #000; text-align: center; padding-top: 5%;\">");
    w.append("<p style=\"color: #fff; font-size: 200%;\" >" + webHandler.getApplicationName() + "</p>");
    w.append("<p style=\" padding-top: 10%;\"><a href=\"?p=status\" target=\"_blank\" class=\"btn btn-large "
            + btnClass + "\" >Status</a></p>");
    w.append("<div class=\"progress " + batchStatus + active
            + "\" style=\"margin-top: 5%; width: 90%; margin-left: 5%; margin-right: 5%;\">  <div class=\"bar\" style=\"width: "
            + width + "%;\"></div></div>");
    w.append("</body></html>");
}

From source file:se.acrend.christopher.server.web.control.BillingController.java

@RequestMapping(value = "/billing/billingCompleted")
public void billingCompleted(@RequestParam final String productId, final HttpServletResponse response)
        throws IOException {
    try {//  ww w .  j  a va 2s.  c  om
        SubscriptionInfo result = billingService.billingCompleted(productId);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Gson gson = ParserFactory.createParser();
        gson.toJson(result, response.getWriter());
    } catch (Exception e) {
        log.error("Kunde inte hmta prenumeration.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:costumetrade.user.login.BasicAuthenticateInterceptor.java

private void handleFailure(HttpServletResponse response, ApiResponse apiResponse) throws IOException {

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());

    PrintWriter out = response.getWriter();
    out.println(JSON.toJSONString(apiResponse));
    out.flush();//www. ja va2 s .c om
}