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.servlets.ExportImportContactsServlet.java

public static String uploadDocument(HttpServletRequest request, String fileid, String userId)
        throws ServiceException {
    String result = "";
    try {//from   w ww.  j  a v a 2 s.  c o m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importcontacts" + StorageHandler.GetFileSeparator() + userId;
        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("ExportImportContactServlet.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    }
    return result;
}

From source file:com.meikai.common.web.servlet.FCKeditorConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * //w  ww  .  j  av  a2s.  co  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 Connector DOPOST ---");

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

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

    // edit check user uploader file size
    int contextLength = request.getContentLength();
    int fileSize = (int) (((float) contextLength) / ((float) (1024)));
    PrintWriter out = response.getWriter();

    if (fileSize < 30240) {

        String commandStr = request.getParameter("Command");
        String typeStr = request.getParameter("Type");
        String currentFolderStr = request.getParameter("CurrentFolder");
        String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/"
                + dateCreated.substring(5) + currentFolderStr;
        // create user dir
        makeDirectory(getServletContext().getRealPath("/"), currentPath);
        String currentDirPath = getServletContext().getRealPath(currentPath);
        // edit end ++++++++++++++++

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

        if (!commandStr.equals("FileUpload"))
            retVal = "203";
        else {
            DiskFileUpload upload = new DiskFileUpload();

            try {

                upload.setSizeMax(1 * 1024 * 1024); // ??,??: 
                upload.setSizeThreshold(4096); // ???,??: 
                upload.setRepositoryPath("c:/temp/"); // ?getSizeThreshold()? 
                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);
                if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) {
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                        retVal = "201";
                        pathToSave = new File(currentDirPath, newName);
                        counter++;
                    }
                    uplFile.write(pathToSave);
                    // ?
                    if (logger.isInfoEnabled()) {
                        logger.info("...");
                    }
                } else {
                    retVal = "202";
                    if (debug)
                        System.out.println("Invalid file type: " + ext);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                retVal = "203";
            }
        }
    } else {
        retVal = "204";
    }
    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.sun.faban.harness.webclient.Uploader.java

/**
 * Responsible for uploading the runs./*from  w w  w .  j  ava 2  s .  c  om*/
 * @param request
 * @param response
 * @return String
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @throws java.lang.ClassNotFoundException
 */
