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:com.exedio.copernica.Form.java

@SuppressWarnings("deprecation") // TODO use new way of fileupload
public Form(final HttpServletRequest request) {
    this.request = request;

    if (FileUploadBase.isMultipartContent(request)) {
        final org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        final int maxSize = 100 * 1024; // TODO: make this configurable
        upload.setSizeThreshold(maxSize); // TODO: always save to disk
        upload.setSizeMax(maxSize);/*  ww  w.j a va  2s . c o  m*/
        //upload.setRepositoryPath("");
        multipartContentParameters = new HashMap<String, Object>();
        try {
            for (Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final String value = item.getString();
                    multipartContentParameters.put(name, value);
                } else {
                    final String name = item.getFieldName();
                    multipartContentParameters.put(name, item);
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }
    } else {
        multipartContentParameters = null;
    }
}

From source file:com.krawler.esp.servlets.deskeramob_V1.java

public static String createProject(Connection conn, HttpServletRequest request, String companyid,
        String subdomain, String userid) throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    java.util.List fileItems = null;
    PreparedStatement pstmt = null;
    String imageName = "";
    try {//from  w ww . ja v  a2 s.  c  om
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createProject", e);
    }

    java.util.HashMap arrParam = new java.util.HashMap();
    java.util.Iterator k = null;
    for (k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        pstmt = conn
                .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0");
        pstmt.setString(1, companyid);
        ResultSet rs = pstmt.executeQuery();
        int noProjects = 0;
        int maxProjects = 0;
        if (rs.next()) {
            noProjects = rs.getInt(1);
        }
        pstmt = conn.prepareStatement("select maxprojects from company where companyid =?");
        pstmt.setString(1, companyid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            maxProjects = rs.getInt(1);
        }
        if (noProjects == maxProjects) {
            return "The maximum limit for projects for this company has already reached";
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e);
    }
    try {
        String projectid = UUID.randomUUID().toString();
        String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString()
                .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim());
        String nickName = AdminServlet.makeNickName(conn, projName, 1);
        if (StringUtil.isNullOrEmpty(projName)) {
            status = "failure";
        } else {
            String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(qry);
            pstmt.setString(1, projectid);
            pstmt.setString(2, projName);
            pstmt.setString(3, arrParam.get("aboutproject").toString());
            pstmt.setString(4, imageName);
            pstmt.setString(5, companyid);
            pstmt.setString(6, nickName);
            int df = pstmt.executeUpdate();
            if (df != 0) {
                pstmt = conn.prepareStatement(
                        "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) "
                                + "VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, projectid);
                pstmt.setString(2, userid);
                pstmt.setInt(3, 4);
                pstmt.setBoolean(4, true);
                pstmt.setInt(5, 0);
                pstmt.executeUpdate();
            }
            //                        /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName});
            if (arrParam.get("image").toString().length() != 0) {
                genericFileUpload uploader = new genericFileUpload();
                uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath());
                if (uploader.isUploaded()) {
                    pstmt = null;
                    //                                        DbUtil.executeUpdate(conn,
                    //                                                        "update project set image=? where projectid = ?",
                    //                                                        new Object[] {
                    //                                                                        ProfileImageServlet.ImgBasePath + projectid
                    //                                                                                        + uploader.getExt(), projectid });

                    pstmt = conn.prepareStatement("update project set image=? where projectid = ?");
                    pstmt.setString(1,
                            ProfileImageServlet.ImgBasePath + projectid + "_200" + uploader.getExt());
                    pstmt.setString(2, projectid);
                    pstmt.executeUpdate();
                    imageName = projectid + uploader.getExt();
                }
            }
            com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain);
            status = "success";
            AdminServlet.setDefaultWorkWeek(conn, projectid);
            conn.commit();
        }
    } catch (ConfigurationException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    } catch (SQLException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    }
    return status;
}

From source file:forseti.JUploadFichero.java

