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.dspace.app.dav.DAVServlet.java

/**
 * Pass this request along to the appropriate resource and method. Includes
 * authentication, where needed. Return true if we handle this request,
 * false otherwise. True means response has been "sent", false not.
 * /*from w w  w.ja v a2  s  .c  o  m*/
 * @param method the method
 * @param request the request
 * @param response the response
 * 
 * @return true, if service internal
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected static boolean serviceInternal(String method, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Fake new DAV methods not understood by the Apache Servlet base class
    // (returns HTTP/500 when it sees unrecognised method)
    // The way it is faked is by submitting "delete=true" in the PUT URL's
    // query parameters (for a delete)
    // The way it is faked is by submitting "mkcol=true" in the PUT URL's
    // query parameters (for a mk-collection)
    if (method.equals(METHOD_PUT) && request.getQueryString().indexOf("delete=true") >= 0) {
        method = METHOD_DELETE;
    }
    if (method.equals(METHOD_PUT) && request.getQueryString().indexOf("mkcol=true") >= 0) {
        method = METHOD_MKCOL;
    }

    // if not a DAV method (i.e. POST), defer to superclass.
    if (!(method.equals(METHOD_PROPFIND) || method.equals(METHOD_PROPPATCH) || method.equals(METHOD_MKCOL)
            || method.equals(METHOD_COPY) || method.equals(METHOD_MOVE) || method.equals(METHOD_DELETE)
            || method.equals(METHOD_GET) || method.equals(METHOD_PUT))) {
        return false;
    }

    // set all incoming encoding to UTF-8
    request.setCharacterEncoding("UTF-8");
    String pathElt[] = getDavResourcePath(request).split("/");

    Context context = null;
    try {
        // this sends a response on failure, unless it throws.
        context = authenticate(request, response, null, null);
        if (context == null) {
            return true;
        }

        // Note: findResource sends error response if it fails.
        DAVResource resource = DAVResource.findResource(context, request, response, pathElt);
        if (resource != null) {
            if (method.equals(METHOD_PROPFIND)) {
                resource.propfind();
            } else if (method.equals(METHOD_PROPPATCH)) {
                resource.proppatch();
            } else if (method.equals(METHOD_COPY)) {
                resource.copy();
            } else if (method.equals(METHOD_DELETE)) {
                resource.delete();
            } else if (method.equals(METHOD_MKCOL)) {
                resource.mkcol();
            } else if (method.equals(METHOD_GET)) {
                resource.get();
            } else if (method.equals(METHOD_PUT)) {
                resource.put();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
            }
            context.complete();
            context = null;
        }
    } catch (SQLException e) {
        log.error(e.toString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                truncateForStatus("Database access error: " + e.toString()));
    } catch (AuthorizeException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.toString(), e);
        } else {
            log.info(e.toString());
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                truncateForStatus("Access denied: " + e.toString()));
    } catch (DAVStatusException e) {
        log.error(e.toString(), e);
        response.sendError(e.getStatus(), truncateForStatus(e.getMessage()));
    } catch (IOException e) {
        log.error(e.toString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                truncateForStatus("IO Error: " + e.toString()));
    } catch (Exception e) {
        log.error(e.toString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                truncateForStatus("IO Error: " + e.toString()));
    } finally {
        // Abort the context if it's still valid
        if (context != null && context.isValid()) {
            context.abort();
        }
    }
    return true;
}

From source file:com.ikon.servlet.admin.RepositoryViewServlet.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");
    String path = WebUtils.getString(request, "path");
    Session session = null;// w  ww .java2 s  .co m
    updateSessionManager(request);

    try {
        session = JCRUtils.getSession();

        if (action.equals("unlock")) {
            unlock(session, path, request, response);
        } else if (action.equals("checkin")) {
            checkin(session, path, request, response);
        } else if (action.equals("remove_content")) {
            removeContent(session, path, request, response);
        } else if (action.equals("remove_current")) {
            path = removeCurrent(session, path, request, response);
        } else if (action.equals("remove_mixin")) {
            removeMixin(session, path, request, response);
        } else if (action.equals("edit")) {
            edit(session, path, request, response);
        } else if (action.equals("set_script")) {
            OKMScripting.getInstance().setScript(null, path, Config.DEFAULT_SCRIPT);
        } else if (action.equals("remove_script")) {
            OKMScripting.getInstance().removeScript(null, path);
        } else if (action.equals("textExtraction")) {
            textExtraction(session, path, request, response);
        }

        if (!action.equals("edit")) {
            list(session, path, request, response);
        }
    } catch (LoginException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (com.ikon.core.RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        JCRUtils.logout(session);
    }
}

