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.ProductServlet.java

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

    request.setCharacterEncoding("UTF-8");

    final String productId = request.getParameter("id");

    final Kiji kiji = (Kiji) getServletContext().getAttribute(KijiContextListener.KIJI_ATTRIBUTE);
    final KijiTable productTable = kiji.openTable("kiji_shopping_product");

    final KijiTableReader reader = productTable.openTableReader();
    try {//from  w  w  w  . j  ava 2  s.  c om
        final KijiDataRequestBuilder drBuilder = KijiDataRequest.builder();
        drBuilder.newColumnsDef().add("info", "name").add("info", "description").add("info", "thumbnail")
                .add("info", "thumbnail_xl").add("info", "price").add("info", "inventory")
                .add("info", "description_words").add("info", "category");
        final KijiDataRequest dataRequest = drBuilder.build();

        final KijiRowData row = reader.get(productTable.getEntityId(productId), dataRequest);
        if (row.containsColumn("info", "name")) {
            Product product = new Product();
            product.setId(productId);
            product.setName(row.getMostRecentValue("info", "name").toString());
            if (row.containsColumn("info", "description")) {
                product.setDescription(row.getMostRecentValue("info", "description").toString());
            }
            if (row.containsColumn("info", "thumbnail")) {
                product.setThumbnail(row.getMostRecentValue("info", "thumbnail").toString());
            }
            if (row.containsColumn("info", "thumbnail_xl")) {
                product.setThumbnailXL(row.getMostRecentValue("info", "thumbnail_xl").toString());
            }
            if (row.containsColumn("info", "price")) {
                product.setPrice(row.<Double>getMostRecentValue("info", "price"));
            }
            if (row.containsColumn("info", "inventory")) {
                product.setInventory(row.<Long>getMostRecentValue("info", "inventory"));
            }
            if (row.containsColumn("info", "description_words")) {
                product.setWords(
                        getWords(row.<DescriptionWords>getMostRecentValue("info", "description_words")));
            }
            if (row.containsColumn("info", "category")) {
                product.setCategory(row.getMostRecentValue("info", "category").toString());
            }
            request.setAttribute("product", product);
        }
    } catch (KijiDataRequestException e) {
        throw new IOException(e);
    } finally {
        IOUtils.closeQuietly(reader);
        ResourceUtils.releaseOrLog(productTable);
    }

    // Rate the item if necessary.
    final String rating = request.getParameter("rate");
    final boolean isLoggedIn = null != request.getSession().getAttribute("login");
    if (isLoggedIn) {
        final String login = request.getSession().getAttribute("login").toString();
        final KijiTable userTable = kiji.openTable("kiji_shopping_user");
        try {
            if (null != rating) {
                // Write the user's rating to the user table.
                final KijiTableWriter writer = userTable.openTableWriter();
                try {
                    final ProductRating productRating = ProductRating.newBuilder().setProductId(productId)
                            .setProductName(((Product) request.getAttribute("product")).getName())
                            .setValue(Integer.parseInt(rating)).build();
                    writer.put(userTable.getEntityId(login), "rating", productId, productRating);
                } finally {
                    IOUtils.closeQuietly(writer);
                }
                request.setAttribute("currentRating", rating);
            } else {
                // Read the user's existing rating for this dish (if any).
                final KijiTableReader userTableReader = userTable.openTableReader();
                try {
                    KijiDataRequestBuilder drBuilder = KijiDataRequest.builder();
                    drBuilder.newColumnsDef().add("rating", productId);
                    KijiDataRequest ratingRequest = drBuilder.build();
                    KijiRowData ratingResult = userTableReader.get(userTable.getEntityId(login), ratingRequest);
                    if (ratingResult.containsColumn("rating", productId)) {
                        int currentRating = ratingResult.<ProductRating>getMostRecentValue("rating", productId)
                                .getValue();
                        request.setAttribute("currentRating", currentRating);
                    }
                } catch (KijiDataRequestException e) {
                    throw new IOException(e);
                } finally {
                    IOUtils.closeQuietly(userTableReader);
                }
            }
        } finally {
            ResourceUtils.releaseOrLog(userTable);
        }
    }

    request.getRequestDispatcher("/WEB-INF/view/Product.jsp").forward(request, response);
}

