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.ramadda.repository.server.RepositoryServlet.java

/**
 * Overriding doGet method in HttpServlet. Called by the server via the service method.
 *
 * @param request - an HttpServletRequest object that contains the request the client has made of the servlet
 * @param response - an HttpServletResponse object that contains the response the servlet sends to the client
 *
 * @throws IOException - if an input or output error is detected when the servlet handles the GET request
 * @throws ServletException - if the request for the GET could not be handled
 *//*from  w ww . ja v a  2s.  c o  m*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // there can be only one
    if (repository == null) {
        try {
            createRepository(request);
        } catch (Exception e) {
            logException(e, request);
            response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error:" + e.getMessage());

            return;
        }
    }
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    RequestHandler handler = new RequestHandler(request);
    Result repositoryResult = null;

    boolean isHeadRequest = request.getMethod().equals("HEAD");
    try {
        try {
            // create a org.ramadda.repository.Request object from the relevant info from the HttpServletRequest object
            Request repositoryRequest = new Request(repository, request.getRequestURI(), handler.formArgs,
                    request, response, this);

            repositoryRequest.setIp(request.getRemoteAddr());
            repositoryRequest.setOutputStream(response.getOutputStream());
            repositoryRequest.setFileUploads(handler.fileUploads);
            repositoryRequest.setHttpHeaderArgs(handler.httpArgs);

            // create a org.ramadda.repository.Result object and transpose the relevant info into a HttpServletResponse object
            repositoryResult = repository.handleRequest(repositoryRequest);
            if (standAloneServer != null) {
                //We are running stand-alone so nothing is doing logging

            }
        } catch (Throwable e) {
            e = LogUtil.getInnerException(e);
            logException(e, request);
            response.sendError(response.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
        if (repositoryResult == null) {
            response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Unknown request:" + request.getRequestURI());

            return;
        }

        if (repositoryResult.getNeedToWrite()) {
            List<String> args = repositoryResult.getHttpHeaderArgs();
            if (args != null) {
                for (int i = 0; i < args.size(); i += 2) {
                    String name = args.get(i);
                    String value = args.get(i + 1);
                    response.setHeader(name, value);
                }
            }

            Date lastModified = repositoryResult.getLastModified();
            if (lastModified != null) {
                response.addDateHeader("Last-Modified", lastModified.getTime());
            }

            if (repositoryResult.getCacheOk()) {
                //                    response.setHeader("Cache-Control",
                //                                       "public,max-age=259200");
                response.setHeader("Expires", "Tue, 08 Jan 2020 07:41:19 GMT");
                if (lastModified == null) {
                    //                        response.setHeader("Last-Modified",
                    //                                           "Tue, 20 Jan 2010 01:45:54 GMT");
                }
            } else {
                response.setHeader("Cache-Control", "no-cache");
            }

            if (isHeadRequest) {
                response.setStatus(repositoryResult.getResponseCode());

                return;
            }

            if (repositoryResult.getRedirectUrl() != null) {
                try {
                    response.sendRedirect(repositoryResult.getRedirectUrl());
                } catch (Exception e) {
                    logException(e, request);
                }
            } else if (repositoryResult.getInputStream() != null) {
                try {

                    response.setStatus(repositoryResult.getResponseCode());
                    response.setContentType(repositoryResult.getMimeType());
                    OutputStream output = response.getOutputStream();
                    try {
                        //                            System.err.println("SLEEP");
                        //                            Misc.sleepSeconds(30);
                        IOUtils.copy(repositoryResult.getInputStream(), output);
                        //IOUtil.writeTo(repositoryResult.getInputStream(),
                        //                               output);
                    } finally {
                        IOUtil.close(output);
                    }
                } catch (IOException e) {
                    //We'll ignore any ioexception
                } catch (Exception e) {
                    logException(e, request);
                } finally {
                    IOUtil.close(repositoryResult.getInputStream());
                }
            } else {
                try {
                    response.setStatus(repositoryResult.getResponseCode());
                    response.setContentType(repositoryResult.getMimeType());
                    OutputStream output = response.getOutputStream();
                    try {
                        output.write(repositoryResult.getContent());
                    } catch (java.net.SocketException se) {
                        //ignore
                    } catch (IOException se) {
                        //ignore
                    } finally {
                        IOUtil.close(output);
                    }
                } catch (Exception e) {
                    logException(e, request);
                }
            }
        }
    } finally {
        if ((repositoryResult != null) && (repositoryResult.getInputStream() != null)) {
            IOUtil.close(repositoryResult.getInputStream());
        }
    }

}

From source file:com.hp.action.StaffsAction.java

public String updateStaff() throws UnsupportedEncodingException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize// www . j  a  va2s . c  om
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    request.setCharacterEncoding("UTF8");
    usersList = userDAO.getListUser(2);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");

    Date out = null;
    System.out.println("OK1" + staff.getId());

    try {
        out = sdf2.parse(startDate);

    } catch (Exception e) {
        e.printStackTrace();
    }

    staff.setDate(out);

    //New
    if (staff.getStt() <= 0) {

        boolean status = staffDAO.saveOrUpdate(staff);
        //staffsList = staffDAO.getListStaff();

        System.out.println("___ " + status);
        if (status)
            return SUCCESS;
        else
            return INPUT;
    }

    //UPdate
    System.out.println("OK" + staff.getId());

    boolean status = staffDAO.update(staff);
    if (status)
        return SUCCESS;
    else
        return INPUT;
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
  * ?  ? ? upload.up  ?  ?  ?? //from   w ww  . j  a va  2  s  .  c om
  * ??? ? ??(?) ?? .
  * @param req HttpServletRequest ?
  * @param res HttpServletResponse ?
  * @throws Exception
  */
