Search in sources :

Example 16 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project sling by apache.

the class InstallServlet method installBasedOnUploadedJar.

private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    InstallationResult result = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // try to hold even largish bundles in memory to potentially improve performance
        factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD);
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        if (items.size() != 1) {
            logAndWriteError("Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp);
            return;
        }
        FileItem item = items.get(0);
        JarInputStream jar = null;
        InputStream rawInput = null;
        try {
            jar = new JarInputStream(item.getInputStream());
            Manifest manifest = jar.getManifest();
            if (manifest == null) {
                logAndWriteError("Uploaded jar file does not contain a manifest", resp);
                return;
            }
            final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
            if (symbolicName == null) {
                logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp);
                return;
            }
            final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
            // the JarInputStream is used only for validation, we need a fresh input stream for updating
            rawInput = item.getInputStream();
            Bundle found = getBundle(symbolicName);
            try {
                installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar");
                result = new InstallationResult(true, null);
                resp.setStatus(200);
                result.render(resp.getWriter());
                return;
            } catch (BundleException e) {
                logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp);
                return;
            }
        } finally {
            IOUtils.closeQuietly(jar);
            IOUtils.closeQuietly(rawInput);
        }
    } catch (FileUploadException e) {
        logAndWriteError("Failed parsing uploaded bundle", e, resp);
        return;
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) JarInputStream(java.util.jar.JarInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Bundle(org.osgi.framework.Bundle) Manifest(java.util.jar.Manifest) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BundleException(org.osgi.framework.BundleException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 17 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project tomee by apache.

the class CommonsFileUploadPartFactory method read.

public static Collection<Part> read(final HttpRequestImpl request) {
    // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);
    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                    // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }
        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 18 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project fess by codelibs.

the class FessMultipartRequestHandler method handleRequest.

// ===================================================================================
//                                                                      Handle Request
//                                                                      ==============
@Override
public void handleRequest(final HttpServletRequest request) throws ServletException {
    // /- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    // copied from super's method and extends it
    // basically for JVN#14876762
    // thought not all problems are resolved however the main case is safety
    // - - - - - - - - - -/
    final ServletFileUpload upload = createServletFileUpload(request);
    prepareElementsHash();
    try {
        final List<FileItem> items = parseRequest(request, upload);
        mappingParameter(request, items);
    } catch (final SizeLimitExceededException e) {
        handleSizeLimitExceededException(request, e);
    } catch (final FileUploadException e) {
        handleFileUploadException(e);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) SizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 19 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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 20 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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

FileUploadException (org.apache.commons.fileupload.FileUploadException)27 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)20 FileItem (org.apache.commons.fileupload.FileItem)16 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)14 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)8 File (java.io.File)5 InputStream (java.io.InputStream)5 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)5 FileItemStream (org.apache.commons.fileupload.FileItemStream)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)4 ServletException (javax.servlet.ServletException)3 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)3 HttpRequestCallback (ghostdriver.server.HttpRequestCallback)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2