From source file:controller.insertProduct.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  w w . j  a va  2  s  .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    insertProduct(request, response);
}

From source file:com.sharksharding.util.web.http.QueryViewServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* ? *//*from  w  ww.  j a v  a2  s  .com*/
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    /* Ioc */
    WebApplicationContext context = WebApplicationContextUtils
            .getWebApplicationContext(request.getSession().getServletContext());
    ShardRule shardRule = (ShardRule) context.getBean("shardRule");
    JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    if (null != shardRule) {
        byte[] viewData = null;
        byte[] responseData = null;
        /* 1???2??? */
        final String TYPE = request.getParameter("type");
        if (null == TYPE) {
            viewData = initView(PATH + "index.html");
            if (null != viewData) {
                write(response, viewData);
            }
        } else {
            switch (Integer.parseInt(TYPE)) {
            case 1:
                String page = request.getParameter("page");
                if (page.equals("index")) {
                    viewData = initView(PATH + "index.html");
                } else if (page.equals("query")) {
                    viewData = initView(PATH + "query.html");
                }
                if (null != viewData) {
                    write(response, viewData);
                }
                break;
            case 2:
                final String SQL = request.getParameter("sql");
                if (null != SQL && 0 < SQL.trim().length()) {
                    JSONObject jsonObj = new JSONObject();
                    ExecuteSql exeSql = new ExecuteSql(jdbcTemplate);
                    try {
                        Map<String, Object> datas = exeSql.queryData(SQL);
                        if (!datas.isEmpty()) {
                            StringBuffer strBuffer = new StringBuffer();
                            Set<String> keys = datas.keySet();
                            for (String key : keys) {
                                strBuffer.append(datas.get(key) + ",");
                            }
                            jsonObj.put("sqlResult", strBuffer.toString());
                            responseData = jsonObj.toJSONString().getBytes();
                        }
                    } catch (Exception e) {
                        Writer write = new StringWriter();
                        e.printStackTrace(new PrintWriter(write));
                        jsonObj.put("error", write.toString());
                        responseData = jsonObj.toString().getBytes("utf-8");
                    }
                } else {
                    responseData = GetIndexData.getData(shardRule).getBytes("utf-8");
                }
                if (null != responseData) {
                    write(response, responseData);
                }
            }
        }
    }
}

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

