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

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

Introduction

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

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:com.krawler.esp.portalmsg.forummsgcomm.java

public static void doPost(Connection conn, java.util.List fileItems, String postid,
        java.sql.Timestamp docdatemod, String userid, String sendefolderpostid) throws ServiceException {
    try {//from w ww.j  av  a2s.  c om
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "attachment";
        java.io.File destDir = new java.io.File(destinationDirectory);
        String Ext = "";
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        String fileid;
        long size;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        for (java.util.Iterator i = fileItems.iterator(); i.hasNext();) {
            org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) i.next();
            if (!fi.isFormField()) {
                String fileName = null;
                fileid = UUID.randomUUID().toString();
                try {
                    fileName = getFileName(fi);
                    //                        fileName = new String(fi.getName().getBytes(), "UTF8");
                    if (fileName.contains(".")) {
                        Ext = fileName.substring(fileName.lastIndexOf("."));
                    }
                    size = fi.getSize();
                    if (size != 0) {

                        File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                        fi.write(uploadFile);
                        fildoc(conn, fileid, fileName, docdatemod, postid, fileid + Ext, userid, size,
                                sendefolderpostid);
                    }

                } catch (Exception e) {
                    throw ServiceException.FAILURE("ProfileHandler.updateProfile", e);
                }
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(forummsgcomm.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.w4t.engine.requests.FileUploadRequest.java

public FileUploadRequest(final HttpServletRequest request) throws ServletException {
    super(request);
    IConfiguration configuration = ConfigurationReader.getConfiguration();
    IFileUpload fileUpload = configuration.getFileUpload();
    UploadRequestFileItemFactory factory = new UploadRequestFileItemFactory();
    DiskFileUpload upload = new DiskFileUpload(factory);
    upload.setSizeThreshold(fileUpload.getMaxMemorySize());
    upload.setSizeMax(fileUpload.getMaxMemorySize());
    upload.setRepositoryPath(FileUploadRequest.SYSTEM_TEMP_DIR);
    try {/*from w  ww  . j a va  2 s  . c  o  m*/
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            parameters.put(item.getFieldName(), item);
        }

    } catch (FileUploadException e) {
        throw new ServletExceptionAdapter(e);
    }
}

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

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {/*from w w w .  j  a va  2  s.co  m*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPost(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*from   ww w  .  jav a  2s.c o m*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    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("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + filename + Ext);
                    fi.write(uploadFile);
                    imgResize(destinationDirectory + "/" + filename + Ext, 100, 100,
                            destinationDirectory + "/" + filename + "_100");
                    imgResize(destinationDirectory + "/" + filename + Ext, 35, 35,
                            destinationDirectory + "/" + filename);

                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPostCompay(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*  w  w  w .  j  a  v a2  s.c  om*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    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("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + "temp_" + filename + Ext);
                    fi.write(uploadFile);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 0, 0,
                            destinationDirectory + "/original_" + filename, true);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 130, 25,
                            destinationDirectory + "/" + filename, false);
                    //                  imgResize(destinationDirectory + "/" + filename + Ext,
                    //                        0, 0, destinationDirectory + "/original_" + filename);
                    uploadFile.delete();
                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                this.ErrorMsg = "Problem occured while uploading logo";
                logger.warn(e.getMessage(), e);
            }
        }
    }
}

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);/*from   w ww. java2s  . co  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:forseti.JUploadFichero.java

@SuppressWarnings("rawtypes")
public boolean procesaFicheros(HttpServletRequest req, PrintWriter out) {
    try {//from w ww .  j  ava2s  .  c o  m
        // 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 ww  w.  java 2 s  . c om*/
    }
    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: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 {/*www  . j  a  v a 2  s.com*/
        // 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:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run./*from w w  w. ja va 2  s . co 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;
    }
}