Search in sources :

Example 31 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload 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)

Example 32 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload 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 33 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project JessMA by ldcsaa.

the class FileUploader method getFileUploadComponent.

private ServletFileUpload getFileUploadComponent() {
    DiskFileItemFactory dif = new DiskFileItemFactory();
    if (factorySizeThreshold != DEFAULT_SIZE_THRESHOLD)
        dif.setSizeThreshold(factorySizeThreshold);
    if (factoryRepository != null)
        dif.setRepository(new File(factoryRepository));
    if (factoryCleaningTracker != null)
        dif.setFileCleaningTracker(factoryCleaningTracker);
    ServletFileUpload sfu = new ServletFileUpload(dif);
    if (sizeMax != NO_LIMIT_SIZE_MAX)
        sfu.setSizeMax(sizeMax);
    if (fileSizeMax != NO_LIMIT_FILE_SIZE_MAX)
        sfu.setFileSizeMax(fileSizeMax);
    if (servletHeaderencoding != null)
        sfu.setHeaderEncoding(servletHeaderencoding);
    if (servletProgressListener != null)
        sfu.setProgressListener(servletProgressListener);
    return sfu;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File)

Example 34 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project eweb4j-framework by laiweiwei.

the class UploadUtil method handleUpload.

public static void handleUpload(Context context) throws Exception {
    ConfigBean cb = (ConfigBean) SingleBeanCache.get(ConfigBean.class.getName());
    UploadConfigBean ucb = cb.getMvc().getUpload();
    String tmpDir = ucb.getTmp();
    int memoryMax = CommonUtil.strToInt(CommonUtil.parseFileSize(ucb.getMaxMemorySize()) + "");
    long sizeMax = CommonUtil.parseFileSize(ucb.getMaxRequestSize());
    if (tmpDir.trim().length() == 0)
        tmpDir = "${RootPath}" + File.separator + "WEB-INF" + File.separator + "tmp";
    tmpDir = tmpDir.replace("${RootPath}", ConfigConstant.ROOT_PATH);
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(memoryMax);
    factory.setRepository(new File(tmpDir));
    ServletFileUpload _upload = new ServletFileUpload(factory);
    if (!_upload.isMultipartContent(context.getRequest()))
        return;
    _upload.setSizeMax(sizeMax);
    try {
        List<FileItem> items = _upload.parseRequest(context.getRequest());
        Iterator<FileItem> it = items.iterator();
        while (it.hasNext()) {
            FileItem item = it.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                String value = item.getString();
                context.getQueryParamMap().put(fieldName, new String[] { value });
            } else {
                String fileName = item.getName();
                if (fileName == null || fileName.trim().length() == 0)
                    continue;
                String stamp = CommonUtil.getNowTime("yyyyMMddHHmmss");
                File tmpFile = new File(tmpDir + File.separator + stamp + "_" + fileName);
                item.write(tmpFile);
                UploadFile uploadFile = new UploadFile(tmpFile, fileName, fieldName, item.getSize(), item.getContentType());
                if (context.getUploadMap().containsKey(fieldName)) {
                    context.getUploadMap().get(fieldName).add(uploadFile);
                } else {
                    List<UploadFile> uploads = new ArrayList<UploadFile>();
                    uploads.add(uploadFile);
                    context.getUploadMap().put(fieldName, uploads);
                }
            }
        }
    } catch (InvalidContentTypeException e) {
        throw new Exception("upload file error", e);
    }
}
Also used : InvalidContentTypeException(org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException) ArrayList(java.util.ArrayList) UploadConfigBean(org.eweb4j.config.bean.UploadConfigBean) ConfigBean(org.eweb4j.config.bean.ConfigBean) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) InvalidContentTypeException(org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) UploadConfigBean(org.eweb4j.config.bean.UploadConfigBean)

Example 35 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project RESTdoclet by IG-Group.

the class FileUploadServlet method doPost.

/* (non-Javadoc)
    * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    * 
    * This method accepts a jar and extracts to a location specified by the header key RESTDOCLET_DEPLOY
    */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String deploySubDir = request.getHeader(RESTDOCLET_DEPLOY);
    String deployDir = configPath + File.separator + deploySubDir;
    File dir = new File(deployDir);
    deleteDir(dir);
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            LOG.info("Upload request to " + deployDir);
            List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory(1024 * 1024, dir)).parseRequest(request);
            for (FileItem item : fileItems) {
                if (item != null) {
                    LOG.debug(item.getName());
                    JarInputStream jis = new JarInputStream(item.getInputStream());
                    JarEntry jarEntry;
                    while ((jarEntry = jis.getNextJarEntry()) != null) {
                        extract(jis, jarEntry, deployDir);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to upload to " + configPath, e);
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JarInputStream(java.util.jar.JarInputStream) JarEntry(java.util.jar.JarEntry) File(java.io.File) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)50 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)36 FileItem (org.apache.commons.fileupload.FileItem)33 FileUploadException (org.apache.commons.fileupload.FileUploadException)22 File (java.io.File)20 ArrayList (java.util.ArrayList)15 IOException (java.io.IOException)14 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)11 InputStream (java.io.InputStream)10 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)9 FileItemStream (org.apache.commons.fileupload.FileItemStream)9 HashMap (java.util.HashMap)8 List (java.util.List)6 ServletException (javax.servlet.ServletException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 Locale (java.util.Locale)4 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)4 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)4 DataBinder (org.springframework.validation.DataBinder)4 Errors (org.springframework.validation.Errors)4