public String uploadRuns(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException, ClassNotFoundException {
    // 3. Upload the run
    HashSet<String> duplicateSet = new HashSet<String>();
    HashSet<String> replaceSet = new HashSet<String>();
    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 ("replace".equals(fieldName)) {
                replaceSet.add(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);
        }
        int runIdx = fileName.lastIndexOf(".");
        String runName = host + '.' + fileName.substring(0, runIdx);
        File runTmp = unjarTmp(uploadFile);
        //Check if archived recently
        if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) {
            //Now check if timestamps are same
            //Get the timestamp of run being uploaded at this point
            //ts is timestamp of run being uploaded
            String ts = getRunIdTimestamp(runName, Config.TMP_DIR);
            l1: while (true) {
                //reposTs is timestamp of run being compared in the
                //repository
                String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR);
                if (reposTs.equals(ts)) {
                    duplicateSet.add(fileName.substring(0, runIdx));
                } else {
                    runName = getNextRunId(runName);
                    if (checkIfArchived(runName))
                        continue l1;
                    File newRunNameFile = new File(Config.OUT_DIR, runName);
                    if (newRunNameFile.exists()) {
                        recursiveDelete(newRunNameFile);
                    }
                    if (recursiveCopy(runTmp, newRunNameFile)) {
                        newRunNameFile.setLastModified(runTmp.lastModified());
                        uploadTags(runName);
                        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;
            }
        } else {
            //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();
            }
            File newRunFile = new File(Config.OUT_DIR, runId);
            if (newRunFile.exists()) {
                recursiveDelete(newRunFile);
            }
            if (recursiveCopy(runTmp, newRunFile)) {
                newRunFile.setLastModified(runTmp.lastModified());
                uploadFile.delete();
                uploadTags(runId);
                recursiveDelete(runTmp);
            } else {
                logger.warning("Origin upload requested. Copy error!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
                break;
            }
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
        //break;
    }
    request.setAttribute("duplicates", duplicateSet);
    return "/duplicates.jsp";
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from  w  w  w . j  a v  a2 s .c  o m
        List<String> deployNames = new ArrayList<String>();
        List<String> cantDeployNames = new ArrayList<String>();
        List<String> errDeployNames = new ArrayList<String>();
        List<String> invalidNames = new ArrayList<String>();
        List<String> errHeaders = new ArrayList<String>();
        List<String> errDetails = new ArrayList<String>();

        String user = null;
        String password = null;
        boolean clearConfig = false;
        boolean hasPermission = true;

        // Check whether we have to return text or html
        boolean acceptHtml = false;
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0)
            acceptHtml = true;

        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);

        StringWriter messageBuffer = new StringWriter();
        PrintWriter messageWriter = new PrintWriter(messageBuffer);

        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 ("user".equals(fieldName)) {
                    user = item.getString();
                } else if ("password".equals(fieldName)) {
                    password = item.getString();
                } else if ("clearconfig".equals(fieldName)) {
                    String value = item.getString();
                    clearConfig = Boolean.parseBoolean(value);
                }
                continue;
            }

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

            String fileName = item.getName();

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

            if (Config.SECURITY_ENABLED) {
                if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0
                        || !Config.DEPLOY_USER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0
                        || !Config.DEPLOY_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }
            // 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")) {
                invalidNames.add(fileName);
                continue;
            }

            String deployName = fileName.substring(0, fileName.length() - 4);

            if (deployName.indexOf('.') > -1) {
                invalidNames.add(deployName);
                continue;
            }

            // Check if we can deploy benchmark or service.
            // If running or queued, we won't deploy benchmark.
            // If service being used by current run,we won't deploy service.
            if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) {
                cantDeployNames.add(deployName);
                continue;
            }

            File uploadFile = new File(Config.BENCHMARK_DIR, fileName);
            if (uploadFile.exists())
                FileHelper.recursiveDelete(uploadFile);

            try {
                item.write(uploadFile);
            } catch (Exception e) {
                throw new ServletException(e);
            }

            try {
                DeployUtil.processUploadedJar(uploadFile, deployName);
            } catch (Exception e) {
                messageWriter.println("\nError deploying " + deployName + ".\n");
                e.printStackTrace(messageWriter);
                errDeployNames.add(deployName);
                continue;
            }
            deployNames.add(deployName);
        }

        if (clearConfig)
            for (String benchName : deployNames)
                DeployUtil.clearConfig(benchName);

        if (!hasPermission)
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        else if (cantDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        else if (errDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (invalidNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (deployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CREATED);
        else
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        StringBuilder b = new StringBuilder();

        if (deployNames.size() > 0) {
            if (deployNames.size() > 1)
                b.append("Benchmarks/services ");
            else
                b.append("Benchmark/service ");

            for (int i = 0; i < deployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) deployNames.get(i));
            }

            b.append(" deployed.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (invalidNames.size() > 0) {
            if (invalidNames.size() > 1)
                b.append("Invalid deploy files ");
            else
                b.append("Invalid deploy file ");
            for (int i = 0; i < invalidNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) invalidNames.get(i));
            }
            b.append(". Deploy files must have .jar extension.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (cantDeployNames.size() > 0) {
            if (cantDeployNames.size() > 1)
                b.append("Cannot deploy benchmarks/services ");
            else
                b.append("Cannot deploy benchmark/services ");
            for (int i = 0; i < cantDeployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) cantDeployNames.get(i));
            }
            b.append(". Benchmark/services being used or " + "queued up for run.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (errDeployNames.size() > 0) {
            if (errDeployNames.size() > 1) {
                b.append("Error deploying benchmarks/services ");
                for (int i = 0; i < errDeployNames.size(); i++) {
                    if (i > 0)
                        b.append(", ");
                    b.append((String) errDeployNames.get(i));
                }
            }

            errDetails.add(messageBuffer.toString());
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (!hasPermission)
            errHeaders.add("Permission denied!");

        Writer writer = response.getWriter();
        if (acceptHtml)
            writeHtml(request, writer, errHeaders, errDetails);
        else
            writeText(writer, errHeaders, errDetails);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:easyJ.http.upload.CommonsMultipartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items are
 * translated from Commons FileUpload <code>FileItem</code> instances to
 * Struts <code>FormFile</code> instances.
 * /*  w w w. jav  a  2s  .c o m*/
 * @param request
 *                The multipart request to be processed.
 * @throws ServletException
 *                 if an unrecoverable error occurs.
 */
public void handleRequest(HttpServletRequest request) throws ServletException {

    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // Create and configure a DIskFileUpload instance.
    DiskFileUpload upload = new DiskFileUpload();
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax((int) getSizeMax(ac));
    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold(ac));
    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(ac));

    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        EasyJLog.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

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

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//from  w ww  .j av a2s  .  c om
        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(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

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

private void doSubmit(String[] reqC, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (reqC.length < 3) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Benchmark and profile not provided in request.");
        return;//from   ww  w. ja  va 2 s. c  o  m
    }
    // first is the bench name
    BenchmarkDescription desc = BenchmarkDescription.getDescription(reqC[1]);
    if (desc == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark " + reqC[1] + " not deployed.");
        return;
    }
    try {
        String user = null;
        String password = null;
        boolean hasPermission = true;

        ArrayList<String> runIdList = new ArrayList<String>();

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

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("sun".equals(fieldName)) {
                    user = item.getString();
                } else if ("sp".equals(fieldName)) {
                    password = item.getString();
                }
                continue;
            }
            if (reqC[2] == null) // No profile
                break;

            if (desc == null)
                break;

            if (!"configfile".equals(fieldName))
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0
                        || !Config.CLI_SUBMITTER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0
                        || !Config.SUBMIT_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }

            String usrDir = Config.PROFILES_DIR + reqC[2];
            File dir = new File(usrDir);
            if (dir.exists()) {
                if (!dir.isDirectory()) {
                    logger.severe(usrDir + " should be a directory");
                    dir.delete();
                    logger.fine(dir + " deleted");
                } else
                    logger.fine("Saving parameter file to" + usrDir);
            } else {
                logger.fine("Creating new profile directory for " + reqC[2]);
                if (dir.mkdirs())
                    logger.fine("Created new profile directory " + usrDir);
                else
                    logger.severe("Failed to create profile " + "directory " + usrDir);
            }

            // Save the latest config file into the profile directory
            String dstFile = Config.PROFILES_DIR + reqC[2] + File.separator + desc.configFileName + "."
                    + desc.shortName;

            item.write(new File(dstFile));
            runIdList.add(RunQ.getHandle().addRun(user, reqC[2], desc));
        }

        response.setContentType("text/plain");
        Writer writer = response.getWriter();

        if (!hasPermission) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            writer.write("Permission denied!\n");
        }

        if (runIdList.size() == 0)
            writer.write("No runs submitted.\n");
        for (String newRunId : runIdList) {
            writer.write(newRunId);
        }

        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param request/*from  w  w  w. j a  v a  2 s. c  o m*/
 * @param fileid
 * @return
 * @throws ServiceException
 */