/**
 * Create and POST a request to the Watson service
 *
 * @param req//from w  w w .j  a va2  s.c  om
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String reqURI = req.getRequestURI();
        String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
        String url = baseURL + "/v1/" + endpoint;
        // concatenate query params
        String queryStr = req.getQueryString();
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");

        String metadata = req.getHeader("x-watson-metadata");
        if (metadata != null) {
            metadata += "client-ip:" + req.getRemoteAddr();
            newReq.addHeader("x-watson-metadata", metadata);
        }

        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        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();

        logger.info("post done");
    } 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:br.bireme.web.AuthenticationServlet.java

/**
 * Processes requests for both HTTP/*from   ww w.j  a  v a 2  s . c  o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding(CODEC);

    final String username = request.getParameter("email");
    final String password = request.getParameter("password");
    final String lang = request.getParameter("lang");
    final ServletContext context = getServletContext();
    final HttpSession session = request.getSession();
    final ResourceBundle messages = Tools.getMessages(lang);

    boolean isAccountsWorking = true;
    RequestDispatcher dispatcher;

    session.removeAttribute("collCenter");
    session.removeAttribute("user");

    if (isAccountsWorking) {
        if ((username == null) || (username.isEmpty()) || (password == null) || (password.isEmpty())) {
            response.sendRedirect(
                    "index.jsp?lang=" + lang + "&errMsg=" + messages.getString("login_is_required"));
            return;
        }

        try {
            final Authentication auth = new Authentication(context.getInitParameter("accounts_host"));
            final JSONObject user = auth.getUser(username, password);
            Set<String> centerIds = auth.getCenterIds(user);

            //if (auth.isAuthenticated(user) && (centerIds != null)) {
            if (auth.isAuthenticated(user)) {
                if (centerIds == null) {
                    centerIds = new HashSet<String>();
                }
                centerIds.add(auth.getColCenter(user)); // cc may not belong to a net (it not appear in centerIds)

                session.setAttribute("user", username); // Login user.
                session.setAttribute("centerIds", centerIds);
                dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
            } else {
                session.removeAttribute("user");
                session.removeAttribute("centerIds");
                dispatcher = context.getRequestDispatcher(
                        "/index.jsp?lang=" + lang + "&errMsg=" + messages.getString("authentication_failed"));
            }
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            dispatcher = context.getRequestDispatcher("/index.jsp?lang=" + lang + "&errMsg="
                    + messages.getString("exception_found") + "<br/><br/>" + ex.getMessage());
            dispatcher.forward(request, response);
        }
    } else {
        final Set<String> ccs = new HashSet<String>();
        ccs.add("PE1.1");
        ccs.add("BR1.1");
        dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
        session.setAttribute("user", username); // Login user.
        session.setAttribute("centerIds", ccs);
        dispatcher.forward(request, response);
    }
}

From source file:org.kuali.rice.kns.web.struts.action.KualiActionServlet.java

/**
 *  KULRICE-8176: KFS Notes/Attachments Tab Functionality for Note Text Error - Visible/Special characters, spaces, or tabs
 * //  ww w .j  ava  2  s.c o  m
 * @see org.apache.struts.action.ActionServlet#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void process(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (StringUtils.isNotBlank(parameterEncoding)) {
        request.setCharacterEncoding(parameterEncoding);
        response.setCharacterEncoding(parameterEncoding);
    }

    super.process(request, response);
}

From source file:controller.servlet.PostServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*ww  w  .  j a  va2 s .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String action = request.getParameter(Constants.ACTION);
    if (action != null) {
        switch (action) {
        case "new-topic":
            requestNewPost(request, response);
            break;
        }
    }
}

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

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    final Kiji kiji = (Kiji) getServletContext().getAttribute(KijiContextListener.KIJI_ATTRIBUTE);

    request.setCharacterEncoding("UTF-8");

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

    if (null == name || name.isEmpty() || null == login || login.isEmpty() || null == password
            || password.isEmpty()) {/*from  w w w  . j a  va  2s.  c  o  m*/
        request.setAttribute("name", name);
        request.setAttribute("login", login);
        request.setAttribute("password", password);
        request.setAttribute("error", "All fields are required.");
        request.getRequestDispatcher("/WEB-INF/view/CreateUser.jsp").forward(request, response);
        return;
    }

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

            KijiRowData row = reader.get(entityId, dataRequest);
            if (row.containsColumn("info", "login")) {
                request.setAttribute("name", name);
                request.setAttribute("login", login);
                request.setAttribute("password", password);
                request.setAttribute("error", "That login is already in use, please choose another.");
                request.getRequestDispatcher("/WEB-INF/view/CreateUser.jsp").forward(request, response);
                return;
            }
        } catch (KijiDataRequestException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(reader);
        }

        KijiTableWriter writer = userTable.openTableWriter();
        try {
            // Create the user.
            writer.put(entityId, "info", "name", name);
            writer.put(entityId, "info", "login", login);
            writer.put(entityId, "info", "password", BCrypt.hashpw(password, BCrypt.gensalt()));
        } finally {
            IOUtils.closeQuietly(writer);
        }
    } finally {
        ResourceUtils.releaseOrLog(userTable);
    }

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

