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:org.jbpm.designer.web.server.TaskFormsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String json = req.getParameter("json");
    String uuid = Utils.getUUID(req);
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String preprocessingData = req.getParameter("ppdata");
    String taskId = req.getParameter("taskid");

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }/*from www . ja v a 2  s. c o  m*/
    Repository repository = profile.getRepository();

    Asset<String> processAsset = null;

    try {
        processAsset = repository.loadAsset(uuid);

        DroolsFactoryImpl.init();
        BpsimFactoryImpl.init();

        Bpmn2JsonUnmarshaller unmarshaller = new Bpmn2JsonUnmarshaller();
        Definitions def = ((Definitions) unmarshaller.unmarshall(json, preprocessingData).getContents().get(0));

        Path myPath = vfsServices.get(uuid);

        TaskFormTemplateManager templateManager = new TaskFormTemplateManager(myPath, formModelerService,
                profile, processAsset, getServletContext().getRealPath(DESIGNER_PATH + TASKFORMS_PATH), def,
                taskId);
        templateManager.processTemplates();

        //storeInRepository(templateManager, processAsset.getAssetLocation(), repository);
        //displayResponse( templateManager, resp, profile );
        resp.setContentType("application/json");
        resp.getWriter().write(
                storeInRepository(templateManager, processAsset.getAssetLocation(), repository).toString());
    } catch (Exception e) {
        _logger.error(e.getMessage());
        //displayErrorResponse(resp, e.getMessage());
        resp.setContentType("text/plain");
        resp.getWriter().write("fail");
    }
}

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

/**
 * @throws IOException/*from  w  w w  .jav a 2 s .  c o  m*/
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final JSONObject jsonResponse = new JSONObject();
    request.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    final String actionParam = request.getParameter("action");

    IndexerServer server = null;
    try {
        server = IndexerServerManager.getIndexerServer(Core.FILESHARE);
    } catch (final IOException e1) {
        final PrintWriter out = response.getWriter();
        out.append(
                "Error while getting the Solr core, please make sure the core dedicated to PromoLinks has booted up. Error code : 69000");
        out.close();
        LOGGER.error(
                "Error while getting the Solr core in doGet, admin servlet, make sure the core dedicated to Promolink has booted up and is still called promolink or that the code has been changed to match the changes. Error 69000 ",
                e1);
        return;

    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        if (actionParam.toLowerCase().equals("download")) {
            final File folderConf = new File(downloadFolder);
            FileUtils.cleanDirectory(folderConf);
            server.downloadConfig(Paths.get(downloadFolder), Core.FILESHARE.toString());
        } else if (actionParam.toLowerCase().equals("upload")) {
            server.uploadConfig(Paths.get(env), Core.FILESHARE.toString());
        } else if (actionParam.toLowerCase().equals("reload")) {
            server.reloadCollection(Core.FILESHARE.toString());
        } else if (actionParam.toLowerCase().equals("upload_and_reload")) {
            server.uploadConfig(Paths.get(env), Core.FILESHARE.toString());
            Thread.sleep(3000);
            server.reloadCollection(Core.FILESHARE.toString());
        }

        jsonResponse.put(OutputConstants.CODE, CodesReturned.ALLOK.getValue());
    } catch (final IOException | SolrServerException | InterruptedException e) {
        LOGGER.error("Exception during action " + actionParam, e);
        jsonResponse.put(OutputConstants.CODE, CodesReturned.GENERALERROR.getValue());
    }
    final PrintWriter out = response.getWriter();
    out.print(jsonResponse);
}

From source file:org.jbpm.designer.web.server.UUIDBasedRepositoryServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String actionParam = req.getParameter("action");
    String preProcessingParam = req.getParameter("pp");
    if (preProcessingParam == null) {
        preProcessingParam = "ReadOnlyService";
    }//from  w  w w. j a  va  2  s .  c  om
    if (actionParam != null && actionParam.equals("toXML")) {
        if (profile == null) {
            profile = _profileService.findProfile(req, profileName);
        }
        String json = req.getParameter("data");
        String xml = "";
        try {
            xml = _repository.toXML(json, profile, preProcessingParam);
        } catch (Exception e) {
            _logger.error("Error transforming to XML: " + e.getMessage());
        }
        StringWriter output = new StringWriter();
        output.write(xml);
        resp.setContentType("application/xml");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(200);
        resp.getWriter().print(output.toString());
    } else if (actionParam != null && actionParam.equals("checkErrors")) {
        String retValue = "false";
        if (profile == null) {
            profile = _profileService.findProfile(req, profileName);
        }
        String json = req.getParameter("data");
        try {
            String xmlOut = profile.createMarshaller().parseModel(json, preProcessingParam);
            String jsonIn = profile.createUnmarshaller().parseModel(xmlOut, profile, preProcessingParam);
            if (jsonIn == null || jsonIn.length() < 1) {
                retValue = "true";
            }
        } catch (Throwable t) {
            retValue = "true";
            _logger.error("Exception parsing process: " + t.getMessage());
        }
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(200);
        resp.getWriter().print(retValue);
    } else {
        BufferedReader reader = req.getReader();
        StringWriter reqWriter = new StringWriter();
        char[] buffer = new char[4096];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            reqWriter.write(buffer, 0, read);
        }

        String data = reqWriter.toString();
        try {
            JSONObject jsonObject = new JSONObject(data);

            String json = (String) jsonObject.get("data");
            String svg = (String) jsonObject.get("svg");
            String uuid = (String) jsonObject.get("uuid");
            boolean autosave = jsonObject.getBoolean("savetype");

            if (profile == null) {
                profile = _profileService.findProfile(req, profileName);
            }

            _repository.save(req, uuid, json, svg, profile, autosave);

        } catch (JSONException e1) {
            throw new ServletException(e1);
        }
    }
}