private static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "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("UTF-8"));
            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) {
                int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0;
                fileName = fileName.substring(startIndex, fileName.lastIndexOf("."));
                fileName = fileName.replaceAll(" ", "");
                fileName = fileName.replaceAll("/", "");
                result = fileName + "_" + fileid + Ext;

                File uploadFile = new File(destinationDirectory + "/" + result);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);

            }
        }

    }
    //        catch (ConfigurationException ex) {
    //            Logger.getLogger(ExportImportContacts.class.getName()).log(Level.SEVERE, null, ex);
    //            throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex);
    //        }
    catch (Exception ex) {
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex);
    }
    return result;
}

From source file:forseti.JUtil.java

@SuppressWarnings("rawtypes")
public static synchronized boolean procesaFicheros(HttpServletRequest req, String dir) {
    boolean res = true;

    try {//from   www .ja  v  a2  s. co  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

        //System.out.println("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) {
            //System.out.println("La lista es nula");
            return false;
        }

        //System.out.println("El nmero de ficheros subidos es: " +  fileItems.size());

        // Iteramos por cada fichero

        Iterator i = fileItems.iterator();
        FileItem actual = null;
        //System.out.println("estamos en la iteracin");

        while (i.hasNext()) {
            actual = (FileItem) i.next();
            String fileName = actual.getName();
            //System.out.println("Nos han subido el fichero" + fileName);

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

            // nos quedamos solo con el nombre y descartamos el path
            fichero = new File(dir + fichero.getName());

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

    } catch (Exception e) {
        System.out.println("Error de Fichero: " + e.getMessage());
        res = false;
    }

    return res;
}

From source file:nextapp.echo2.webcontainer.filetransfer.JakartaCommonsFileUploadProvider.java

/**
 * @see nextapp.echo2.webcontainer.filetransfer.MultipartUploadSPI#updateComponent(nextapp.echo2.webrender.Connection,
 *      nextapp.echo2.app.filetransfer.UploadSelect)
 *//*  w w  w  .ja  v  a 2  s  .  co m*/
public void updateComponent(Connection conn, UploadSelect uploadSelect) throws IOException, ServletException {

    DiskFileUpload handler = null;
    HttpServletRequest request = null;
    List items = null;
    Iterator it = null;
    FileItem item = null;
    boolean searching = true;
    InputStream in = null;
    int size = 0;
    String contentType = null;
    String name = null;

    try {
        handler = new DiskFileUpload();
        handler.setSizeMax(getFileUploadSizeLimit());
        handler.setSizeThreshold(getMemoryCacheThreshold());
        handler.setRepositoryPath(getDiskCacheLocation().getCanonicalPath());

        request = conn.getRequest();
        items = handler.parseRequest(request);

        searching = true;
        it = items.iterator();
        while (it.hasNext() && searching) {
            item = (FileItem) it.next();
            if (UploadFormService.FILE_PARAMETER_NAME.equals(item.getFieldName())) {
                in = item.getInputStream();
                size = (int) item.getSize();
                contentType = item.getContentType();
                name = item.getName();

                File tempFile = writeTempFile(in, uploadSelect);
                UploadEvent uploadEvent = new UploadEvent(tempFile, size, contentType, name);
                UploadSelectPeer.activateUploadSelect(uploadSelect, uploadEvent);

                searching = false;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
}