@RequestMapping(value = "/cntrwkFileUpManage_upload.up", method = RequestMethod.POST)
public void upload(HttpServletRequest req, HttpServletResponse res,
        @RequestParam(value = "changeInfoId", required = true) String changeInfoId,
        @RequestParam(value = "fileType", required = true) String fileType) throws Exception {
    req.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        File targetFolder = null;

        // "DEXTUploadNX_EmptyFolderPath"? DEXTUploadNX? ?  ??()  ?  .
        String[] emptyFolderNames = dextj.getParameterValues("DEXTUploadNX_EmptyFolderPath");
        if (emptyFolderNames == null)
            emptyFolderNames = new String[0];
        for (String nextName : emptyFolderNames) {
            targetFolder = new File(repository, nextName);
            if (!targetFolder.exists())
                targetFolder.mkdir();
        }

        // "DEXTUploadNX_FolderPath"? DEXTUploadNX? ? ??()  ?  .
        String[] folderNames = dextj.getParameterValues("DEXTUploadNX_FolderPath");
        if (folderNames == null)
            folderNames = new String[0];

        // "DEXTUploadNX"? DEXTUploadNX? ?  ? ??  .
        FileItem[] fileItems = dextj.getFileItemValues("DEXTUploadNX");
        if (fileItems == null)
            fileItems = new FileItem[0];

        // "DEXTUploadNX_FolderPath", "DEXTUploadNX" ? ? ?? ??   ?? ? ?.

        for (int i = 0; i < folderNames.length; i++) {
            targetFolder = new File(repository, folderNames[i]);
            if (!targetFolder.exists())
                targetFolder.mkdir();

            if (fileItems[i].IsUploaded()) {
                fileItems[i].SaveAs(targetFolder.getAbsolutePath(),
                        changeInfoId + "_" + fileItems[i].getFileName(), true);

                TnAtchmnflVO tnAtchmnflVO = getTnAtchmnflVOFromFileItem(fileItems[i], changeInfoId, fileType);

                tnAtchmnflService.deleteTnAtchmnfl(tnAtchmnflVO);
                tnAtchmnflService.insertTnAtchmnfl(tnAtchmnflVO);

            }
        }

    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:com.hp.action.StaffsAction.java

public String editStaff() throws UnsupportedEncodingException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize/*  w w w  .  j av  a  2 s .  c  o m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //request.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF8");
    usersList = userDAO.getListUser(2);

    String para = request.getParameter("id_st");

    int id_st = ValidateHandle.getInteger(para);
    if (id_st > -1) {
        staff = staffDAO.loadStaff(id_st);
        return SUCCESS;
    } else
        return INPUT;

    //        String stt = request.getParameter("id_staff");
    //        int st;
    //        if(stt ==null){
    //            return INPUT;
    //        }
    //        st = Integer.parseInt(stt);
    //        
    //        staffsList = staffDAO.getListStaff();
    //        staff = staffDAO.loadStaff(st);

}

From source file:org.rapidcontext.core.web.Request.java

/**
 * Creates a new request wrapper./* w w  w. ja va 2  s .  co  m*/
 *
 * @param request        the servlet request
 * @param response       the servlet response
 */
public Request(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ignore) {
            // Do nothing
        }
    }
    logRequest();
}

