Example usage for org.apache.commons.fileupload DiskFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload DiskFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload DiskFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest req) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it.//from www  . j  ava  2  s.c  o  m
 *
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /*from   w  ww.j  a v a2s .com*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("ConnectorServlet.doPost");
    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }
    System.out.println("1111111111111111111111");
    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.baobao121.baby.common.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /*  w w w.j  av a2s  . c o  m*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:crds.pub.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from ww  w. java2  s  .  c o m*/
 *
 */
@SuppressWarnings({ "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id
            + currentFolderStr + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from   w w  w  . j  ava 2s. c  om*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);

            //???IP
            String server_ip = (String) session.getAttribute("server_ip");
            if (server_ip == null) {
                server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
            }
            String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());

            fileUrl = url + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = url + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

public Hashtable getHashtable(HttpServletRequest request) throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {//from ww  w  . ja v a  2  s  .c o  m
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,/*from  w  w w  .ja v  a2 s .  com*/
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}

From source file:forseti.admon.JAdmAWSS3Dlg.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    String adm_awss3_dlg = "";
    request.setAttribute("adm_awss3_dlg", adm_awss3_dlg);
    String mensaje = "";
    short idmensaje = -1;

    if (request.getContentType() != null
            && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
        if (!getSesion(request).getRegistrado()) {
            irApag("/forsetiadmin/errorAtributos.jsp", request, response);
            return;
        } else {//from  ww w . ja v a 2  s  .c  o m
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3||||", mensaje);
                irApag("/forsetiaweb/caja_mensajes.jsp", request, response);
                return;
            }

            try {
                JGestionArchivos gestion = new JGestionArchivos();
                DiskFileUpload fu = new DiskFileUpload();
                List items = fu.parseRequest(request);
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("ID_MODULO"))
                            gestion.setID_MODULO(item.getString());
                        else if (item.getFieldName().equals("OBJIDS"))
                            gestion.setOBJIDS(item.getString());
                        else if (item.getFieldName().equals("IDSEP"))
                            gestion.setIDSEP(item.getString());
                    } else
                        gestion.getArchivos().addElement(item);
                }

                if (!getSesion(request).getPermiso(gestion.getID_MODULO())) {
                    idmensaje = 3;
                    mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                            "ADM_AWSS3_GESTIONAR", "AAS3||||", mensaje);
                    irApag("/forsetiaweb/caja_mensajes.jsp", request, response);
                    return;
                }

                SubirArchivo(request, response, gestion);
                return;
            } catch (FileUploadException e) {
                e.printStackTrace();
                return;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

        }

    }

    if (request.getParameter("proceso") != null && !request.getParameter("proceso").equals("")) {
        if (request.getParameter("proceso").equals("SUBIR_ARCHIVO")) {
            // Revisa si tiene permisos
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }

            getSesion(request).setID_Mensaje(idmensaje, mensaje);
            irApag("/forsetiweb/administracion/adm_awss3_dlg.jsp", request, response);
            return;

        } else if (request.getParameter("proceso").equals("DESCARGAR_ARCHIVO")) {
            if (!getSesion(request).getPermiso("ADM_AWSS3")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADM_AWSS3",
                        "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADM_AWSS3",
                        "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }
            // Solicitud de envio a procesar
            if (request.getParameter("id") != null) {
                String[] valoresParam = request.getParameterValues("id");
                if (valoresParam.length == 1) {
                    // Verificacion
                    Descargar(request, response, request.getParameter("id"));
                    return;
                } else {
                    idmensaje = 1;
                    mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2);
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                    return;
                }
            } else {
                idmensaje = 3;
                mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1);
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }
        } else if (request.getParameter("proceso").equals("ELIMINAR_ARCHIVO")) {
            // Revisa si tiene permisos
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }

            // Solicitud de envio a procesar
            if (request.getParameter("id") != null) {
                String[] valoresParam = request.getParameterValues("id");
                if (valoresParam.length == 1) {
                    //System.out.println("POST:" + request.getParameter("id") + ":request.getParameter(id)");
                    Eliminar(request, response, request.getParameter("id"));
                    return;
                } else {
                    idmensaje = 1;
                    mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2);
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                    return;
                }
            } else {
                idmensaje = 3;
                mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1);
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }
        } else {
            idmensaje = 3;
            mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3);
            getSesion(request).setID_Mensaje(idmensaje, mensaje);
            irApag("/forsetiweb/caja_mensajes.jsp", request, response);
            return;
        }

    } else // si no se mandan parametros, manda a error
    {
        idmensaje = 3;
        mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3);
        getSesion(request).setID_Mensaje(idmensaje, mensaje);
        irApag("/forsetiweb/caja_mensajes.jsp", request, response);
        return;
    }

}