From source file:com.investdata.common.filter.CharacterEncodingFilter.java

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
        request.setCharacterEncoding(this.encoding);//?  
        if (this.forceEncoding) {
            response.setCharacterEncoding(this.encoding);
        }//from w w  w.j  a v  a2  s .  c  o  m
    }
    filterChain.doFilter(request, response);//  

    /*
    if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
       request.setCharacterEncoding(this.encoding);
       if (this.forceEncoding && setCharacterEncodingAvailable) {
    response.setCharacterEncoding(this.encoding);
       }
    }
    filterChain.doFilter(request, response);
    */
}

From source file:com.example.cognitive.personality.DemoServlet.java

/**
 * Create and POST a request to the Personality Insights service
 * //w  ww  .j a  v a 2s  . co  m
 * @param req
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet pesponse
 * @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 {
    logger.info("doPost");

    req.setCharacterEncoding("UTF-8");
    // create the request
    String text = req.getParameter("text");

    try {
        URI profileURI = new URI(baseURL + "/v2/profile").normalize();

        Request profileRequest = Request.Post(profileURI).addHeader("Accept", "application/json")
                .bodyString(text, ContentType.TEXT_PLAIN);

        Executor executor = Executor.newInstance().auth(username, password);
        Response response = executor.execute(profileRequest);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Service error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:controller.productServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String command = request.getParameter("command");
    String proid = request.getParameter("product_id");

    String url = "";
    try {//from   www.j  av  a2  s  . c  o m
        switch (command) {

        case "delete":
            if (prod.countProductByBill(Integer.parseInt(proid)) > 0) {
                out.println("Ban k the xoa san pham nay");
                out.flush();
                return;
            } else {
                fedd.deleteFeedbackByProduct(Integer.parseInt(proid));
                prod.deleteProduct(Integer.parseInt(proid));
                url = "/java/admin/ql-product.jsp";
            }
            break;
        }
    } catch (Exception e) {
    }
    response.sendRedirect(url);
}

From source file:controller.categoryServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String command = request.getParameter("command");
    String catid = request.getParameter("category_id");

    String url = "";
    try {//from  w ww .j ava2 s.co  m
        switch (command) {

        case "delete":
            CategoryEntity cateen = new CategoryEntity();
            if (pro.countProductByCategory(Integer.parseInt(catid)) == 0) {
                cate.deleteCategory(Integer.parseInt(catid));
                url = "/java/admin/ql-category.jsp";
            } else {
                out.println("Khong the xoa danh muc nay");
                out.flush();
                return;
            }
            break;
        }
    } catch (Exception e) {
    }
    response.sendRedirect(url);
}

From source file:hd.controller.AddImageToProjectServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www  .  j  a v a  2 s  . c  om
 *
 * @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);
                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //Init Jpa
            CategoryJpaController categoryJpa = new CategoryJpaController(emf);
            StyleJpaController styleJpa = new StyleJpaController(emf);
            ProjectJpaController projectJpa = new ProjectJpaController(emf);
            IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf);
            // get Object Category by categoryId
            int cateId = Integer.parseInt((String) params.get("ddlCategory"));
            Category cate = categoryJpa.findCategory(cateId);
            // get Object Style by styleId
            int styleId = Integer.parseInt((String) params.get("ddlStyle"));
            Style style = styleJpa.findStyle(styleId);
            // get Object Project by projectId
            int projectId = Integer.parseInt((String) params.get("txtProjectId"));
            Project project = projectJpa.findProject(projectId);
            project.setStatus(Constant.STATUS_WAIT);
            projectJpa.edit(project);
            //Get param
            String title = (String) params.get("title");
            String description = (String) params.get("description");

            String url = "images/" + fileName;
            //Init IdeabookPhoto
            IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project);
            photoJpa.create(photo);
            url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId;

            //System
            HDSystem system = new HDSystem();
            system.setNotificationProject(request);
            response.sendRedirect(url);
        }
    } catch (Exception e) {
        log("Error at AddImageToProjectServlet: " + e.getMessage());
    } finally {
        out.close();
    }
}

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

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

    Employer employer = new Employer();
    Employer user;/*from w w  w.  j ava 2  s  .co  m*/
    List<Project> projects = new ArrayList();
    List<Skills> skills = new ArrayList();
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    //finding the user
    int id = Integer.parseInt(request.getParameter("id"));
    user = employerService.getEmployer(id);

    skills = skillsService.getSkillByEmployerId(user.getIdEmployer());
    projects = projectService.getProjectByEmployerId(user.getIdEmployer());

    session.setAttribute("User", user);
    session.setAttribute("projects", projects);
    session.setAttribute("skills", skills);
    //session.setAttribute("allEmployers", employerService.getAllEmployers());

    request.getRequestDispatcher("Personal_Employer.jsp").forward(request, response);

}

From source file:com.matrimony.controller.ProfileController.java

@RequestMapping(value = "shortUserProfile", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody//  ww w  . ja  va 2s  .c  om
public String getInfoUserByUserId(HttpServletRequest request, HttpServletResponse response, String id) {
    System.out.println("Tim id: " + id);
    try {
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    User user = UserDAO.findById(id);
    ShortUserProfile sortUserProfile = new ShortUserProfile();
    sortUserProfile.setAvatar(user.getAvatarPhoto());
    sortUserProfile.setName(user.getName());
    sortUserProfile.setUsername(user.getUsername());
    String json = Global.gson.toJson(sortUserProfile);
    return json;
}