From source file:isl.FIMS.servlet.export.ExportXML.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    boolean isGuest = this.getRights(username).equals("guest");
    if (!isGuest) {
        try {// w w w.j av a  2s  .  co m
            String filePath = this.export_import_Folder;
            java.util.Date date = new java.util.Date();
            Timestamp t = new Timestamp(date.getTime());
            String currentDir = filePath + t.toString().replaceAll(":", "").replaceAll("\\s", "");
            File saveDir = new File(currentDir);
            saveDir.mkdir();
            Config conf = new Config("EksagwghXML");
            String type = request.getParameter("type");
            String id = request.getParameter("id");
            request.setCharacterEncoding("UTF-8");
            DBCollection col = new DBCollection(this.DBURI, this.systemDbCollection + type, this.DBuser,
                    this.DBpassword);
            String collectionPath = UtilsQueries.getPathforFile(col, id + ".xml", id.split(type)[1]);
            col = new DBCollection(this.DBURI, collectionPath, this.DBuser, this.DBpassword);
            DBFile dbf = col.getFile(id + ".xml");

            String isWritable = "true";
            if (GetEntityCategory.getEntityCategory(type).equals("primary")) {
                isWritable = dbf
                        .queryString("//admin/write='" + username + "'" + "or //admin/status='published'")[0];
            }
            if (isWritable.equals("true")) {
                String[] res = dbf.queryString("//admin/refs/ref");
                ServletOutputStream outStream = response.getOutputStream();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=\"" + id + ".zip\"");
                writeFile(type, id, currentDir, username);
                for (int i = 0; i < res.length; i++) {
                    Element e = Utils.getElement(res[i]);
                    String sps_type = e.getAttribute("sps_type");
                    String sps_id = e.getAttribute("sps_id");
                    sps_id = sps_type + sps_id;
                    writeFile(sps_type, sps_id, currentDir, username);
                }
                //check if any disk files to export
                ArrayList<String> externalFiles = new <String>ArrayList();
                String q = "//*[";
                for (String attrSet : this.uploadAttributes) {
                    String[] temp = attrSet.split("#");
                    String func = temp[0];
                    String attr = temp[1];
                    if (func.contains("text")) {
                        q += "@" + attr + "]/text()";
                    } else {
                        q = "data(//*[@" + attr + "]/@" + attr + ")";
                    }
                    String[] result = dbf.queryString(q);
                    for (String extFile : result) {
                        externalFiles.add(extFile + "#" + attr);
                    }
                }
                for (String extFile : externalFiles) {
                    DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml",
                            this.DBuser, this.DBpassword);
                    String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length());
                    extFile = extFile.substring(0, extFile.lastIndexOf("#"));
                    String mime = Utils.findMime(uploadsDBFile, extFile, attr);
                    String path = "";
                    if (mime.equals("Photos")) {
                        path = this.systemUploads + File.separator + type + File.separator + mime
                                + File.separator + "original" + File.separator + extFile;
                    } else {
                        path = this.systemUploads + File.separator + type + File.separator + mime
                                + File.separator + extFile;
                    }
                    File f = new File(path);
                    if (f.exists()) {
                        if (extFile.startsWith("../")) {
                            extFile = extFile.replace("../", "");

                            File file = new File(
                                    currentDir + System.getProperty("file.separator") + id + ".xml");
                            if (!file.exists()) {
                                file = new File(
                                        currentDir + System.getProperty("file.separator") + id + ".x3ml");
                            }
                            if (file.exists()) {
                                String content = FileUtils.readFileToString(file);
                                content = content.replaceAll("../" + extFile, extFile);
                                FileUtils.writeStringToFile(file, content);

                            }

                        }
                        FileUtils.copyFile(f,
                                new File(currentDir + System.getProperty("file.separator") + extFile));
                    }
                }
                File f = new File(currentDir + System.getProperty("file.separator") + "zip");
                f.mkdir();
                String zip = f.getAbsolutePath() + System.getProperty("file.separator") + id + ".zip";
                Utils.createZip(zip, currentDir);
                Utils.downloadZip(outStream, new File(zip));
            } else {
                String displayMsg = "";
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                displayMsg = Messages.ACCESS_DENIED;
                StringBuilder xml = new StringBuilder(
                        this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
                xml.append("<Display>").append(displayMsg).append("</Display>\n");
                xml.append(this.xmlEnd());

                String xsl = conf.DISPLAY_XSL;
                try {
                    XMLTransform xmlTrans = new XMLTransform(xml.toString());
                    xmlTrans.transform(out, xsl);
                } catch (DMSException e) {
                }
                out.close();

            }
            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java

private void canvasRestApiCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8");
    M_log.debug("canvasRestApiCall(): called");
    PrintWriter out = response.getWriter();
    response.setContentType("application/json");
    if (canvasToken == null || canvasURL == null) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        out = response.getWriter();/*from w  w w  . j a v a  2  s.  c  o  m*/
        out.print(appExtPropertiesFile.getProperty("property.file.load.error"));
        out.flush();
        M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool");
        return;
    }
    if (isAllowedApiRequest(request)) {
        callType = appExtPropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_CALL_TYPE);
        if (callType.equals("canvas")) {
            apiConnectionLogic(request, response);
        } else {
            esbRestApiCall(request, response);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        out = response.getWriter();
        out.print(appExtPropertiesFile.getProperty("api.not.allowed.error"));
        out.flush();
    }
}