From source file:com.krawler.spring.hrms.common.hrmsDocumentController.java

public ModelAndView addDocuments(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    List fileItems = null;//w w  w.  j  a  va  2  s.co  m
    KwlReturnObject kmsg = null;
    String auditAction = "";
    boolean applicant = false;
    String id = java.util.UUID.randomUUID().toString();
    PrintWriter out = null;
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        String userid = sessionHandlerImplObj.getUserid(request);
        String map = request.getParameter("mapid");
        HashMap<String, String> arrParam = new HashMap<String, String>();
        boolean fileUpload = false;
        String docdesc;
        ArrayList<FileItem> fi = new ArrayList<FileItem>();
        if (request.getParameter("fileAdd") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            documentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
            arrParam.put("IsIE", request.getParameter("IsIE"));
            if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
                applicant = true;
                userid = arrParam.get("refid");
            }
            if (StringUtil.isNullOrEmpty((String) arrParam.get("docdesc")) == false) {
                docdesc = (String) arrParam.get("docdesc");
            }
        }
        for (int cnt = 0; cnt < fi.size(); cnt++) {
            String docID;
            if (applicant) {
                kmsg = hrmsExtApplDocsDAOObj.uploadFile(fi.get(cnt), userid, arrParam,
                        profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request)));
                HrmsDocs doc = (HrmsDocs) kmsg.getEntityList().get(0);
                docID = doc.getDocid();
            } else {
                kmsg = documentDAOObj.uploadFile(fi.get(cnt), userid, arrParam);
                Docs doc = (Docs) kmsg.getEntityList().get(0);
                docID = doc.getDocid();
            }

            String companyID = sessionHandlerImplObj.getCompanyid(request);
            String userID = sessionHandlerImplObj.getUserid(request);
            String refid = arrParam.get("refid");
            jobj.put("userid", userID);
            jobj.put("docid", docID);
            jobj.put("companyid", companyID);
            jobj.put("id", id);
            jobj.put("map", map);
            jobj.put("refid", refid);
            if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
                hrmsExtApplDocsDAOObj.saveDocumentMapping(jobj);
            } else {
                documentDAOObj.saveDocumentMapping(jobj);
            }
        }
        myjobj.put("ID", id);
        txnManager.commit(status);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        txnManager.rollback(status);
    } finally {
        out.close();
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:com.baobao121.baby.common.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * /*w  w w  .j a va 2  s . com*/
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    String currentPath = "";
    String currentDirPath = "";
    String typeStr = request.getParameter("Type");
    UserCommonInfo info = null;
    info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO);
    if (info == null) {
        info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO);
    }
    currentPath = baseDir + "images/";
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) {
        currentPath += "admin/";
    } else {
        if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) {
            currentPath += "babyInfo/";
        }
        if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) {
            currentPath += "teacherInfo/";
        }
    }
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    currentPath += info.getId();
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            upload.setHeaderEncoding("utf-8");
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");

            String fileNameLong = uplFile.getName();
            InputStream is = uplFile.getInputStream();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];
            Calendar calendar = Calendar.getInstance();
            String nameWithoutExt = String.valueOf(calendar.getTimeInMillis());
            ;
            String ext = getExtension(fileName);
            fileName = nameWithoutExt + "." + ext;
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName);
                changeDimension(is, desc, 450, 1000);
                if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) {
                    Photo photo = new Photo();
                    photo.setPhotoName(fileName);
                    PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName());
                    if (album.getId() != null) {
                        Long albumId = album.getId();
                        photo.setPhotoAlbumId(albumId);
                        photo.setPhotoLink(fileUrl);
                        photo.setDescription("");
                        photo.setReadCount(0L);
                        photo.setCommentCount(0L);
                        photo.setReadPopedom("1");
                        photo.setCreateTime(DateUtil.getCurrentDateTimestamp());
                        photo.setModifyTime(DateUtil.getCurrentDateTimestamp());
                        babyPhotoDao.save(photo);
                        babyAlbumDao.updateAlbumCount(albumId);
                    }
                }
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("?: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "??";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','"
            + newName + "','" + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}