From source file:org.alfresco.web.app.servlet.ajax.AjaxServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w w  w  .  ja v a2 s . c o  m*/
protected void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    // set default character encoding for the response
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/xml;charset=UTF-8");

    long startTime = 0;
    String uri = request.getRequestURI();
    if (logger.isDebugEnabled()) {
        final String queryString = request.getQueryString();
        logger.debug("Processing URL: " + uri
                + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }

    // dump the request headers
    if (headersLogger.isDebugEnabled()) {
        final Enumeration<?> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String name = (String) headers.nextElement();
            headersLogger.debug(name + ": " + request.getHeader(name));
        }
    }

    try {

        // Make sure the user is authenticated, if not throw an error to return the 
        // 500 Internal Server Error code back to the client
        AuthenticationStatus status = servletAuthenticate(request, response, false);
        if (status == AuthenticationStatus.Failure) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied: User not authenticated");
            return;
        }

        setNoCacheHeaders(response);

        uri = uri.substring(request.getContextPath().length() + "/".length());
        final String[] tokens = uri.split("/");
        if (tokens.length < 3) {
            throw new AlfrescoRuntimeException("Servlet URL did not contain all required args: " + uri);
        }

        // retrieve the command from the URL
        final String commandName = tokens[1];
        // retrieve the binding expression from the URL
        final String expression = tokens[2];

        // setup the faces context
        final FacesContext facesContext = FacesHelper.getFacesContext(request, response, getServletContext());

        // start a timer
        if (perfLogger.isDebugEnabled())
            startTime = System.currentTimeMillis();

        // instantiate the relevant command
        AjaxCommand command = null;
        if (Command.invoke.toString().equals(commandName)) {
            command = new InvokeCommand();
        } else if (Command.get.toString().equals(commandName)) {
            command = new GetCommand();
        } else {
            throw new AlfrescoRuntimeException("Unrecognised command received: " + commandName);
        }

        // execute the command
        command.execute(facesContext, expression, request, response);
    } catch (RuntimeException error) {
        handleError(response, error);
    } finally {
        // measure the time taken
        if (perfLogger.isDebugEnabled()) {
            perfLogger.debug("Time to execute command: " + (System.currentTimeMillis() - startTime) + "ms");
        }

        ContextHolder.setContext(null);
    }
}

From source file:ilearn.orb.controller.AnnotationController.java

@RequestMapping(value = "/annotation")
public ModelAndView textAnnotation(Locale locale, ModelMap modelMap, HttpServletRequest request,
        HttpSession session) {//from  ww  w  .  j a  v a  2s.c  om

    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    // System.err.println(request.getRemoteAddr());
    // System.err.println(request.getRemoteHost());
    // System.err.println(request.getRemotePort());
    txModule = new TextAnnotationModule();
    ModelAndView model = new ModelAndView();
    model.setViewName("annotation");
    try {
        Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
                .setDateFormat(DateFormat.LONG).create();
        User[] students = null;
        try {
            String json = UserServices.getProfiles(Integer.parseInt(session.getAttribute("id").toString()),
                    session.getAttribute("auth").toString());
            students = gson.fromJson(json, User[].class);
        } catch (NullPointerException e) {
        }
        if (students == null || students.length == 0) {
            students = HardcodedUsers.defaultStudents();
        }
        modelMap.put("students", students);
        String text = request.getParameter("inputText");
        String profileId = request.getParameter("selectedId");
        if (text != null) {
            text = new String(text.getBytes("8859_1"), "UTF-8");
        } else
            text = "";
        modelMap.put("profileId", profileId);
        modelMap.put("text", text);
        // UserProfile pr = retrieveProfile(session,
        // Integer.parseInt(profileId));
    } catch (NumberFormatException e) {
        //e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return model;
}