Search in sources :

Example 81 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project data-access by pentaho.

the class UploadFileDebugServlet method getFileItem.

private FileItem getFileItem(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List items = upload.parseRequest(request);
        Iterator it = items.iterator();
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
                // $NON-NLS-1$
                return item;
            }
        }
    } catch (FileUploadException e) {
        return null;
    }
    return null;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 82 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project nimbus by nimbus-org.

the class HttpServletRequestFileConverter method convert.

public Object convert(Object obj) throws ConvertException {
    if (!(obj instanceof HttpServletRequest)) {
        throw new ConvertException("Parameter is not instancce of HttpServletRequest.");
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    if (repositoryPath != null) {
        factory.setRepository(new File(repositoryPath));
    }
    factory.setSizeThreshold(sizeThreshold);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(requestSizeThreshold);
    if (headerEncoding != null) {
        upload.setHeaderEncoding(headerEncoding);
    }
    try {
        return upload.parseRequest((HttpServletRequest) obj);
    } catch (FileUploadException e) {
        throw new ConvertException(e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 83 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project lobcder by skoulouzis.

the class WorkerServlet method doPost.

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(this.bufferSize);
        // sets temporary location to store files
        factory.setRepository(Util.getUploadDir());
        ServletFileUpload upload = new ServletFileUpload(factory);
        // sets maximum size of upload file
        // upload.setFileSizeMax(MAX_FILE_SIZE);
        // sets maximum size of request (include file + form data)
        // upload.setSizeMax(MAX_REQUEST_SIZE);
        Map<String, Triple<Long, Long, Collection<Long>>> storagMap = parseQuery(request.getQueryString());
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();
        FileItem item;
        // 
        while (iter.hasNext()) {
            item = iter.next();
            if (item.getName() == null) {
                continue;
            }
            String fileName = item.getName();
            Triple<Long, Long, Collection<Long>> triple = storagMap.get(fileName);
            StringBuilder storeName = new StringBuilder();
            storeName.append(triple.getLeft()).append("-");
            storeName.append(triple.getMiddle()).append("-");
            for (Long l : triple.getRight()) {
                storeName.append(l).append("-");
            }
            storeName.deleteCharAt(storeName.length() - 1);
            String filePath = Util.getUploadDir() + File.separator + fileName + "_" + storeName.toString();
            File storeFile = new File(filePath);
            item.write(storeFile);
        }
    } catch (Exception ex) {
        Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) JAXBException(javax.xml.bind.JAXBException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) VlException(nl.uva.vlet.exception.VlException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) MutableTriple(org.apache.commons.lang3.tuple.MutableTriple) Triple(org.apache.commons.lang3.tuple.Triple) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Collection(java.util.Collection) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 84 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ghostdriver by detro.

the class DirectFileUploadTest method checkFileUploadCompletes.

@Test
public void checkFileUploadCompletes() throws IOException {
    WebDriver d = getDriver();
    if (!(d instanceof PhantomJSDriver)) {
        // The command under test is only available when using PhantomJS
        return;
    }
    PhantomJSDriver phantom = (PhantomJSDriver) d;
    String buttonId = "upload";
    // Create the test file for uploading
    File testFile = File.createTempFile("webdriver", "tmp");
    testFile.deleteOnExit();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
    writer.write(FILE_HTML);
    writer.close();
    server.setHttpHandler("POST", new HttpRequestCallback() {

        @Override
        public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {
            if (ServletFileUpload.isMultipartContent(req) && req.getPathInfo().endsWith("/upload")) {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory(1024, new File(System.getProperty("java.io.tmpdir")));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List<FileItem> items;
                try {
                    items = upload.parseRequest(req);
                } catch (FileUploadException fue) {
                    throw new IOException(fue);
                }
                res.setHeader("Content-Type", "text/html; charset=UTF-8");
                InputStream is = items.get(0).getInputStream();
                OutputStream os = res.getOutputStream();
                IOUtils.copy(is, os);
                os.write("<script>window.top.window.onUploadDone();</script>".getBytes());
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                return;
            }
            res.sendError(400);
        }
    });
    // Upload the temp file
    phantom.get(server.getBaseUrl() + "/common/upload.html");
    phantom.executePhantomJS("var page = this; page.uploadFile('input#" + buttonId + "', '" + testFile.getAbsolutePath() + "');");
    phantom.findElement(By.id("go")).submit();
    // Uploading files across a network may take a while, even if they're really small.
    // Wait for the loading label to disappear.
    WebDriverWait wait = new WebDriverWait(phantom, 10);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));
    phantom.switchTo().frame("upload_target");
    wait = new WebDriverWait(phantom, 5);
    wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), LOREM_IPSUM_TEXT));
    // Navigate after file upload to verify callbacks are properly released.
    phantom.get("http://www.google.com/");
}
Also used : WebDriver(org.openqa.selenium.WebDriver) PhantomJSDriver(org.openqa.selenium.phantomjs.PhantomJSDriver) HttpRequestCallback(ghostdriver.server.HttpRequestCallback) HttpServletResponse(javax.servlet.http.HttpServletResponse) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException) Test(org.junit.Test)