@SuppressWarnings("rawtypes")
public boolean procesaFicheros(HttpServletRequest req, PrintWriter out) {
    try {// w w w . jav  a 2  s  .  c om
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();

        // maximo numero de bytes
        fu.setSizeMax(1024 * 512); // 512 K

        depura("Ponemos el tamao mximo");
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);

        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");

        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(req);

        if (fileItems == null) {
            depura("La lista es nula");
            return false;
        }

        // Iteramos por cada fichero

        Iterator i = fileItems.iterator();
        FileItem actual = null;
        depura("estamos en la iteracin");

        while ((actual = (FileItem) i.next()) != null) {
            String fileName = actual.getName();
            out.println("<br>Nos han subido el archivo: " + fileName);

            // construimos un objeto file para recuperar el trayecto completo
            File fichero = new File(fileName);
            depura("El nombre del fichero es " + fichero.getName());

            // nos quedamos solo con el nombre y descartamos el path
            fichero = new File("../tomcat/webapps/ROOT/forsetidoc/IMG/" + fichero.getName());

            // escribimos el fichero colgando del nuevo path
            actual.write(fichero);
        }

    } catch (Exception e) {
        if (e != null)
            depura("Error de Aplicacin " + e.getMessage());

        return false;
    }

    return true;
}

From source file:com.krawler.svnwebclient.util.Uploader.java

public void doPost(HttpServletRequest request, HttpServletResponse responce, String destinationDirectory,
        String tempDirectory) throws SessionExpiredException {
    File tempDir = new File(tempDirectory);
    String sep = StorageHandler.GetFileSeparator();
    if (!tempDir.exists()) {
        tempDir.mkdirs();//from  w  w w. j  a v  a2 s  .c o m
    }
    DiskFileUpload fu = new DiskFileUpload();
    // maximum size before a FileUploadException will be thrown
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(tempDirectory);
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        Logger.getInstance(Uploader.class).error(e, e);
    }
    String docid1 = null;
    String docownerid = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        try {
            if (fi1.getFieldName().toString().equals("docid")) {
                docid1 = new String(fi1.getString().getBytes(), "UTF8");
            }
            if (fi1.getFieldName().toString().equals("docownerid")) {
                docownerid = new String(fi1.getString().getBytes(), "UTF8");
            }
        } catch (UnsupportedEncodingException e) {
            // Logger.getInstance(Uploader.class).error(e, e);
        }
    }
    if (docid1.equals("")) {
        docid1 = UUID.randomUUID().toString();
        this.setFlagType(true);
        docownerid = AuthHandler.getUserid(request);
    } else {
        this.setFlagType(false);
    }
    try {
        if (docownerid.equalsIgnoreCase("my")) {
            docownerid = AuthHandler.getUserid(request);
        }
        destinationDirectory = com.krawler.esp.handlers.StorageHandler.GetDocStorePath() + sep + docownerid;
    } catch (ConfigurationException ex) {
        this.isUploaded = false;
        this.errorMessage = "Problem occurred while uploading file";
        return;
    }
    File destDir = new File(destinationDirectory);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    this.parameters.put("destinationDirectory", destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();

        /*
         * try{ String docid1 = fi.getString("docid"); }catch(Exception e){}
         */
        if (fi.isFormField()) {
            try {
                if (fi.getFieldName().toString().equals("docid")
                        && new String(fi.getString().getBytes(), "UTF8").equals("")) {
                    this.parameters.put(fi.getFieldName(), docid1);
                } else {
                    this.parameters.put(fi.getFieldName(), new String(fi.getString().getBytes(), "UTF8"));
                }
            } catch (UnsupportedEncodingException e) {
                Logger.getInstance(Uploader.class).error(e, e);
            }
        } else {
            // filename on the client
            String fileName = null;

            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                // org.tmatesoft.svn.core.internal.wc.SVNFileUtil.isExecutable(fi);
                String filext = "";
                if (fileName.contains("."))
                    filext = fileName.substring(fileName.lastIndexOf("."));

                if (fi.getSize() != 0) {
                    this.isUploaded = true;

                    // write the file
                    File uploadFile = new File(
                            destinationDirectory + sep + FileUtil.getLastPathElement(docid1 + filext));
                    fi.write(uploadFile);
                    this.parameters.put("svnName", uploadFile.getName());
                    if (filext.equals("")) {
                        this.parameters.put("fileExt", filext);
                    } else {
                        this.parameters.put("fileExt", filext.substring(1));
                    }
                } else {
                    this.isUploaded = false;
                    this.errorMessage = "Cannot upload a 0 byte file";
                }
            } catch (Exception e) {
                this.isUploaded = false;
                this.errorMessage = "Problem occurred while uploading file";
                Logger.getInstance(Uploader.class).error(e, e);
            }
            this.parameters.put(FormParameters.FILE_NAME, FileUtil.getLastPathElement(fileName));
        }
    }
}