From source file:com.hp.action.CustomerAction.java

public String editCustomer() throws UnsupportedEncodingException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize/*w ww.jav a  2s .  c om*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //request.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF8");
    staffsList = staffDAO.getListUser(null);

    String stt = request.getParameter("id_cus");
    int id_cus = ValidateHandle.getInteger(stt);
    if (id_cus > -1) {
        customersList = customerDAO.getListCustomer();
        customer = customerDAO.loadCustomer(id_cus);
        return SUCCESS;
    } else
        return INPUT;

}

From source file:com.devpia.service.DEXTUploadJController.java

/** ?  */
@RequestMapping(value = "/cntrwkFileUpManage_delete.down", method = RequestMethod.POST)
public void cntrwkFileUpManage_delete(HttpServletRequest req, HttpServletResponse res,
        @RequestParam(value = "fileType") String fileType,
        @RequestParam(value = "changeInfoId") String changeInfoId,
        @RequestParam(value = "fileName") String fileName,
        @RequestParam(value = "atchmnflId") String atchmnflId) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/html; charset=UTF-8");

    TnAtchmnflVO vo = new TnAtchmnflVO();
    vo.setChangeInfoId(new BigDecimal(changeInfoId));
    vo.setFileFomCodeTy(fileType);/*from  w  ww.  jav  a 2  s . c om*/
    vo.setFileNm(fileName);
    vo.setAtchmnflId(new BigDecimal(atchmnflId));
    tnAtchmnflService.deleteTnAtchmnfl(vo);

}

From source file:cdr.forms.FormController.java

@RequestMapping(value = "/{formId}.form", method = RequestMethod.POST)
public String processForm(Model model, @PathVariable(value = "formId") String formId,
        @Valid @ModelAttribute("deposit") Deposit deposit, BindingResult errors, Principal user,
        SessionStatus sessionStatus,/*from  w  ww. j av  a2 s  .com*/
        @RequestParam(value = "deposit", required = false) String submitDepositAction,
        HttpServletRequest request, HttpServletResponse response) throws PermissionDeniedException {

    request.setAttribute("hasSupplementalObjectsStep", formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID));

    // Check that the form submitted by the user matches the one in the session

    if (!deposit.getFormId().equals(formId))
        throw new Error("Form ID in session doesn't match form ID in path");

    //

    this.getAuthorizationHandler().checkPermission(formId, deposit.getForm(), request);

    //

    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error("Failed to set character encoding", e);
    }

    //

    if (user != null)
        deposit.getForm().setCurrentUser(user.getName());

    // Remove entries set to null, append an entry for elements with append set

    for (DepositElement element : deposit.getElements()) {

        Iterator<DepositEntry> iterator = element.getEntries().iterator();

        while (iterator.hasNext()) {
            if (iterator.next() == null)
                iterator.remove();
        }

        if (element.getAppend() != null) {
            element.appendEntry();
            element.setAppend(null);
        }

    }

    // Check the deposit's files for virus signatures

    IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>();

    for (DepositFile depositFile : deposit.getAllFiles())
        scanDepositFile(depositFile, signatures);

    // If the "submit deposit" button was pressed, run the validator.

    if (submitDepositAction != null) {

        Validator validator = new DepositValidator();
        validator.validate(deposit, errors);

    }

    // If the deposit has validation errors and no virus signatures were detected, display errors

    if (errors.hasErrors() && signatures.size() == 0) {
        LOG.debug(errors.getErrorCount() + " errors");
        return "form";
    }

    // If the "submit deposit" button was not pressed, render the form again

    if (submitDepositAction == null) {
        return "form";
    }

    // Otherwise, display one of the result pages: if we detected a virus signature, display
    // the virus warning; otherwise, try to submit the deposit and display results. In each
    // case, we want to do the same cleanup.

    String view;

    if (signatures.size() > 0) {

        model.addAttribute("signatures", signatures);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        view = "virus";

    } else {

        // Redirect for supplemental objects special case

        if (formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID)) {
            return "redirect:/supplemental";
        }

        // We're doing a regular deposit, so call the deposit handler

        DepositResult result = this.getDepositHandler().deposit(deposit);

        if (result.getStatus() == Status.FAILED) {

            LOG.error("deposit failed");

            if (getNotificationHandler() != null)
                getNotificationHandler().notifyError(deposit, result);

            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            view = "failed";

        } else {

            if (getNotificationHandler() != null)
                getNotificationHandler().notifyDeposit(deposit, result);

            view = "success";

        }

    }

    // Clean up

    deposit.deleteAllFiles();

    sessionStatus.setComplete();
    request.setAttribute("formId", formId);
    request.setAttribute("administratorEmail", getAdministratorEmail());

    return view;

}