Search in sources :

Example 11 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project com-liferay-apio-architect by liferay.

the class MultipartBodyMessageBodyReader method readFrom.

@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
    if (!isMultipartContent(_httpServletRequest)) {
        throw new BadRequestException("Request body is not a valid multipart form");
    }
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    try {
        List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);
        Iterator<FileItem> iterator = fileItems.iterator();
        Map<String, String> values = new HashMap<>();
        Map<String, BinaryFile> binaryFiles = new HashMap<>();
        Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
        Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();
        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();
            String name = fileItem.getFieldName();
            Matcher matcher = _arrayPattern.matcher(name);
            if (matcher.matches()) {
                int index = Integer.parseInt(matcher.group(2));
                String actualName = matcher.group(1);
                _storeFileItem(fileItem, value -> {
                    Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName, __ -> new HashMap<>());
                    indexedMap.put(index, value);
                }, binaryFile -> {
                    Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName, __ -> new HashMap<>());
                    indexedMap.put(index, binaryFile);
                });
            } else {
                _storeFileItem(fileItem, value -> values.put(name, value), binaryFile -> binaryFiles.put(name, binaryFile));
            }
        }
        Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);
        Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);
        return Body.create(key -> Optional.ofNullable(values.get(key)), key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)), key -> Optional.ofNullable(binaryFiles.get(key)));
    } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {
        throw new BadRequestException("Request body is not a valid multipart form", e);
    }
}
Also used : HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ArrayList(java.util.ArrayList) List(java.util.List) BinaryFile(com.liferay.apio.architect.file.BinaryFile) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) BadRequestException(javax.ws.rs.BadRequestException) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 12 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project v7files by thiloplanz.

the class BucketsServlet method doFormPost.

