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.ikon.servlet.admin.CssServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from   ww  w .ja v  a 2  s  .  c  om*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Css css = new Css();
            css.setActive(false);

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("css_id")) {
                        if (!item.getString("UTF-8").isEmpty()) {
                            css.setId(new Long(item.getString("UTF-8")).longValue());
                        }
                    } else if (item.getFieldName().equals("css_name")) {
                        css.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_context")) {
                        css.setContext(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_content")) {
                        css.setContent(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_active")) {
                        css.setActive(true);
                    }
                }
            }

            if (action.equals("edit")) {
                CssDAO.getInstance().update(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_UPDATE", String.valueOf(css.getId()), null, css.getName());
            } else if (action.equals("delete")) {
                String name = WebUtils.getString(request, "css_name");
                CssDAO.getInstance().delete(css.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_DELETE", String.valueOf(css.getId()), null, name);
            } else if (action.equals("create")) {
                long id = CssDAO.getInstance().create(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_CREATE", String.valueOf(id), null, css.getName());
            }
        }

        list(userId, request, response);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.netcracker.tss.web.servlet.customer.CustomerOrderTaxiEditDeleteServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww w  . jav a  2s .  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 {
    request.setCharacterEncoding("UTF-8");
    try {
        if (request.getParameter("addTo") != null) {
            addAddressTo(request);
            redirectToEdit(request, response, null);
        } else if (request.getParameter("addFrom") != null) {
            addAddressFrom(request);
            redirectToEdit(request, response, null);
        } else if (request.getParameter("deleteTo") != null || request.getParameter("deleteFrom") != null) {
            deleteAddress(request);
            redirectToEdit(request, response, null);
        } else {
            TaxiOrderBeanLocal taxiOrderBeanLocal = getTaxiOrderBean(request);
            Address addFrom = toAddress(request.getParameter("fromAddr"), request);
            Address addTo = toAddress(request.getParameter("toAddr"), request);
            PriceBeanLocal priceBean = getPriceBean(request);
            float distance = 0;
            double price = 0;
            try {
                MapBeanLocal mapBean = getMapBean(request);
                distance = mapBean.calculateDistance(request.getParameter("fromAddr"),
                        request.getParameter("toAddr"));
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
            price = priceBean.calculatePrice(distance, DateParser.parseDate(request),
                    (TaxiOrder) request.getSession().getAttribute("taxiOrder"), UserUtils.findCurrentUser());
            request.getSession().removeAttribute("taxiOrder");
            Date orderTime = DateParser.parseDate(request);
            orderTime.setYear(new Date().getYear());
            taxiOrderBeanLocal.editTaxiOrderCustomer(taxiOrderId, addFrom, addTo, orderTime, distance, price);
            request.setAttribute("taxiOrderId", taxiOrderId);
            request.setAttribute("pageContent", "content/confirmation-updated.jsp");
            request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request,
                    response);
        }
    } catch (Exception e) {
        Logger.getLogger(CustomerSoberServiceServlet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
        String error = "Sorry, we can not make this order! Please, check all input parameters ad try again.";
        redirectToEdit(request, response, error);
    }
}

From source file:com.openkm.servlet.admin.CronTabServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    updateSessionManager(request);/* w  w w.jav  a  2s  .c om*/

    try {
        Map<String, String> types = new LinkedHashMap<String, String>();
        types.put(MimeTypeConfig.MIME_BSH, "BSH");
        types.put(MimeTypeConfig.MIME_JAR, "JAR");

        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            CronTab ct = new CronTab();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("execute")) {
            execute(request, response);
            list(request, response);
        } else if (action.equals("download")) {
            download(request, response);
        } else {
            list(request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.mockey.model.RequestFromClient.java

/**
 * Initialization will extract Headers, Body, Parameters, and Cookies from
 * the raw HTTP request. Note: This class will <i>_ignore_</i> some header
 * information. See <code>HEADERS_TO_IGNORE</code>
 * /* w w w .  j  a v a 2s.  c  o m*/
 * @param rawRequest
 */
public RequestFromClient(HttpServletRequest rawRequest) {
    try {
        rawRequest.setCharacterEncoding(HTTP.ISO_8859_1); // "UTF-8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    this.method = rawRequest.getMethod();

    parseRequestHeaders(rawRequest);
    parseRequestBody(rawRequest);
    parseParameters(rawRequest);
    parseCookies(rawRequest);
}

From source file:com.sbu.controller.Feed_Form_Employer_Edit_Contorller.java

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

    List<Project> projects;
    List<Skills> skills;/*from  ww  w  .j a va 2 s.c  om*/
    Vector<Project> filtered_projects = new Vector<>();
    Vector<Skills> filtered_skills = new Vector<>();
    List<Employer> users;
    Employer user = null;
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();

    int id = Integer.parseInt(request.getParameter("id"));

    //user = employerService.getEmployer(id);

    skills = skillsService.getAllSkills();
    projects = projectService.getAllProjects();
    users = employerService.getAllEmployers();
    for (int i = 0; i < users.size(); i++) {
        if (users.get(i).getIdEmployer() == id) {
            user = users.get(i);
            break;
        }
    }

    for (int i = 0; i < skills.size(); i++) {
        if (skills.get(i).getEmployeridEmployer().equals(user))
            filtered_skills.add(skills.get(i));
    }

    for (int i = 0; i < projects.size(); i++) {
        if (projects.get(i).getEmployeridEmployer().equals(user))
            filtered_projects.add(projects.get(i));
    }

    request.setAttribute("User", user);
    request.setAttribute("projects", filtered_projects);
    request.setAttribute("skills", filtered_skills);

    getServletContext().getRequestDispatcher("/accountsetting_Employer_Edit.jsp").forward(request, response);

}

From source file:org.debux.webmotion.server.WebMotionServer.java

/**
 * Apply config in mapping on request and response
 *///w w w .  j a  va  2s . com
protected void applyConfig(Mapping mapping, Call call) throws WebMotionException {
    HttpContext context = call.getContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    Config config = mapping.getConfig();
    String encoding = config.getEncoding();
    try {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);

    } catch (UnsupportedEncodingException encodingException) {
        throw new WebMotionException("Invalid encoding for request", encodingException);
    }
}

From source file:org.geowe.server.upload.FileUploadZipServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ServletFileUpload upload = new ServletFileUpload();
    response.setContentType("text/plain; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_FILE_SIZE);//from   w w w . j a v a2  s.  com

    try {
        final FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            final FileItemStream item = iter.next();

            ZipFile zipFile = createZipFile(item);

            final String content = readZipFile(zipFile);

            if (EMPTY.equals(content)) {
                response.setStatus(HttpStatus.SC_NO_CONTENT);
                response.getWriter().printf(HttpStatus.SC_NO_CONTENT + ":" + content);
            } else if (BAD_FORMAT.equals(content)) {
                response.setStatus(HttpStatus.SC_NOT_ACCEPTABLE);
                response.getWriter().printf(HttpStatus.SC_NOT_ACCEPTABLE + ":" + content);
            } else {
                response.setStatus(HttpStatus.SC_OK);
                response.getWriter().printf(content);
            }

        }
    } catch (SizeLimitExceededException e) {
        response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG);
        response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage());
        LOG.error(e.getMessage());
    } catch (Exception e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong.");
        LOG.error(e.getMessage());
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Sets the character encoding for reading parameters and content from a request in a JSP page.
 *
 * @param request The servlet request object
 *///from  ww w . j  a va 2s.  c  o m
public static void setUTF8(HttpServletRequest request) {
    ArgumentNotValid.checkNotNull(request, "request");
    // Why is this in an if block? Suppose we forward from a page where
    // we read file input from the request. Trying to set the character
    // encoding again here will throw an exception!
    // This is a bit of a hack - we know that _if_ we have set it,
    // we have set it to UTF-8, so this way we won't set it twice...
    if (request.getCharacterEncoding() == null || !request.getCharacterEncoding().equals("UTF-8")) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ArgumentNotValid("Should never happen! UTF-8 not supported", e);
        }
    }
}

From source file:org.alfresco.repo.web.scripts.TenantWebScriptServlet.java

protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled())
        logger.debug("Processing tenant request (" + req.getMethod() + ") " + req.getRequestURL()
                + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));

    if (req.getCharacterEncoding() == null) {
        req.setCharacterEncoding("UTF-8");
    }/*from   www. j av a  2  s  .co m*/

    setLanguageFromRequestHeader(req);

    try {
        WebScriptServletRuntime runtime = getRuntime(req, res);
        runtime.executeScript();
    } catch (IllegalStateException e) {
        if (e.getMessage().contains("getOutputStream() has already been called for this response")) {
            if (logger.isDebugEnabled()) {
                logger.warn("Client has cut off communication", e);
            } else {
                logger.warn("Client has cut off communication");
            }
        } else {
            throw e;
        }
    } finally {
        // clear threadlocal
        I18NUtil.setLocale(null);
        // clear authentication and tenant context
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}

