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.commonfarm.web.ECSideFilter.java

public void doAjaxFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");

    String easyListName = getEasyList(request);
    String easyDataAccessName = getEasyDataAccess(request);

    String findAjaxZoneAtClient = request.getParameter(TableConstants.AJAX_FINDZONE_CLIENT);
    if (findAjaxZoneAtClient != null
            && ("false".equalsIgnoreCase(findAjaxZoneAtClient) || "0".equals(findAjaxZoneAtClient))) {
        ECSideAjaxResponseWrapper bufferResponseWrapper = new ECSideAjaxResponseWrapper(response);
        try {/*from w  w  w  .j ava 2s. c o  m*/

            String ectableId = request.getParameter(TableConstants.EXTREME_COMPONENTS_INSTANCE);
            if (easyListName != null) {
                easyDataAccessHandler.easyList(request, bufferResponseWrapper,
                        getEasyListModelBean(request, easyListName));
            } else if (easyDataAccessName != null) {
                String sqlName = getSqlName(request);
                easyDataAccessHandler.dataAccess(getDataAccessModelBean(request, easyDataAccessName), sqlName,
                        request, response);
            }
            chain.doFilter(request, bufferResponseWrapper);
            String zone = bufferResponseWrapper.findSubstring(ECSideUtils.getAjaxBegin(ectableId),
                    ECSideUtils.getAjaxEnd(ectableId));
            HttpServletResponse originalResponse = bufferResponseWrapper.getOriginalResponse();
            originalResponse.flushBuffer();
            originalResponse.getOutputStream().write(zone.getBytes("UTF-8"));
            originalResponse.flushBuffer();
            originalResponse.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        if (easyListName != null) {
            easyDataAccessHandler.easyList(request, response, getEasyListModelBean(request, easyListName));
        } else if (easyDataAccessName != null) {
            String sqlName = getSqlName(request);
            easyDataAccessHandler.dataAccess(getDataAccessModelBean(request, easyDataAccessName), sqlName,
                    request, response);
        }
        chain.doFilter(request, response);
    }
}

From source file:edu.lafayette.metadb.web.metadata.UpdateAdminDescMetadata.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//w w w  . j a  v a 2s . co  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");
    JSONObject output = new JSONObject();

    String type = request.getParameter("type");
    String message = type + " metadata cannot be updated\n";

    try {
        HttpSession session = request.getSession(false);
        if (session == null)
            return;
        String projname = (String) session.getAttribute(Global.SESSION_PROJECT);
        String userName = (String) session.getAttribute("username");
        int itemNumber = Integer.parseInt(request.getParameter("current"));

        String locker = ItemsDAO.getLocker(projname, itemNumber);
        if (!(userName.equals(locker) || locker.trim().equals("") || locker == null))
            return;

        output.put("projname", projname);
        String[] ids_array = request.getParameter("edited-ids").split(" ");
        Set<String> ids = new HashSet<String>();
        for (String id : ids_array) {
            ids.add(id);
        }

        JSONArray failed_items = new JSONArray();
        message = "Metadata exist and will be updated\n";
        for (String id_string : ids) {
            int id = Integer.parseInt(id_string);
            JSONObject whitelisted = whitelist(id_string, projname, type, itemNumber, request);

            if (whitelisted.getBoolean("success")) {
                MetaDbHelper.note("Whitelist succeeded, proj " + projname + ", item " + itemNumber + ", id "
                        + id + ", data " + whitelisted.getString("data"));
                AdminDescDataDAO.updateAdminDescData(projname, itemNumber, id,
                        whitelisted.getString("data").trim());

            } else {
                MetaDbHelper.note("Didn't pass whitelist");
                failed_items.put(whitelisted);
            }

        }
        output.put("failure", failed_items);
        output.put("message", message);
        output.put("type", type);
    } catch (NumberFormatException e) {
        //No problem, when splitting string last element is "", thus cannot be
        //converted to numbers
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.print(output);
    out.flush();
}