From source file:com.krawler.esp.servlets.FileImporterServlet.java

public File getfile(HttpServletRequest request, String fileid) throws ServiceException {
    File uploadFile = null;//from  ww w . j a  v a  2 s  .  c  o m
    try {
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        File destdir = new File(destinationDirectory);
        if (!destdir.exists()) {
            destdir.mkdir();
        }
        DiskFileUpload fu = new DiskFileUpload();
        String Ext = "";
        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                String fileName = null;
                try {
                    fileName = new String(fi.getName().getBytes(), "UTF8");
                    if (fileName.contains(".")) {
                        Ext = fileName.substring(fileName.lastIndexOf("."));
                    }
                    long size = fi.getSize();
                    if (fi.getSize() != 0) {
                        String projid = request.getParameter("projectid");
                        uploadFile = new File(
                                destinationDirectory + StorageHandler.GetFileSeparator() + fileid + Ext);
                        fi.write(uploadFile);
                        fildoc(fileid, fileName, projid, fileid + Ext, AuthHandler.getUserid(request), size);

                    }
                } catch (IOException ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex.toString());
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                } catch (ServiceException ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex);
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                } catch (Exception ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex.toString());
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                }
            } else {
                arrParam.put(fi.getFieldName(), fi.getString());
            }
        }
    } catch (ConfigurationException ex) {
        KrawlerLog.op.warn("Problem Storing Data In DB [FileImporterServlet.storeInDB()]:" + ex);
        throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
    }
    return uploadFile;
}

From source file:forseti.JSubirArchivo.java

@SuppressWarnings("rawtypes")
public int processFiles(HttpServletRequest request, boolean onlyOne) // Request No debe contener parametros de formulario, sino solo los parmetro del archivo
{
    int numFiles = 0, thisFile = 0;

    try {/*from w w  w .j a  v  a  2 s  . co  m*/
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();
        // maximo numero de bytes
        fu.setSizeMax(1024 * m_MaxSize); // 512 K
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);
        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");
        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(request);
        if (fileItems == null) {
            m_Error += JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " null";
            return 0;
        }
        // Iteramos por cada fichero
        Iterator i = fileItems.iterator();
        FileItem actual = null;

        if (onlyOne) {
            actual = (FileItem) i.next();
            String fileName = actual.getName();
            // construimos un objeto file para recuperar el trayecto completo
            File file = new File(fileName);

            // Verifica que el archivo sea de la extension esperada
            for (int f = 0; f < m_Files.size(); f++) {
                String ext = "." + getExt(f).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                    break;
                }
            }

            if (numFiles == 0)
                m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName();

        } else {
            while ((actual = (FileItem) i.next()) != null) {
                String fileName = actual.getName();
                // construimos un objeto file para recuperar el trayecto completo
                File file = new File(fileName);
                String ext = "." + getExt(thisFile).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                // Verifica que el archivo sea de la extension esperada
                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                } else
                    m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - "
                            + ext;

                thisFile += 1;
            }
            System.out.println("Despues while");
        }
    } catch (Exception e) {
        if (e != null)
            m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage();
    }

    return numFiles;
}

From source file:de.jwi.jfm.servlets.Controller.java