private void doFormPost(HttpServletRequest request, HttpServletResponse response, BSONObject bucket) throws IOException {
    ObjectId uploadId = new ObjectId();
    BSONObject parameters = new BasicBSONObject();
    List<FileItem> files = new ArrayList<FileItem>();
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            for (Object _file : upload.parseRequest(request)) {
                FileItem file = (FileItem) _file;
                if (file.isFormField()) {
                    String v = file.getString();
                    parameters.put(file.getFieldName(), v);
                } else {
                    files.add(file);
                }
            }
        } catch (FileUploadException e) {
            throw new IOException(e);
        }
    } else {
        for (Entry<String, String[]> param : request.getParameterMap().entrySet()) {
            String[] v = param.getValue();
            if (v.length == 1)
                parameters.put(param.getKey(), v[0]);
            else
                parameters.put(param.getKey(), v);
        }
    }
    BSONObject result = new BasicBSONObject("_id", uploadId);
    BSONObject uploads = new BasicBSONObject();
    for (FileItem file : files) {
        DiskFileItem f = (DiskFileItem) file;
        // inline until 10KB
        if (f.isInMemory()) {
            uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.get(), uploadId, f.getName(), f.getContentType()));
        } else {
            uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.getStoreLocation(), uploadId, f.getName(), f.getContentType()));
        }
        file.delete();
    }
    result.put("files", uploads);
    result.put("parameters", parameters);
    bucketCollection.update(new BasicDBObject("_id", bucket.get("_id")), new BasicDBObject("$push", new BasicDBObject("FormPost.data", result)));
    String redirect = BSONUtils.getString(bucket, "FormPost.redirect");
    // redirect mode
    if (StringUtils.isNotBlank(redirect)) {
        response.sendRedirect(redirect + "?v7_formpost_id=" + uploadId);
        return;
    }
    // echo mode
    // JSON does not work, see https://jira.mongodb.org/browse/JAVA-332
    // response.setContentType("application/json");
    // response.getWriter().write(JSON.serialize(result));
    byte[] bson = BSON.encode(result);
    response.getOutputStream().write(bson);
}
Also used : ObjectId(org.bson.types.ObjectId) BasicBSONObject(org.bson.BasicBSONObject) BSONObject(org.bson.BSONObject) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) BasicBSONObject(org.bson.BasicBSONObject) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) BasicDBObject(com.mongodb.BasicDBObject) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BasicBSONObject(org.bson.BasicBSONObject) BasicDBObject(com.mongodb.BasicDBObject) BSONObject(org.bson.BSONObject) FileUploadException(org.apache.commons.fileupload.FileUploadException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 13 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project jaggery by wso2.

the class RequestHostObject method parseMultipart.

private static void parseMultipart(RequestHostObject rho) throws ScriptException {
    if (rho.files != null) {
        return;
    }
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;
    try {
        items = upload.parseRequest(rho.request);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        throw new ScriptException(e);
    }
    // Process the uploaded items
    String name;
    rho.files = rho.context.newObject(rho);
    for (Object obj : items) {
        FileItem item = (FileItem) obj;
        name = item.getFieldName();
        if (item.isFormField()) {
            ArrayList<FileItem> x = (ArrayList<FileItem>) rho.parameterMap.get(name);
            if (x == null) {
                ArrayList<FileItem> array = new ArrayList<FileItem>(1);
                array.add(item);
                rho.parameterMap.put(name, array);
            } else {
                x.add(item);
            }
        } else {
            rho.files.put(item.getFieldName(), rho.files, rho.context.newObject(rho, "File", new Object[] { item }));
        }
    }
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ScriptableObject(org.mozilla.javascript.ScriptableObject) LogHostObject(org.jaggeryjs.hostobjects.log.LogHostObject) 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 14 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project MassBank-web by MassBank.

the class AdminActions method doUpload.

@Action(name = "doUpload", post = true)
public Redirect doUpload(HttpServletRequest req) throws ServletException {
    RequestContext reqContext = new ServletRequestContext(req);
    boolean isMultipart = ServletFileUpload.isMultipartContent(reqContext);
    if (isMultipart) {
        try {
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(req);
            // Process the uploaded items
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String fileExtesion = fileName;
                    fileExtesion = fileExtesion.toLowerCase();
                    if (!(fileExtesion.endsWith(".jar") || fileExtesion.endsWith(".aar"))) {
                        return new Redirect(UPLOAD).withStatus(false, "Unsupported file type " + fileExtesion);
                    } else {
                        String fileNameOnly;
                        if (fileName.indexOf("\\") < 0) {
                            fileNameOnly = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
                        } else {
                            fileNameOnly = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
                        }
                        File uploadedFile = new File(serviceDir, fileNameOnly);
                        item.write(uploadedFile);
                        return new Redirect(UPLOAD).withStatus(true, "File " + fileNameOnly + " successfully uploaded");
                    }
                }
            }
        } catch (Exception e) {
            return new Redirect(UPLOAD).withStatus(false, "The following error occurred: " + e.getMessage());
        }
    }
    throw new ServletException("Invalid request");
}
Also used : ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File)

Example 15 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project zuul by Netflix.

the class FilterScriptManagerServlet method handlePostBody.

private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    org.apache.commons.fileupload.FileItemIterator it = null;
    try {
        it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream stream = it.next();
            InputStream input = stream.openStream();
            // NOTE: we are going to pull the entire stream into memory
            // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
            byte[] uploadedBytes = getBytesFromInputStream(input);
            input.close();
            if (uploadedBytes.length == 0) {
                setUsageError(400, "ERROR: Body contained no data.", response);
                return null;
            }
            return new String(uploadedBytes);
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
    return null;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) 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)

Aggregations

FileItemFactory (org.apache.commons.fileupload.FileItemFactory)27 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)27 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)24 FileItem (org.apache.commons.fileupload.FileItem)23 FileUploadException (org.apache.commons.fileupload.FileUploadException)16 HashMap (java.util.HashMap)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 JSONObject (org.json.JSONObject)6 ApplicationContext (org.springframework.context.ApplicationContext)6 File (java.io.File)5 InputStream (java.io.InputStream)5 ServletException (javax.servlet.ServletException)5 ILogEventService (org.cerberus.crud.service.ILogEventService)5 MessageEvent (org.cerberus.engine.entity.MessageEvent)5 Answer (org.cerberus.util.answer.Answer)5 Iterator (java.util.Iterator)4 AnswerItem (org.cerberus.util.answer.AnswerItem)4 BufferedReader (java.io.BufferedReader)3