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:no.dusken.aranea.admin.control.VcardController.java

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws PageNotFoundException, ServletRequestBindingException {

    response.setContentType("text/x-vcard");
    response.setCharacterEncoding("UTF-8");
    Map<String, Object> map = new HashMap<String, Object>();

    Set<Person> persons = new HashSet<Person>();

    if (request.getParameter("username") != null) {

        Person person;//from  ww  w . j  a va  2  s  .c o m
        String username = ServletRequestUtils.getRequiredStringParameter(request, "username");
        person = personService.getPersonByUsername(username);

        if (person == null) {
            //response.sendError(HttpServletResponse.SC_NOT_FOUND,
            //      "No such person: " + username);
            //Throwing exception so this can be threated as a 404 error on a higher level
            throw new PageNotFoundException("Person with username: " + username + " not found.");
        }
        persons.add(person);
        response.setHeader("Content-Disposition", "inline; filename=" + person.getUsername() + ".vcf");
    } else if (request.getParameter("active") != null) {
        boolean active = ServletRequestUtils.getRequiredBooleanParameter(request, "active");
        response.setHeader("Content-Disposition", "inline; filename=contacts.vcf");
        persons.addAll(personService.getPersonsByActive(active));
    } else if (request.getParameter("role") != null) {
        String r = ServletRequestUtils.getRequiredStringParameter(request, "role");
        Role role = roleService.getRolesByName(r);
        response.setHeader("Content-Disposition", "inline; filename=" + r + "_contacts.vcf");
        // only get active members having that role
        persons.addAll(personService.getPersons(role, true));
    } else {
        throw new PageNotFoundException("Missing parameter");
    }

    map.put("persons", persons);

    // add images <username, base64image>
    Map<String, String> images = new HashMap<String, String>();
    for (Person p : persons) {
        if (p.getPortrait() != null) {
            try {
                String imageString = imageUtils.getBase64Image(p.getPortrait(), imageWidth, imageHeight);
                // have to add spaces, vcard demands intendation
                imageString = imageString.replaceAll("\n", "\n ");
                images.put(p.getUsername(), imageString);
            } catch (Exception e) {
                // ignore, no image added
            }
        }
    }
    map.put("images", images);

    map.put("formatter", new SimpleDateFormat("yyyy-MM-dd"));

    return new ModelAndView("no/dusken/aranea/base/admin/person/vcard", map);
}

From source file:com.gae.ImageUpServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("utf-8");
    PrintWriter out = resp.getWriter();

    op = req.getParameter("op");
    kind = req.getParameter("kind");
    skey = req.getParameter("skey");
    id = req.getParameter("id").split(",");
    val = req.getParameter("val").split("<p>");
    //for(int i=0; i<id.length; i++ ){
    //   if(id[i].equals("filetitle")){
    //      //filetitle = val[i];
    //      imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
    //   }//from   w  w  w.  ja v a  2 s . c  o  m
    //}
    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filetitle);   
    out.println("");
}

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

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

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {/* w ww. ja  v a  2s  . c o  m*/
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

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

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } 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:org.nsesa.editor.gwt.an.amendments.server.service.PdfExportService.java

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".pdf");
    response.setCharacterEncoding("UTF8");
    final String content = object.getBody();
    final InputSource inputSource;
    byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
    inputSource = new InputSource(new ByteArrayInputStream(bytes));

    try {//from  w w w . j a v a2 s.c o  m
        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(sw.toString(), editorUrl + "/");
        renderer.layout();
        renderer.createPDF(response.getOutputStream());
        response.setContentLength(sw.toString().length());
        response.flushBuffer();

    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    } catch (DocumentException e) {
        throw new RuntimeException("Export to pdf failed", e);
    }

}

From source file:com.log4ic.compressor.servlet.CompressionServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf8");
    PrintWriter writer = resp.getWriter();
    //TODO ?,?//from ww w .  java  2  s. com
    try {
        Compressor.compress(req, resp, cacheManager, fileDomain);
    } catch (QueryStringEmptyException e) {
        logger.error("?.", e);
        //501 - Not Implemented ?????
        resp.setStatus(501);
        writer.write("?." + e.getMessage());
    } catch (UnsupportedFileTypeException e) {
        logger.error("???.", e);
        //501 - Not Implemented ?????
        resp.setStatus(501);
        writer.write("???." + e.getMessage());
    } catch (CompressionException e) {
        logger.error("?.", e);
        //501 - Not Implemented ?????
        resp.setStatus(501);
        writer.write("?." + e.getMessage());
    } catch (GssParserException e) {
        logger.error("?,CSS.", e);
        //501 - Not Implemented ?????
        resp.setStatus(501);
        writer.write("?,CSS." + e.getMessage());
    } catch (LessException e) {
        logger.error("?,CSS.", e);
        //501 - Not Implemented ?????
        resp.setStatus(501);
        writer.write("?,CSS." + e.getMessage());
    }
}

