Example usage for javax.servlet.http HttpServletRequest setCharacterEncoding

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

Introduction

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

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:com.wibidata.shopping.servlet.SignInServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");

    final Kiji kiji = (Kiji) getServletContext().getAttribute(KijiContextListener.KIJI_ATTRIBUTE);

    final String login = request.getParameter("login");
    final String password = request.getParameter("password");

    if (null == login || login.isEmpty() || null == password || password.isEmpty()) {
        request.setAttribute("login", login);
        request.setAttribute("password", password);
        request.setAttribute("error", "All fields are required.");
        request.getRequestDispatcher("/WEB-INF/view/SignIn.jsp").forward(request, response);
        return;/*w ww  . j a v a 2  s. co m*/
    }

    final KijiTable userTable = kiji.openTable("kiji_shopping_user");
    final EntityId entityId = userTable.getEntityId(login);
    final KijiTableReader reader = userTable.openTableReader();
    try {
        // Authenticate the user.
        KijiDataRequestBuilder drBuilder = KijiDataRequest.builder();
        drBuilder.newColumnsDef().add("info", "password").add("info", "name");
        KijiDataRequest dataRequest = drBuilder.build();

        KijiRowData row = reader.get(entityId, dataRequest);
        if (!row.containsColumn("info", "password")
                || !BCrypt.checkpw(password, row.getMostRecentValue("info", "password").toString())) {
            request.setAttribute("login", login);
            request.setAttribute("error", "Invalid login or password.");
            request.getRequestDispatcher("/WEB-INF/view/SignIn.jsp").forward(request, response);
            return;
        }
        request.setAttribute("name", row.getMostRecentValue("info", "name").toString());
    } catch (KijiDataRequestException e) {
        throw new IOException(e);
    } finally {
        IOUtils.closeQuietly(reader);
        ResourceUtils.releaseOrLog(userTable);
    }

    // Set the login cookie for the user.
    request.getSession().setAttribute("login", login);
    request.getRequestDispatcher("/WEB-INF/view/SignedIn.jsp").forward(request, response);
}

From source file:com.slience.controller.AuthController.java

@RequestMapping("role/update")
@ResponseBody/*from www  .ja v  a 2s.  co m*/
public Map<String, ?> handRoleUpdateRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody Map<String, String> body) throws Exception {

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

    return null;
}

From source file:com.slience.controller.AuthController.java

@RequestMapping("user/update")
@ResponseBody/*from  ww  w  .  j a v  a 2s. c o m*/
public Map<String, ?> handUserUpdateRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody Map<String, String> body) throws Exception {

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

    return null;
}

From source file:org.biokoframework.http.fields.impl.JsonFieldsParser.java

@Override
public Fields safelyParse(HttpServletRequest request) throws RequestNotSupportedException {
    Reader reader;/*from w w  w  .  j a  v  a 2  s.c  o  m*/
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("utf-8");
        }
        reader = request.getReader();
        Writer writer = new StringWriter();
        IOUtils.copy(reader, writer);
        return Fields.fromJson(writer.toString());
    } catch (IOException exception) {
        // TODO log exception
        throw new RequestNotSupportedException(exception);
    }
}

From source file:de.betterform.agent.web.servlet.PlainHtmlServlet.java

/**
 * handles all interaction with the user during a form-session.
 * <p/>//from w  w w .jav  a2  s .c o m
 * Note: this method is only triggered if the
 * browser has javascript turned off.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    request.setCharacterEncoding("UTF-8");
    WebUtil.nonCachingResponse(response);

    WebProcessor webProcessor = WebUtil.getWebProcessor(request, response, session);
    try {

        webProcessor.setRequest(request);
        webProcessor.setResponse(response);
        webProcessor.handleRequest();
    } catch (Exception e) {
        webProcessor.close(e);
    }
}

From source file:com.ibm.watson.ta.retail.ImportHousingServlet.java

/**
 * Forward the request to the index.jsp file
 *
 * @param req the req/*  w  ww .ja v  a  2 s  .  c  o m*/
 * @param resp the resp
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    logger.info("forwarding...");

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL;
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();

        Request newReq = Request.Get(uri);
        newReq.addHeader("Authorization", "Basic c2ltcGx5cmV0czpzaW1wbHlyZXRz");
        logger.log(Level.SEVERE, "My custom log:" + queryStr);

        Executor executor = Executor.newInstance();
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:com.francelabs.datafari.servlets.admin.ZooKeeperConf.java

/**
 * @throws IOException/*  w w w . jav  a2  s .c  om*/
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    final JSONObject jsonResponse = new JSONObject();

    final PrintWriter out = response.getWriter();
    out.print(jsonResponse);
}

From source file:ua.aits.oblenergo_site.controller.AjaxAndFormController.java

@RequestMapping(value = "/system/users/deletedata.do", method = RequestMethod.POST)
public ModelAndView doDeleteUser(HttpServletRequest request) throws SQLException, ClassNotFoundException,
        InstantiationException, IllegalAccessException, UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    String user_id = request.getParameter("user_id");
    Users.deleteUser(user_id);/* w ww. j  av a2 s. c  o m*/
    return new ModelAndView("redirect:" + "/system/users");
}

From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//from w  w w .j av a2s  .c  o  m
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (!fileItem.isFormField()) {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext)
                                && !"PNG".equalsIgnoreCase(ext)) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR,
                                    "Invalid image. Please upload JPG or PNG file");
                            return (new MyProfileAction().execute(request, response));
                        }
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return (new MyProfileAction().execute(request, response));
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new MyProfileAction().execute(request, response));
            }
            if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file");
                return (new MyProfileAction().execute(request, response));
            }

            User user = loggedInUser;
            user.setProfilePicture(file);
            UserDAO.getInstance().setProfilePicture(user);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "", "Profile picture update"));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
    request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully");
    return (new MyProfileAction().execute(request, response));
}

From source file:org.apache.nutch.webapp.controller.NutchController.java

public final void execute(ComponentContext tileContext, HttpServletRequest request,
        HttpServletResponse response, ServletContext servletContext) throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    try {/*from  ww w  . j  ava  2 s .  c  om*/
        nutchPerform(tileContext, request, response, servletContext);
    } catch (Exception e) {
        LOG.info("Exception occured while executing nutch controller:");
        e.printStackTrace(LogUtil.getInfoStream(LOG));
    }
}