From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // set charset
    response.setCharacterEncoding(Fields.CHARSET);
    request.setCharacterEncoding(Fields.CHARSET);

    // login stuff
    UserManager user = null;//from w  w  w. j  a  v a2  s. c  o  m
    try {
        user = Tools.doLogin(request, response, false);
    } catch (CombineArchiveWebCriticalException e) {
        LOGGER.error(e, "Exception while getting User");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } catch (CombineArchiveWebException e) {
        LOGGER.warn(e, "Exception while getting User");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return;
    }

    // splitting request URL
    String[] requestUrl = request.getRequestURI().substring(request.getContextPath().length()).split("/");

    // check entry points
    if (requestUrl.length >= 5 && requestUrl[2].equals("archive")) {
        // request to download an archive from *any* workspace
        // without necessarily obtained this workspace before

        UserManager targetUser = null;
        if (requestUrl[3] != null && !requestUrl[3].isEmpty())
            targetUser = new UserManager(requestUrl[3]);
        else
            return;

        if (requestUrl[4] != null && !requestUrl[4].isEmpty() && targetUser != null)
            downloadArchive(request, response, targetUser, URLDecoder.decode(requestUrl[4], Fields.CHARSET));
    } else if (requestUrl.length >= 4 && requestUrl[2].equals("archive")) {
        // request to download an archive from the workspace
        if (requestUrl[3] != null && !requestUrl[3].isEmpty())
            downloadArchive(request, response, user, URLDecoder.decode(requestUrl[3], Fields.CHARSET));
    } else if (requestUrl.length >= 5 && requestUrl[2].equals("file")) {

        String archive = null;
        String file = null;

        if (requestUrl[3] != null && !requestUrl[3].isEmpty())
            archive = URLDecoder.decode(requestUrl[3], Fields.CHARSET);
        else
            return;

        StringBuilder filePath = new StringBuilder();
        for (int i = 4; i < requestUrl.length; i++) {

            if (requestUrl[i] != null && !requestUrl[i].isEmpty()) {
                filePath.append("/");
                filePath.append(requestUrl[i]);
            }
        }
        // decode the name
        file = URLDecoder.decode(filePath.toString(), Fields.CHARSET);

        if (archive != null && !archive.isEmpty() && file != null && !file.isEmpty())
            downloadFile(request, response, user, archive, file);

    }

}