From source file:info.magnolia.cms.security.auth.callback.FormClientCallback.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response) {
    try {/*from   w  ww  .j  a  v  a 2 s.  co m*/
        if (!response.isCommitted()) {
            response.setContentType("text/html");
            if (null == request.getCharacterEncoding()) {
                response.setCharacterEncoding(MIMEMapping.getContentEncodingOrDefault("text/html"));
            }
        }
        FreemarkerUtil.process(getLoginForm(), getMessages(), response.getWriter());
    } catch (Throwable t) {
        log.error("exception while writing login template", t);
    }
}

From source file:com.shyshlav.functions.filework.download_image.java

public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8"); //  
    response.setCharacterEncoding("UTF-8");
    filePath = request.getSession().getServletContext().getInitParameter("avathars");
    System.out.println(filePath);
    isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipart);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (!isMultipart) {
        return "  ";
    }//from  w  w  w .j  a  va2s  . co m
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\test"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        //String name,String password,String email,String surname,String link_to_image,String about_me,String id
        String name = null;
        String password = null;
        String re_password = null;
        String surname = null;
        String about_me = null;
        String id = null;
        String link_to_server = null;
        String email = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                String fieldname = fi.getFieldName();
                String fieldvalue = fi.getString();
                if (fieldname.equals("name")) {
                    name = fi.getString("UTF-8");
                } else if (fieldname.equals("surname")) {
                    surname = fi.getString("UTF-8");
                } else if (fieldname.equals("password")) {
                    password = fi.getString("UTF-8");
                } else if (fieldname.equals("re_password")) {
                    re_password = fi.getString("UTF-8");
                } else if (fieldname.equals("about_me")) {
                    about_me = fi.getString("UTF-8");
                } else if (fieldname.equals("id")) {
                    id = fi.getString("UTF-8");
                } else if (fieldname.equals("email")) {
                    email = fi.getString("UTF-8");
                }
                System.out.println(fieldname + fieldvalue);
                if (fieldname == null || fieldvalue == null) {
                    return "? ? ? ";
                }
            }
            if (!fi.isFormField()) {
                if (!password.equals(re_password)) {
                    System.out.println(password + " - " + re_password);
                    return "  ?";
                }
                // Get the uploaded file parameters
                String fileName = email + ".png";
                link_to_server = "/musicbox/avathars/" + email + ".png".trim();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                System.out.println("Uploaded Filename: " + filePath + fileName);
            }
        }
        System.out.println(link_to_server);
        updateUser um = new updateUser();
        um.updateUser(name, password, surname, link_to_server, about_me, id);
    } catch (Exception ex) {
        System.out.println(ex);
        return "    1 ";
    }
    return "ok";
}

From source file:fi.hoski.web.forms.EventServlet.java

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

    // 1. event type
    EventType eventType;/*ww  w.  jav a 2 s. co  m*/
    try {
        eventType = EventType.valueOf(request.getParameter("eventType"));
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: eventType");
        return;
    }

    // 2. earliest date
    Date startDate;
    try {
        String evd = request.getParameter("startDate");
        startDate = evd != null ? new Date(Long.parseLong(evd)) : null;
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: eventDate");
        return;
    }

    // 3. max count    
    Integer maxCount;
    try {
        String maxc = request.getParameter("maxCount");
        maxCount = maxc != null ? new Integer(maxc) : null;
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: maxCount");
        return;
    }

    // 4. get events of said type
    List<Event> events = eventManager.getEvents(eventType, new Day(startDate), maxCount);

    // 5. write json
    response.setContentType("application/json");

    try {
        JSONArray jsonEvents = new JSONArray();
        for (Event event : events) {
            JSONObject e = new JSONObject(event.getAll());
            e.put("reservations", event.getChildCount());
            e.put("isFull", event.isFull());
            e.put("key", event.createKeyString());
            Day d = (Day) event.get(Event.EventDate);
            e.put("eventDate", d.getDate().getTime());
            e.put("eventName", d);
            jsonEvents.put(e);
        }

        JSONObject json = new JSONObject();

        json.put("events", jsonEvents);
        json.write(response.getWriter());
    } catch (JSONException e) {
        throw new ServletException(e);
    }
}

From source file:be.iminds.aiolos.ui.CommonServlet.java

protected void renderJSON(HttpServletResponse response, Locale locale) throws IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final PrintWriter pw = response.getWriter();
    writeJSON(pw, locale);/*w w  w.j  a  va  2s .  co  m*/
}

From source file:com.ecs.cms.web.mvc.view.MappingJacksonJsonView.java

@Override
protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType(getContentType());
    response.setCharacterEncoding(this.encoding.getJavaName());
    if (this.disableCaching) {
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
        response.addDateHeader("Expires", 1L);
    }// w w w  .j a v a2 s.co  m
}