From source file:com.megaeyes.web.controller.UserController.java

/**
 * @Title: updateUser// w  ww.j a v  a2 s  .  c o  m
 * @Description: 
 * @param @param request
 * @param @param response
 * @param @throws UnsupportedEncodingException 
 * @return void 
 * @throws
 */
@ControllerDescription(description = "?", isLog = true, isCheckSession = true)
@RequestMapping("/updateUser.json")
public void updateUser(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    BaseResponse resp = new BaseResponse();
    String id = (String) request.getAttribute("userId");
    String logonName = (String) request.getAttribute("logonName");
    String password = (String) request.getAttribute("password");
    String accessServerId = (String) request.getAttribute("accessServerId");
    String note = (String) request.getAttribute("note");
    String name = (String) request.getAttribute("name");
    String naming = (String) request.getAttribute("naming");
    String sex = (String) request.getAttribute("sex");
    Long age = null;
    String age1 = (String) request.getAttribute("age");
    if (StringUtils.isNotBlank(age1)) {
        try {
            age = Long.parseLong(age1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("age");
        }
    }
    String mobile = (String) request.getAttribute("mobile");
    String phone = (String) request.getAttribute("phone");
    String email = (String) request.getAttribute("email");
    Long maxSession = null;
    String maxSession1 = (String) request.getAttribute("maxSession");
    if (StringUtils.isNotBlank(maxSession1)) {
        try {
            maxSession = Long.parseLong(maxSession1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("maxSession");
        }
    }
    String userAccount = null;
    Short priority = null;
    String priority1 = (String) request.getAttribute("priority");
    if (StringUtils.isNotBlank(priority1)) {
        try {
            priority = Short.parseShort(priority1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("priority");
        }
    }
    String sipCode = (String) request.getAttribute("sipCode");
    String dispatchServerId = (String) request.getAttribute("dispatchServerId");
    if ("null".equals(dispatchServerId)) {
        dispatchServerId = "";
    }
    // ?
    Short isInnerUser = null;
    String isInnerUserString = request.getParameter("isInnerUser");
    if (StringUtils.isNotBlank(isInnerUserString)) {
        try {
            isInnerUser = Short.parseShort(isInnerUserString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("isInnerUser");
        }
    }
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            userManager.updateUser(id, logonName, password, accessServerId, note, name, naming, sex, age,
                    mobile, phone, email, maxSession, userAccount, priority, sipCode, dispatchServerId,
                    isInnerUser);
            resp.setCode(ErrorCode.SUCCESS);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
    }
    writePageNoZip(response, resp);

}

From source file:com.openkm.servlet.admin.RepositoryViewServlet.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");
    String path = WebUtils.getString(request, "path");
    Session session = null;// w  w w.j  av  a  2s  .  c  o  m
    updateSessionManager(request);

    try {
        session = JCRUtils.getSession();

        if (action.equals("unlock")) {
            unlock(session, path, request, response);
        } else if (action.equals("checkin")) {
            checkin(session, path, request, response);
        } else if (action.equals("remove_content")) {
            removeContent(session, path, request, response);
        } else if (action.equals("remove_current")) {
            path = removeCurrent(session, path, request, response);
        } else if (action.equals("remove_mixin")) {
            removeMixin(session, path, request, response);
        } else if (action.equals("edit")) {
            edit(session, path, request, response);
        } else if (action.equals("set_script")) {
            OKMScripting.getInstance().setScript(null, path, Config.DEFAULT_SCRIPT);
        } else if (action.equals("remove_script")) {
            OKMScripting.getInstance().removeScript(null, path);
        } else if (action.equals("textExtraction")) {
            textExtraction(session, path, request, response);
        }

        if (!action.equals("edit")) {
            list(session, path, request, response);
        }
    } catch (LoginException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (com.openkm.core.RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        JCRUtils.logout(session);
    }
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration//  www  .  j a v a  2 s .c o m
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:Controlador.Contr_Evento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w.  jav  a2  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 {
    /*Se detalla el contenido que tendra el servlet*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    /*Se crea una variable para la sesion*/
    HttpSession session = request.getSession(true);

    boolean b;
    try {
        /*Se declaran las variables necesarias*/
        Cls_Evento eve = new Cls_Evento();
        Cls_Mensajeria sms = new Cls_Mensajeria();
        String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti;
        String urlsalidaimg;
        urlsalidaimg = "/media/santiago/Santiago/IMGTE/";
        //urlsalidaimg = "I:\\IMGTE\\";
        String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Evento");

        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */

        List items = servlet_up.parseRequest(request);
        Iterator it = items.iterator();

        /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                //Plain request parameters will come here. 

                String name = item.getFieldName();
                if (name.equals("Creador")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCreador(item.getString());
                } else if (name.equals("Nombre")) {
                    /*Se guarda el campo en la clase*/
                    eve.setNombre(item.getString());
                } else if (name.equals("Codigo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCodigo(item.getString());
                } else if (name.equals("Rango")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRango(item.getString());
                } else if (name.equals("Rangomaximo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRangoMaximo(item.getString());
                } else if (name.equals("Fecha")) {
                    /*Se guarda el campo en la clase*/
                    eve.setFecha(item.getString());
                } else if (name.equals("Descripcion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDescipcion(item.getString());
                } else if (name.equals("Ciudad")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCiudad(item.getString());
                } else if (name.equals("Direccion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDireccion(item.getString());
                } else if (name.equals("Motivo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setMotivo(item.getString());
                } else if (name.equals("Latitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLatitud(item.getString());
                } else if (name.equals("Longitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLongitud(item.getString());
                } else if (name.equals("RegistrarEvento")) {
                    /*Se convierte la fecha a date*/
                    if (eve.ConvertirFecha(eve.getFecha())) {
                        /*Se evalua si la fecha tiene dos dias mas a la fecha de hoy*/
                        if (eve.ValidarDosDiasFecha(eve.getFechaDate())) {
                            /*Se evalua si se mando una iamgen*/
                            if (!eve.getImagen().equals("")) {
                                /*Si se envia una imagen obtiene la imagen para eliminarla luego*/
                                File img = new File(eve.getImagen());
                                /*Se ejecuta el metodo de registrar evento, en la clase modelo
                                 con los datos que se encuentran en la clase*/
                                String rangoprecios = eve.getRango() + "-" + eve.getRangoMaximo();
                                b = eve.setRegistrarEvento(eve.getTypeimg(), eve.getNombre(),
                                        eve.getFechaDate(), eve.getDescipcion(), rangoprecios, eve.getCreador(),
                                        eve.getCiudad(), eve.getDireccion(), eve.getLatitud(),
                                        eve.getLongitud());
                                if (b) {
                                    File imagedb = new File(
                                            urlimgservidor + "/" + eve.getCodigo() + eve.getTypeimg());
                                    img.renameTo(imagedb);
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje",
                                            "Se registro el evento satisfactoriamente.");
                                    session.setAttribute("TipoMensaje", "Dio");
                                    response.sendRedirect(
                                            "View/RClasificacionEvento.jsp?CodigoEvento=" + eve.getCodigo());
                                } else {
                                    img.delete();
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje", eve.getMensaje());
                                    session.setAttribute("TipoMensaje", "NODio");
                                    response.sendRedirect("View/RegistrarEvento.jsp");
                                }
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Seleccione una imagen para registrar el evento");
                                session.setAttribute("TipoMensaje", "NODio");
                                response.sendRedirect("View/RegistrarEvento.jsp");
                            }

                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "No se puede registrar un evento que inicie antes de dos das");
                            session.setAttribute("TipoMensaje", "NODio");
                            response.sendRedirect("View/RegistrarEvento.jsp");
                        }
                    } else {
                        /*Se guarda un mensaje mediante las sesiones
                         y se redirecciona*/
                        session.setAttribute("Mensaje",
                                "Ocurri un problema inesperado con la fecha del evento. Estamos trabajando para solucionar este problema.");
                        session.setAttribute("TipoMensaje", "NODio");
                        response.sendRedirect("View/RegistrarEvento.jsp");
                    }

                } else if (name.equals("DesactivarEvento")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se cancel el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/CEventoPendiente.jsp");
                } else if (name.equals("DesactivarEventoAdmin")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(administradir)*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se desaprob el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se desaprob el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al desaprobar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/ConsultaTodosEventos.jsp");
                } else if (name.equals("DesactivarEventoEmpresa")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(Empresa)*/
                        if (eve.setCancelarEvento(eve.getCodigo(), eve.getMotivo())) {
                            session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                        } else {
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }

                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/MisEventos.jsp");
                }

            } else {
                if (!item.getName().equals("")) {
                    //uploaded files will come here.
                    FileItem file = item;
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (sizeInBytes > 1000000) {
                        /*Se muestra un mensaje en caso de pesar mas de 3 MB*/
                        session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB");
                        session.setAttribute("TipoMensaje", "NODio");
                        /*Se redirecciona*/
                        response.sendRedirect("View/ConsultaSeleccion.jsp");
                    } else {
                        if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) {
                            if (contentType.indexOf("jpeg") > 0) {
                                contentType = ".jpg";
                            } else {
                                contentType = ".png";
                            }
                            /*Se crea la imagne*/
                            File archivo_server = new File(urlimgservidor + "/" + item.getName());
                            /*Se guardael url de la imagen en la clase*/
                            eve.setImagen(urlimgservidor + "/" + item.getName());
                            eve.setTypeimg(contentType);
                            /*Se guarda la imagen*/
                            item.write(archivo_server);
                        } else {
                            session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    }
                } else {
                    /**
                     * Se guardael url de la imagen en la clase
                     */
                    eve.setImagen("");
                }
            }
        }

        response.sendRedirect("View/index.jsp");
    } catch (FileUploadException ex) {
        System.out.print(ex.getMessage().toString());

    } catch (Exception ex) {
        Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

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

    //Authorize/*from  w w  w .j a v a2 s  .co  m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    request.setCharacterEncoding("UTF8");

    //update price

    //new product
    if (provider.getSerial() <= 0) {

        boolean status = providerDAO.saveOrUpdate(provider);

        if (status) {
            return SUCCESS;
        }
        return INPUT;
    } else {
        System.out.println("OK" + provider.getId());

        boolean status = providerDAO.update(provider);

        if (status) {

            return SUCCESS;
        }

        return INPUT;
    }
}

From source file:eionet.rpcserver.servlets.XmlRpcRouter.java

/**
 * Standard doPost implementation.//from w  ww  . j  a  v a  2 s.c o m
 *
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /*
    System.out.println("=============================");
    System.out.println("============POST ============");
    System.out.println("=============================");
            
    */
    byte[] result = null;
    //authorization here!

    String encoding = null;
    try {
        Hashtable<Object, Object> props = UITServiceRoster.loadProperties();

        encoding = (String) props.get(UITServiceRoster.PROP_XMLRPC_ENCODING);
    } catch (Exception e) {
    }

    if (encoding != null) {
        req.setCharacterEncoding(encoding);
        XmlRpc.setEncoding(encoding);
    }

    //get authorization header from request
    String auth = req.getHeader("Authorization");
    if (auth != null) {

        if (!auth.toUpperCase().startsWith("BASIC")) {
            throw new ServletException("wrong kind of authorization!");
        }

        //get encoded username and password
        String userPassEncoded = auth.substring(6);

        String userPassDecoded = new String(Base64.decodeBase64(userPassEncoded));

        //split decoded username and password
        StringTokenizer userAndPass = new StringTokenizer(userPassDecoded, ":");
        String username = userAndPass.nextToken();
        String password = userAndPass.nextToken();

        result = xmlrpc.execute(req.getInputStream(), username, password);
    } else {
        //log("================ 2 ");
        result = xmlrpc.execute(req.getInputStream());
    }

    res.setContentType("text/xml");
    res.setContentLength(result.length);
    OutputStream output = res.getOutputStream();
    output.write(result);
    output.flush();

    //req.getSession().invalidate(); //???????????????
}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    ServletContext sc = getServletContext();
    String action = null;//from   w  w w  . ja  v a  2s  . c  o m
    String filter = "";
    String userId = request.getRemoteUser();
    Session dbSession = null;
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            ConfigStoredFile stFile = new ConfigStoredFile();
            Config cfg = new Config();
            byte data[] = null;

            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("filter")) {
                        filter = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("cfg_key")) {
                        cfg.setKey(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_type")) {
                        cfg.setType(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_value")) {
                        cfg.setValue(item.getString("UTF-8").trim());
                    }
                } else {
                    is = item.getInputStream();
                    stFile.setName(item.getName());
                    stFile.setMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));

                    if (cfg.getKey() != null && cfg.getKey().startsWith("logo")) {
                        String size = null;

                        if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_LOGIN)) {
                            size = "316x74>";
                        } else if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_REPORT)) {
                            size = "150x35>";
                        }

                        File tmpIn = FileUtils.createTempFileFromMime(stFile.getMime());
                        File tmpOut = FileUtils.createTempFileFromMime(stFile.getMime());
                        FileOutputStream fos = null;

                        try {
                            fos = new FileOutputStream(tmpIn);
                            IOUtils.copy(is, fos);
                            ImageUtils.resize(tmpIn, size, tmpOut);
                            data = FileUtils.readFileToByteArray(tmpOut);
                        } finally {
                            FileUtils.deleteQuietly(tmpIn);
                            FileUtils.deleteQuietly(tmpOut);
                            IOUtils.closeQuietly(fos);
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        data = IOUtils.toByteArray(is);
                        IOUtils.closeQuietly(is);
                    }

                    stFile.setContent(SecureStore.b64Encode(data));
                }
            }

            if (action.equals("create")) {
                if (Config.FILE.equals(cfg.getType())) {
                    cfg.setValue(new Gson().toJson(stFile));
                } else if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.create(cfg);
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("edit")) {
                if (Config.FILE.equals(cfg.getType())) {
                    cfg.setValue(new Gson().toJson(stFile));
                } else if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            } else {
                                stOption.setSelected(false);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.update(cfg);
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("delete")) {
                ConfigDAO.delete(cfg.getKey());
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null);
                list(userId, filter, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importConfig(userId, request, response, data, dbSession);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null);
                list(userId, filter, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String formattedSvgEncoded = req.getParameter("fsvg");
    String rawSvgEncoded = req.getParameter("rsvg");
    String uuid = Utils.getUUID(req);
    String profileName = req.getParameter("profile");
    String transformto = req.getParameter("transformto");
    String jpdl = req.getParameter("jpdl");
    String gpd = req.getParameter("gpd");
    String bpmn2in = req.getParameter("bpmn2");
    String jsonin = req.getParameter("json");
    String preprocessingData = req.getParameter("pp");
    String respaction = req.getParameter("respaction");
    String pp = req.getParameter("pp");
    String processid = req.getParameter("processid");
    String sourceEnc = req.getParameter("enc");
    String convertServiceTasks = req.getParameter("convertservicetasks");

    String formattedSvg = (formattedSvgEncoded == null ? ""
            : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8"));
    //formattedSvg = URLDecoder.decode(formattedSvg, "UTF-8");
    String rawSvg = (rawSvgEncoded == null ? "" : new String(Base64.decodeBase64(rawSvgEncoded), "UTF-8"));
    //rawSvg = URLDecoder.decode(rawSvg, "UTF-8");

    if (sourceEnc != null && sourceEnc.equals("true")) {
        bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8");
    }//from w  ww. j  av  a 2  s .c  om
    IDiagramProfile profile = _profileService.findProfile(req, profileName);

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

    Repository repository = profile.getRepository();

    if (transformto != null && transformto.equals(TO_PDF)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PDFTranscoder t = new PDFTranscoder();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");

                resp.getWriter().write("<object data=\"data:application/pdf;base64,"
                        + Base64.encodeBase64(bout.toByteArray()) + "\" type=\"application/pdf\"></object>");
            } else {
                storeInRepository(uuid, rawSvg, transformto, processid, repository);

                resp.setContentType("application/pdf");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
                }

                PDFTranscoder t = new PDFTranscoder();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_PNG)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");
                resp.getWriter().write(
                        "<img src=\"data:image/png;base64," + Base64.encodeBase64(bout.toByteArray()) + "\">");
            } else {
                storeInRepository(uuid, rawSvg, transformto, processid, repository);
                resp.setContentType("image/png");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\"");
                }

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_SVG)) {
        storeInRepository(uuid, rawSvg, transformto, processid, repository);
    } else if (transformto != null && transformto.equals(JPDL_TO_BPMN2)) {
        try {
            String bpmn2 = JbpmMigration.transform(jpdl);
            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2);
            // add bpmndi info to Definitions with help of gpd
            addBpmnDiInfo(def, gpd);
            // hack for now
            revisitSequenceFlows(def, bpmn2);
            // another hack if id == name
            revisitNodeNames(def);

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String fullXmlModel = outputStream.toString();
            // convert to json and write response
            String json = profile.createUnmarshaller().parseModel(fullXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) {
        try {
            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\"");
                bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\"");
            }

            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in);
            def.setTargetNamespace("http://www.omg.org/bpmn20");

            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                // fix the data input associations for converted tasks
                List<RootElement> rootElements = def.getRootElements();
                for (RootElement root : rootElements) {
                    if (root instanceof Process) {
                        updateTaskDataInputs((Process) root, def);
                    }
                }
            }

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8");
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION,
                    true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF,
                    JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD);
            bpmn2resource.setEncoding("UTF-8");
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String revisedXmlModel = outputStream.toString();
            String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) {
        try {
            DroolsFactoryImpl.init();
            BpsimFactoryImpl.init();
            if (preprocessingData == null) {
                preprocessingData = "";
            }
            String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData);
            resp.setContentType("application/xml");
            resp.getWriter().print(processXML);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/xml");
            resp.getWriter().print("");
        }

    }
}