From source file:controladores.usuarios.ControladorUsuarios.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w . j  a va  2 s .c o  m*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    FUsuario faUsu = new FUsuario();
    UsuarioDto usuario;
    Encriptar encript;
    String salida;
    if (request.getParameter("botonRegistro") != null) {
        RolDto suRol = new RolDto();
        suRol.setIdRol(Integer.parseInt(request.getParameter("ruRol")));

        UsuarioDto nuevoUsuario = new UsuarioDto();
        nuevoUsuario.setIdUsuario(Long.parseLong(request.getParameter("ruDocumento")));
        nuevoUsuario.setNombres(request.getParameter("ruNombres"));
        nuevoUsuario.setApellidos(request.getParameter("ruApellidos"));
        nuevoUsuario.setClave(request.getParameter("ruClave"));
        nuevoUsuario.setCorreo(request.getParameter("ruCorreo"));
        nuevoUsuario.setFechaNacimiento(request.getParameter("ruFechaNacimiento"));
        nuevoUsuario.setDireccion(request.getParameter("ruDireccion"));
        nuevoUsuario.setIdCiudad(Integer.parseInt(request.getParameter("ruCiudad")));
        nuevoUsuario.setImagen(null);
        nuevoUsuario.setEstado(1);
        if (request.getParameter("notificaciones") == null) {

        } else if (request.getParameter("notificaciones") != null) {
            nuevoUsuario.setNotifaciones(1);
        }
        salida = faUsu.registrarUsuario(nuevoUsuario, suRol);

        if (salida.equals("ok")) {
            response.sendRedirect(
                    "index.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Registro xitoso!</strong> puede iniciar sesin.&tipoAlert=success");
        } else if (salida.equals("okno")) {
            response.sendRedirect(
                    "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Algo sali mal!</strong> Por favor intentelo de nuevo.&tipoAlert=warning");
        } else {
            response.sendRedirect(
                    "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ocurri un error!</strong> Detalle: "
                            + salida + "&tipoAlert=danger");
        }
    } else if (request.getParameter("recuperar") != null) {
        encript = new Encriptar();

        usuario = faUsu.obtenerUsuarioPorCorreo(request.getParameter("rcCorreo"));
        String correo = usuario.getCorreo();

        if (!correo.equals("")) {
            try {

                String con = Long.toString(usuario.getIdUsuario());
                String ced = encript.encode(con);

                String url = "http://localhost:8080/FarmersMarket/index.jsp?id=" + (ced);
                String mensaje = "<!DOCTYPE html>";
                mensaje += "<body>";
                mensaje += "<p>Se nos ha notificado la solicitud de recuperar tu contrasea, por favor ingresa al siguiente enlace y sigue las instrucciones"
                        + " para poder obtener tu contrasea lo antes posible</p>";
                mensaje += "<a href=" + url + ">Recuperar contrasea</a>";
                mensaje += "<br>-----------------------------------------------------------------------------------------------------------------";
                mensaje += "<p>Por favor no responder a este correo, es de uso exclusivo para notificaciones y solicitudes."
                        + "<br>No se le dara una respuesta por motivos de administracin y seguridad, si tiene algun inconveniente por favor"
                        + " contacte a nuestros administradores desde nuestro sistema en el siguiente enlace</p>";
                mensaje += "<a href='http://localhost:8080/FarmersMarket/index.jsp'>Farmers Market</a>";
                mensaje += "<br>-----------------------------------------------------------------------------------------------------------------";
                if (Correo.sendMail("Recuperar Contrasea", mensaje, correo)) {
                    response.sendRedirect(
                            "index.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Solicitud enviada!</strong> Por favor revise su correo.&tipoAlert=success");
                } else {
                    response.sendRedirect(
                            "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ha ocurrido algo!</strong> Vuelva a intentarlo.&tipoAlert=warning");
                }

            } catch (EncoderException ex) {
                response.sendRedirect(
                        "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ocurri un error!</strong> Detalle: "
                                + ex.getMessage() + "&tipoAlert=danger");
            }
        } else if (correo.equals("")) {
            response.sendRedirect(
                    "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Lo sentimos!</strong> El correo no se encuentra registrado."
                            + correo + "&tipoAlert=warning");
        }
    } else if (request.getParameter("recuperarCodigo") != null) {
        encript = new Encriptar();
        if (request.getParameter("rcCodigo").trim().equals(request.getParameter("codigo"))) {

            try {
                String cedula = encript.Decode(request.getParameter("encriptacion"));
                usuario = faUsu.obtenerUsuarioPorDocumento(Long.parseLong(cedula));
                if (!usuario.getClave().equals("")) {
                    response.sendRedirect(
                            "index.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Hemos recuperado tu contrasea :D es la siguiente: <i>"
                                    + usuario.getClave()
                                    + "</i>!</strong> te recomendamos  cambiarla lo antes posible.&tipoAlert=success");
                } else {
                    response.sendRedirect(
                            "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ha ocurrido algo!</strong> Vuelva a intentarlo.&tipoAlert=warning");
                }
            } catch (Exception ex) {
                response.sendRedirect(
                        "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ocurri un error!</strong> Detalle: "
                                + ex.getMessage() + "&tipoAlert=danger");
            }
        } else {
            response.sendRedirect(
                    "index.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> El codigo que ingreso no es correcto!</strong> Intentelo de nuevo.&tipoAlert=warning");
        }
    } else if (request.getParameter("cambiarPass") != null) {

        usuario = faUsu.obtenerUsuarioPorDocumento(Long.parseLong(request.getParameter("ccDocumento")));
        boolean admin = false;
        HttpSession miSesionRoles = request.getSession(false);
        ArrayList<RolDto> rolesActuales;
        rolesActuales = (ArrayList<RolDto>) miSesionRoles.getAttribute("roles");
        for (RolDto rol : rolesActuales) {
            if (rol.getIdRol() == 3) {
                admin = true;
            }
        }
        if (usuario.getClave().equals(request.getParameter("ccClaveAntigua"))) {
            salida = faUsu.cambiarContrasena(request.getParameter("ccClaveNueva"),
                    Long.parseLong(request.getParameter("ccDocumento")));
            if (salida.equals("ok")) {
                if (admin) {
                    response.sendRedirect(
                            "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Su contrasea a sido modificada!</strong>&tipoAlert=success");
                } else {
                    response.sendRedirect(
                            "pages/indexp.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Su contrasea a sido modificada!</strong>&tipoAlert=success");
                }
            } else if (salida.equals("okno")) {
                response.sendRedirect(
                        "pages/indexp.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> Ha ocurrido algo!</strong> Vuelva a intentarlo.&tipoAlert=warning");
            }

        } else {
            if (admin) {
                response.sendRedirect(
                        "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> La contrasea no es correcta!</strong> Vuelva a intentarlo.&tipoAlert=warning");
            } else {
                response.sendRedirect(
                        "pages/indexp.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> La contrasea no es correcta!</strong> Vuelva a intentarlo.&tipoAlert=warning");
            }
        }
    } else if (request.getParameter("idUsuarioConsulta") != null) {

        UsuarioDto informacion = faUsu
                .obtenerUsuarioPorDocumento(Long.parseLong(request.getParameter("idUsuarioConsulta")));
        HttpSession miSesion = request.getSession(true);
        miSesion.setAttribute("infUsuario", informacion);
        response.sendRedirect("pages/informacionusuario.jsp");
    } else if (request.getParameter("actualizarDatos") != null) {
        String correo = faUsu.correoRegistrado(request.getParameter("pffCorreo"),
                Long.parseLong(request.getParameter("auDocumento")));
        if (correo.equals("")) {
            String mensaje = faUsu.actualizarDatos(request.getParameter("pffDireccion"),
                    request.getParameter("pffCorreo"), Long.parseLong(request.getParameter("auDocumento")));
            if (mensaje.equals("ok")) {
                response.sendRedirect(
                        "pages/perfil.jsp?msg=<strong><i class='glyphicon glyphicon-ok'></i> Sus datos han sido modificados!</strong>&tipoAlert=success");
                HttpSession miSesion = request.getSession(false);
                UsuarioDto datosPersona = faUsu
                        .obtenerUsuarioPorDocumento(Long.parseLong(request.getParameter("auDocumento")));
                miSesion.setAttribute("usuarioEntro", datosPersona);
            } else {
                response.sendRedirect(
                        "pages/perfil.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se logro actualizar sus datos!</strong> Vuelva a intentarlo.&tipoAlert=warning");
            }
        } else {
            response.sendRedirect(
                    "pages/perfil.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> El correo ya se encuentra registrado!</strong> Vuelva a intentarlo.&tipoAlert=warning");
        }
    } else {
        response.sendRedirect("pages/indexp.jsp");
    }
}