Example 85 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ghostdriver by detro.

the class FileUploadTest method checkFileUploadCompletes.

@Test
public void checkFileUploadCompletes() throws IOException {
    WebDriver d = getDriver();
    // Create the test file for uploading
    File testFile = File.createTempFile("webdriver", "tmp");
    testFile.deleteOnExit();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
    writer.write(FILE_HTML);
    writer.close();
    server.setHttpHandler("POST", new HttpRequestCallback() {

        @Override
        public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {
            if (ServletFileUpload.isMultipartContent(req) && req.getPathInfo().endsWith("/upload")) {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory(1024, new File(System.getProperty("java.io.tmpdir")));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List<FileItem> items;
                try {
                    items = upload.parseRequest(req);
                } catch (FileUploadException fue) {
                    throw new IOException(fue);
                }
                res.setHeader("Content-Type", "text/html; charset=UTF-8");
                InputStream is = items.get(0).getInputStream();
                OutputStream os = res.getOutputStream();
                IOUtils.copy(is, os);
                os.write("<script>window.top.window.onUploadDone();</script>".getBytes());
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                return;
            }
            res.sendError(400);
        }
    });
    // Upload the temp file
    d.get(server.getBaseUrl() + "/common/upload.html");
    d.findElement(By.id("upload")).sendKeys(testFile.getAbsolutePath());
    d.findElement(By.id("go")).submit();
    // Uploading files across a network may take a while, even if they're really small.
    // Wait for the loading label to disappear.
    WebDriverWait wait = new WebDriverWait(d, 10);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));
    d.switchTo().frame("upload_target");
    wait = new WebDriverWait(d, 5);
    wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), LOREM_IPSUM_TEXT));
    // Navigate after file upload to verify callbacks are properly released.
    d.get("http://www.google.com/");
}
Also used : WebDriver(org.openqa.selenium.WebDriver) HttpRequestCallback(ghostdriver.server.HttpRequestCallback) HttpServletResponse(javax.servlet.http.HttpServletResponse) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException) Test(org.junit.Test)

Aggregations

DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)91 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)85 FileItem (org.apache.commons.fileupload.FileItem)73 FileUploadException (org.apache.commons.fileupload.FileUploadException)50 File (java.io.File)44 IOException (java.io.IOException)32 HashMap (java.util.HashMap)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)24 List (java.util.List)22 ArrayList (java.util.ArrayList)21 InputStream (java.io.InputStream)19 ServletException (javax.servlet.ServletException)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)9 Locale (java.util.Locale)8 JSONObject (org.json.JSONObject)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 Iterator (java.util.Iterator)7 Map (java.util.Map)7