private String handleUpload(HttpServletRequest request, Folder folder) throws Exception {
    DiskFileUpload upload = new DiskFileUpload();
    upload.setRepositoryPath(tempDir.toString());
    System.out.println(upload.getSizeMax());

    // parse this request by the handler
    // this gives us a list of items from the request
    List items = upload.parseRequest(request);

    Iterator itr = items.iterator();

    boolean unzip = false;

    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();

        // check if the current item is a form field or an uploaded file
        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            if ("command".equals(name) && "unzip".equals(value)) {
                unzip = true;//from  ww  w .  j  a  v  a 2s  .  com
            }
        } else {
            String name = item.getFieldName();
            unzip = "unzip".equals(name);

            if (!"".equals(item.getName())) {
                folder.upload(item, unzip);
            }
            // the item must be an uploaded file save it to disk. Note that
            // there
            // seems to be a bug in item.getName() as it returns the full
            // path on
            // the client's machine for the uploaded file name, instead of
            // the file
            // name only. To overcome that, I have used a workaround using
            // fullFile.getName().
            /*
             * File fullFile = new File(item.getName()); File savedFile =
             * new File(getServletContext().getRealPath("/"),
             */
            // item.write(savedFile);
        }
    }
    return "";
}

From source file:fsi_admin.JAwsS3Conn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/* ww w. jav  a  2  s  . c  o  m*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("ACTION") == null) {
            System.out.println("No recibi parametros de conexin antes del archivo");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD,ACTION) antes del archivo";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), S3BUKT = new StringBuffer(), S3USR = new StringBuffer(),
                    S3PASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del S3
            if (!obtenInfoAWSS3(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), S3BUKT, S3USR, S3PASS,
                    msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                AWSCredentials credentials = new BasicAWSCredentials(S3USR.toString(), S3PASS.toString());
                AmazonS3 s3 = new AmazonS3Client(credentials);
                Region usWest2 = Region.getRegion(Regions.US_WEST_2);
                s3.setRegion(usWest2);
                //System.out.println("AwsConn:" + parametros.getProperty("NOMBRE") + ":parametros.getProperty(NOMBRE)");
                String nombre = parametros.getProperty("SERVER") + parametros.getProperty("DATABASE")
                        + parametros.getProperty("ID_MODULO") + parametros.getProperty("OBJIDS")
                        + parametros.getProperty("IDSEP") + parametros.getProperty("NOMBRE");
                //System.out.println("AwsConn_Nombre:" + nombre + ":nombre");

                if (parametros.getProperty("ACTION").equals("SUBIR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    Double TAMBITES = new Double(Double.parseDouble(parametros.getProperty("TAMBITES")));

                    if (COBRAR.booleanValue() && SALDO
                            .doubleValue() < (COSTO.doubleValue() * (((TOTBITES + TAMBITES) / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de subida tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de subida tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!subirArchivo(msj, s3, S3BUKT.toString(), nombre, archivos)) {
                            System.out.println("No se permiti subir el archivo al s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"), parametros.getProperty("TAMBITES"));
                        }
                    }

                } else if (parametros.getProperty("ACTION").equals("ELIMINAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));

                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de borrado tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de borrado tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!eliminarArchivo(msj, s3, S3BUKT.toString(), nombre)) {
                            System.out.println("No se permiti eliminar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            eliminarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"));
                        }
                    }
                } else if (parametros.getProperty("ACTION").equals("DESCARGAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    //System.out.println("COBRAR: " + COBRAR.booleanValue() + " SALDO: " + SALDO.doubleValue() + " COSTO: " + COSTO.doubleValue() + " TOTBITES: " + TOTBITES + " TOTMB: " + ((TOTBITES / 1024) / 1024) + " RES: " + (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024)));
                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out.println(
                                "El servicio S3 de descarga tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de descarga tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!descargarArchivo(response, msj, s3, S3BUKT.toString(), nombre,
                                parametros.getProperty("NOMBRE"))) {
                            System.out.println("No se permiti descargar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else
                            return;
                    }
                }

                if (ERROR == null) {
                    //Devuelve la respuesta al cliente
                    Element S3 = new Element("S3");
                    S3.setAttribute("Archivo", nombre);
                    S3.setAttribute("MsjError", "");
                    Document Reporte = new Document(S3);

                    Format format = Format.getPrettyFormat();
                    format.setEncoding("utf-8");
                    format.setTextMode(TextMode.NORMALIZE);
                    XMLOutputter xmlOutputter = new XMLOutputter(format);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    xmlOutputter.output(Reporte, out);

                    byte[] data = out.toByteArray();
                    ByteArrayInputStream istream = new ByteArrayInputStream(data);

                    String destino = "Archivo.xml";
                    JBajarArchivo fd = new JBajarArchivo();
                    fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml",
                            data.length, destino);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR AWS S3: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }

}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run.//from   w ww . j  ava 2 s. c o  m
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException If the servlet fails
 * @throws IOException If there is an I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.

    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        File runTmp = unjarTmp(uploadFile);

        String runId = null;

        if (origin) {
            // Change origin file to know where this run came from.
            File metaInf = new File(runTmp, "META-INF");
            File originFile = new File(metaInf, "origin");
            if (!originFile.exists()) {
                logger.warning("Origin upload requested. Origin file" + "does not exist!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                break;
            }

            RunId origRun;
            try {
                origRun = new RunId(readStringFromFile(originFile).trim());
            } catch (IndexOutOfBoundsException e) {
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Origin file error. " + e.getMessage());
                break;
            }

            runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
            String localHost = origRun.getHostName();
            if (!localHost.equals(Config.FABAN_HOST)) {
                logger.warning("Origin upload requested. Origin host " + localHost
                        + " does not match this host " + Config.FABAN_HOST + '!');
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            writeStringToFile(runTmp.getName(), originFile);
        } else {
            runId = runTmp.getName();
        }

        if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) {
            uploadFile.delete();
            recursiveDelete(runTmp);
        } else {
            logger.warning("Origin upload requested. Copy error!");
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
            break;
        }

        response.setStatus(HttpServletResponse.SC_CREATED);
        break;
    }
}

From source file:fsi_admin.JSmtpConn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/* ww  w  .  j  a va2  s.c  o  m*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null
                || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null
                || parametros.getProperty("SOURCEMAIL") == null) {
            System.out.println("No recibi parametros de conexin antes del correo a enviar");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(),
                    SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del SMTP
            if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT,
                    SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) {
                    System.out.println("El servicio tiene un costo que no alcanza en el saldo");
                    ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo";
                    codErr = "2";
                    ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                            parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                            parametros.getProperty("PASSWORD"), request, ERROR, 2);

                } else {
                    Properties props;

                    props = System.getProperties();
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString()));

                    // Set properties indicating that we want to use STARTTLS to encrypt the connection.
                    // The SMTP session will begin on an unencrypted connection, and then the client
                    // will issue a STARTTLS command to upgrade to an encrypted connection.
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.starttls.enable", "true");
                    props.put("mail.smtp.starttls.required", "true");

                    // Create a Session object to represent a mail session with the specified properties. 
                    Session session = Session.getDefaultInstance(props);
                    MimeMessage mmsg = new MimeMessage(session);
                    BodyPart messagebodypart = new MimeBodyPart();
                    MimeMultipart multipart = new MimeMultipart();

                    if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"),
                            parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"),
                            parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart,
                            multipart)) {
                        System.out.println("No se permiti preparar el mensaje");
                        ERROR = msj.toString();
                        codErr = "3";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 3);

                    } else {
                        if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) {
                            System.out.println("No se permiti adjuntar archivos al mensaje");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);

                        } else {
                            if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj,
                                    session, mmsg, multipart)) {
                                System.out.println("No se permiti enviar el mensaje");
                                ERROR = msj.toString();
                                codErr = "3";
                                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                        parametros.getProperty("PASSWORD"), request, ERROR, 3);
                            } else {
                                ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                        parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"),
                                        COSTO, SALDO, COBRAR);

                                //Devuelve la respuesta al cliente
                                Element Correo = new Element("Correo");
                                Correo.setAttribute("Subject", parametros.getProperty("SUBJECT"));
                                Correo.setAttribute("MsjError", "");
                                Document Reporte = new Document(Correo);

                                Format format = Format.getPrettyFormat();
                                format.setEncoding("utf-8");
                                format.setTextMode(TextMode.NORMALIZE);
                                XMLOutputter xmlOutputter = new XMLOutputter(format);
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                xmlOutputter.output(Reporte, out);

                                byte[] data = out.toByteArray();
                                ByteArrayInputStream istream = new ByteArrayInputStream(data);

                                String destino = "Correo.xml";
                                JBajarArchivo fd = new JBajarArchivo();
                                fd.doDownload(response, getServletConfig().getServletContext(), istream,
                                        "text/xml", data.length, destino);

                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }
}