From source file:com.node.action.UserAction.java

/**
 * // w  w  w .j  a  v  a  2  s.  c o  m
 * ??excel
 * 
 * @param request
 * @param response
 * @version: 1.0
 * @author: liuwu
 * @version: 201642 ?5:53:39
 */
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
    response.reset();
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String hf = request.getParameter("hfs");
    String type = request.getParameter("type");
    String exportname = "grid";
    try {
        if (type.equals("excel")) {
            exportname += ".xls";
            response.setHeader("Content-disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(exportname, "UTF-8") + "");
            response.setContentType("application/msexcel;charset=utf-8");
        } else if (type.equals("word")) {
            exportname += ".doc";
            response.setHeader("Content-disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(exportname, "UTF-8") + "");
            response.setContentType("application/ms-word;charset=UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    PrintWriter out;
    try {
        out = response.getWriter();
        out.println(hf);
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.wx.CustomerWXServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//  www.  j  ava  2 s. co  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 {
    //processRequest(request, response);
    //?
    response.setContentType("text/html;charset=utf-8");
    //response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");

    //????
    String sToken = "testToken";
    String sCorpID = "wxe706b25abb1216c0";
    String sEncodingAESKey = "AWdjbue1y51jzlAMwBCSm9GDt7zW6zuIbNqGEPcqsRR";

    try {
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);

        // ?url?
        //URLDecoder.decode(request.getParameter("echostr"),"utf-8");
        String sVerifyMsgSig = URLDecoder.decode(request.getParameter("msg_signature"), "utf-8");
        String sVerifyTimeStamp = URLDecoder.decode(request.getParameter("timestamp"), "utf-8");
        String sVerifyNonce = URLDecoder.decode(request.getParameter("nonce"), "utf-8");
        String sVerifyEchoStr = URLDecoder.decode(request.getParameter("echostr"), "utf-8");

        PrintWriter out = response.getWriter();
        String sEchoStr; //?
        try {
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
            System.out.println("verifyurl echostr: " + sEchoStr);
            // ?URL?sEchoStr
            out.print(sEchoStr);
            out.close();
            out = null;
        } catch (Exception e) {
            //?URL
            e.printStackTrace();
        }

    } catch (AesException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:com.bluexml.side.framework.alfresco.shareLanguagePicker.CustomWebScriptView.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // Expose the model object as request attributes.
    exposeModelAsRequestAttributes(model, request);

    if (logger.isDebugEnabled())
        logger.debug("Processing request (" + request.getMethod() + ") " + request.getRequestURL()
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));

    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }/*from   w  ww.  ja  v a 2  s .  co m*/

    Locale resolveLocale = localeResolver.resolveLocale(request);
    localeResolver.setLocale(request, response, resolveLocale);

    // hand off to the WebScript Servlet View runtime
    WebScriptViewRuntime runtime = new WebScriptViewRuntime(getUrl(), container, authenticatorFactory, request,
            response, serverProperties);
    runtime.executeScript();
}

From source file:com.ultrapower.eoms.common.plugin.ecside.filter.ECSideFilter.java

    public void doAjaxFilter(HttpServletRequest request,HttpServletResponse response,FilterChain chain)throws IOException, ServletException{
       //from  ww  w. j av a2s.c  o  m
      request.setCharacterEncoding("UTF-8");
//      response.setCharacterEncoding("UTF-8");
      
        String easyListName=getEasyList(request);
        String easyDataAccessName=getEasyDataAccess(request);

      String findAjaxZoneAtClient=request.getParameter(TableConstants.AJAX_FINDZONE_CLIENT);
      if (findAjaxZoneAtClient!=null && ("false".equalsIgnoreCase(findAjaxZoneAtClient)||"0".equals(findAjaxZoneAtClient))) {
         ECSideAjaxResponseWrapper bufferResponseWrapper = new ECSideAjaxResponseWrapper(response);
         try {

            String ectableId = request.getParameter(TableConstants.EXTREME_COMPONENTS_INSTANCE);
            if (easyListName!=null){
               easyDataAccessHandler.easyList(request,bufferResponseWrapper,getEasyListModelBean(request,easyListName));
            }else if (easyDataAccessName!=null){
               String sqlName=getSqlName(request);
               easyDataAccessHandler.dataAccess(getDataAccessModelBean(request,easyDataAccessName), sqlName, request, response);
            }
            chain.doFilter(request, bufferResponseWrapper);
            String zone = bufferResponseWrapper.findSubstring(
                  ECSideUtils.getAjaxBegin(ectableId), ECSideUtils.getAjaxEnd(ectableId));
            HttpServletResponse originalResponse = bufferResponseWrapper.getOriginalResponse();
            if (zone!=null){
               originalResponse.getOutputStream().write(zone.getBytes("UTF-8"));
            }
//            originalResponse.flushBuffer();
            originalResponse.getOutputStream().flush();
            originalResponse.getOutputStream().close();
         } catch (Exception e) {
            LogHandler.errorLog(logger, e);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("Exception:<br />\n"+ExceptionUtils.formatStackTrace(e).replaceAll("\n","<br/>\n"));
            response.getWriter().close();
            
         }
      } else {
         if (easyListName!=null){
            easyDataAccessHandler.easyList(request,response,getEasyListModelBean(request,easyListName));
         }else if (easyDataAccessName!=null){
            String sqlName=getSqlName(request);
            easyDataAccessHandler.dataAccess(getDataAccessModelBean(request,easyDataAccessName), sqlName, request, response);
         }
         chain.doFilter(request, response);
      }
    }

From source file:org.ecocean.servlet.UserCreate.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String context = "context0";
    //context=ServletUtilities.getContext(request);

    //set up the user directory
    //setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
    if (!shepherdDataDir.exists()) {
        shepherdDataDir.mkdirs();// w  ww  . j ava2  s  .  c o m
    }
    File usersDir = new File(shepherdDataDir.getAbsolutePath() + "/users");
    if (!usersDir.exists()) {
        usersDir.mkdirs();
    }

    //set up for response
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    boolean createThisUser = false;

    String addedRoles = "";
    boolean isEdit = false;
    if (request.getParameter("isEdit") != null) {
        isEdit = true;
        //System.out.println("isEdit is TRUE in UserCreate!");
    }

    //create a new Role from an encounter

    if ((request.getParameter("username") != null) && (!request.getParameter("username").trim().equals(""))
            && (((request.getParameter("password") != null)
                    && (!request.getParameter("password").trim().equals(""))
                    && (request.getParameter("password2") != null)
                    && (!request.getParameter("password2").trim().equals("")))
                    || (request.getParameter("isEdit") != null))) {

        String username = request.getParameter("username").trim();

        String password = "";
        if (!isEdit)
            password = request.getParameter("password").trim();
        String password2 = "";
        if (!isEdit)
            password2 = request.getParameter("password2").trim();

        if ((password.equals(password2)) || (isEdit)) {

            Shepherd myShepherd = new Shepherd(context);
            myShepherd.setAction("UserCreate.class");

            User newUser = new User();

            myShepherd.beginDBTransaction();

            if (myShepherd.getUser(username) == null) {

                String salt = ServletUtilities.getSalt().toHex();
                String hashedPassword = ServletUtilities.hashAndSaltPassword(password, salt);
                //System.out.println("hashed password: "+hashedPassword+" with salt "+salt + " from source password "+password);
                newUser = new User(username, hashedPassword, salt);
                myShepherd.getPM().makePersistent(newUser);
                createThisUser = true;
            } else {
                newUser = myShepherd.getUser(username);
            }

            //here handle all of the other User fields (e.g., email address, etc.)
            if ((request.getParameter("fullName") != null)
                    && (!request.getParameter("fullName").trim().equals(""))) {
                newUser.setFullName(request.getParameter("fullName").trim());
            } else if (isEdit && (request.getParameter("fullName") != null)
                    && (request.getParameter("fullName").trim().equals(""))) {
                newUser.setFullName(null);
            }

            if (request.getParameter("receiveEmails") != null) {
                newUser.setReceiveEmails(true);
            } else {
                newUser.setReceiveEmails(false);
            }

            if ((request.getParameter("emailAddress") != null)
                    && (!request.getParameter("emailAddress").trim().equals(""))) {
                newUser.setEmailAddress(request.getParameter("emailAddress").trim());
            } else if (isEdit && (request.getParameter("emailAddress") != null)
                    && (request.getParameter("emailAddress").trim().equals(""))) {
                newUser.setEmailAddress(null);
            }

            if ((request.getParameter("affiliation") != null)
                    && (!request.getParameter("affiliation").trim().equals(""))) {
                newUser.setAffiliation(request.getParameter("affiliation").trim());
            } else if (isEdit && (request.getParameter("affiliation") != null)
                    && (request.getParameter("affiliation").trim().equals(""))) {
                newUser.setAffiliation(null);
            }

            if ((request.getParameter("userProject") != null)
                    && (!request.getParameter("userProject").trim().equals(""))) {
                newUser.setUserProject(request.getParameter("userProject").trim());
            } else if (isEdit && (request.getParameter("userProject") != null)
                    && (request.getParameter("userProject").trim().equals(""))) {
                newUser.setUserProject(null);
            }

            if ((request.getParameter("userStatement") != null)
                    && (!request.getParameter("userStatement").trim().equals(""))) {
                newUser.setUserStatement(request.getParameter("userStatement").trim());
            } else if (isEdit && (request.getParameter("userStatement") != null)
                    && (request.getParameter("userStatement").trim().equals(""))) {
                newUser.setUserStatement(null);
            }

            if ((request.getParameter("userURL") != null)
                    && (!request.getParameter("userURL").trim().equals(""))) {
                newUser.setUserURL(request.getParameter("userURL").trim());
            } else if (isEdit && (request.getParameter("userURL") != null)
                    && (request.getParameter("userURL").trim().equals(""))) {
                newUser.setUserURL(null);
            }

            newUser.RefreshDate();

            //now handle roles

            //if this is not a new user, we need to blow away all old roles
            List<Role> preexistingRoles = new ArrayList<Role>();
            if (!createThisUser) {
                //get existing roles for this existing user
                preexistingRoles = myShepherd.getAllRolesForUser(username);
                myShepherd.getPM().deletePersistentAll(preexistingRoles);
            }

            //start role processing

            List<String> contexts = ContextConfiguration.getContextNames();
            int numContexts = contexts.size();
            //System.out.println("numContexts is: "+numContexts);
            for (int d = 0; d < numContexts; d++) {

                String[] roles = request.getParameterValues("context" + d + "rolename");
                if (roles != null) {
                    int numRoles = roles.length;
                    //System.out.println("numRoles in context"+d+" is: "+numRoles);
                    for (int i = 0; i < numRoles; i++) {

                        String thisRole = roles[i].trim();
                        if (!thisRole.trim().equals("")) {
                            Role role = new Role();
                            if (myShepherd.getRole(thisRole, username, ("context" + d)) == null) {

                                role.setRolename(thisRole);
                                role.setUsername(username);
                                role.setContext("context" + d);
                                myShepherd.getPM().makePersistent(role);
                                addedRoles += ("SEPARATORSTART"
                                        + ContextConfiguration.getNameForContext("context" + d) + ":" + roles[i]
                                        + "SEPARATOREND");
                                //System.out.println(addedRoles);
                                myShepherd.commitDBTransaction();
                                myShepherd.beginDBTransaction();
                                //System.out.println("Creating role: context"+d+thisRole);
                            }
                        }
                    }
                }
            }
            //end role processing

            myShepherd.commitDBTransaction();
            myShepherd.closeDBTransaction();
            myShepherd = null;

            //output success statement
            out.println(ServletUtilities.getHeader(request));
            if (createThisUser) {
                out.println("<strong>Success:</strong> User '" + StringEscapeUtils.escapeHtml4(username)
                        + "' was successfully created with added roles: <ul>"
                        + addedRoles.replaceAll("SEPARATORSTART", "<li>").replaceAll("SEPARATOREND", "</li>")
                        + "</ul>");
            } else {
                out.println("<strong>Success:</strong> User '" + StringEscapeUtils.escapeHtml4(username)
                        + "' was successfully updated and has assigned roles: <ul>"
                        + addedRoles.replaceAll("SEPARATORSTART", "<li>").replaceAll("SEPARATOREND", "</li>")
                        + "</ul>");

            }
            out.println("<p><a href=\"" + request.getScheme() + "://"
                    + CommonConfiguration.getURLLocation(request) + "/appadmin/users.jsp?context=context0"
                    + "\">Return to User Administration" + "</a></p>\n");
            out.println(ServletUtilities.getFooter(context));

        } else {
            //output failure statement
            out.println(ServletUtilities.getHeader(request));
            out.println(
                    "<strong>Failure:</strong> User was NOT successfully created. Your passwords did not match.");
            out.println("<p><a href=\"" + request.getScheme() + "://"
                    + CommonConfiguration.getURLLocation(request) + "/appadmin/users.jsp?context=context0"
                    + "\">Return to User Administration" + "</a></p>\n");
            out.println(ServletUtilities.getFooter(context));

        }

    } else {
        //output failure statement
        out.println(ServletUtilities.getHeader(request));
        out.println(
                "<strong>Failure:</strong> User was NOT successfully created. I did not have all of the username and password information I needed.");
        out.println("<p><a href=\"" + request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/appadmin/users.jsp?context=context0" + "\">Return to User Administration" + "</a></p>\n");
        out.println(ServletUtilities.getFooter(context));

    }

    out.close();

}

From source file:tw.com.sbi.product.controller.Service.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    ServiceService serviceService = null;

    String groupId = request.getSession().getAttribute("group_id").toString();
    String action = request.getParameter("action");

    logger.debug("Action: " + action);

    if ("selectAll".equals(action)) {

    } else if ("selectByProductId".equals(action)) {
        try {//ww  w.j ava2  s  .  c o m
            serviceService = new ServiceService();
            String product_id = request.getParameter("product_id");

            List<ProductServiceVO> list = serviceService.selectByProductId(product_id);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("selectByProductSpec".equals(action)) {
        try {
            serviceService = new ServiceService();
            String product_spec = request.getParameter("product_spec");

            List<ProductServiceVO> list = serviceService.selectByProductSpec(product_spec);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("genService".equals(action)) {
        try {
            String productId = request.getParameter("product_id");
            String quantity = request.getParameter("quantity");

            logger.debug("Product ID: " + productId);
            logger.debug("Quantity: " + quantity);

            serviceService = new ServiceService();

            List<ProductServiceVO> list = serviceService.genServiceID(groupId, productId, quantity);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

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

    }

}

From source file:com.openkm.servlet.frontend.DownloadServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("service({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String path = request.getParameter("path");
    String uuid = request.getParameter("uuid");
    String[] uuidList = request.getParameterValues("uuidList");
    String[] pathList = request.getParameterValues("pathList");
    String checkout = request.getParameter("checkout");
    String ver = request.getParameter("ver");
    boolean export = request.getParameter("export") != null;
    boolean inline = request.getParameter("inline") != null;
    File tmp = File.createTempFile("okm", ".tmp");
    InputStream is = null;/*from   ww w.j a  v  a  2s.c  o  m*/
    updateSessionManager(request);

    try {
        // Now an document can be located by UUID
        if (uuid != null && !uuid.equals("")) {
            uuid = FormatUtil.sanitizeInput(uuid);
            path = OKMRepository.getInstance().getNodePath(null, uuid);
        } else if (path != null) {
            path = FormatUtil.sanitizeInput(path);
            path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
        }

        if (export) {
            if (exportZip) {
                FileOutputStream os = new FileOutputStream(tmp);
                String fileName = "export.zip";

                if (path != null) {
                    exportFolderAsZip(path, os);
                    fileName = PathUtils.getName(path) + ".zip";
                } else if (uuidList != null || pathList != null) {
                    // Export into a zip file multiple documents
                    List<String> paths = new ArrayList<String>();

                    if (uuidList != null) {
                        for (String uuidElto : uuidList) {
                            String foo = new String(uuidElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(OKMRepository.getInstance().getNodePath(null, foo));
                        }
                    } else if (pathList != null) {
                        for (String pathElto : pathList) {
                            String foo = new String(pathElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(foo);
                        }
                    }

                    fileName = PathUtils.getName(PathUtils.getParent(paths.get(0)));
                    exportDocumentsAsZip(paths, os, fileName);
                    fileName += ".zip";
                }

                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                WebUtils.sendFile(request, response, fileName, MimeTypeConfig.MIME_ZIP, inline, is);
            } else if (exportJar) {
                // Get document
                FileOutputStream os = new FileOutputStream(tmp);
                exportFolderAsJar(path, os);
                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                String fileName = PathUtils.getName(path) + ".jar";
                WebUtils.sendFile(request, response, fileName, "application/x-java-archive", inline, is);
            }
        } else {
            if (OKMDocument.getInstance().isValid(null, path)) {
                // Get document
                Document doc = OKMDocument.getInstance().getProperties(null, path);

                if (ver != null && !ver.equals("")) {
                    is = OKMDocument.getInstance().getContentByVersion(null, path, ver);
                } else {
                    is = OKMDocument.getInstance().getContent(null, path, checkout != null);
                }

                // Send document
                String fileName = PathUtils.getName(doc.getPath());
                WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
            } else if (OKMMail.getInstance().isValid(null, path)) {
                // Get mail
                Mail mail = OKMMail.getInstance().getProperties(null, path);

                // Send mail
                ServletOutputStream sos = response.getOutputStream();
                String fileName = PathUtils.getName(mail.getSubject() + ".eml");
                WebUtils.prepareSendFile(request, response, fileName, MimeTypeConfig.MIME_EML, inline);
                response.setContentLength((int) mail.getSize());
                MimeMessage m = MailUtils.create(null, mail);
                m.writeTo(sos);
                sos.flush();
                sos.close();
            }
        }
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound),
                e.getMessage()));
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(
                new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository),
                        e.getMessage()));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage()));
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage()));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(tmp);
    }

    log.debug("service: void");
}