Search in sources :

Example 86 with DiskFileItemFactory

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

the class ServletUtils method handleFileUploads.

// TODO: seriously, javadoc the piece handleFileUploads method
/**
 * @param modelManager
 * @param request
 * @param map
 * @return
 * @throws FileUploadException
 */
public static final Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix, HttpServletRequest request, Map<Object, Object> map) throws FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(fileStoragePrefix));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileUploadSize);
    List fileItems = upload.parseRequest(request);
    for (FileItem item : (List<FileItem>) fileItems) {
        // we'll put this in the parameter map,
        // assuming the backing that is looking for it
        // knows what to expect
        String fieldName = item.getFieldName();
        Boolean isFormField = item.isFormField();
        Long size = item.getSize();
        if (isFormField) {
            if (size > 0) {
                map.put(fieldName, new String[] { item.getString() });
            }
        } else if (!isFormField) {
            map.put(fieldName, item);
        }
    }
    return true;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File)

Example 87 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project MSEC by Tencent.

the class FileUploadTool method FileUpload.

// 处理multi-part格式的http请求
// 将key-value字段放到fields里返回
// 将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
public static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);
    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");
    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                // 普通的k -v字段
                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName;
                System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }
        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 88 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project Axe by DongyuCai.

the class FormRequestHelper method init.

/**
 * 初始化
 */
public static void init(ServletContext servletContext) throws Exception {
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    servletFileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    int uploadLimit = ConfigHelper.getAppUploadLimit();
    if (uploadLimit > 0) {
        servletFileUpload.setFileSizeMax(uploadLimit * 1024 * 1024);
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory)

Example 89 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project jwt by emweb.

the class WebRequest method parse.

@SuppressWarnings({ "unchecked", "deprecation" })
private void parse(final ProgressListener progressUpdate) throws IOException {
    if (FileUploadBase.isMultipartContent(this)) {
        try {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            if (progressUpdate != null) {
                upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() {

                    public void update(long pBytesRead, long pContentLength, int pItems) {
                        progressUpdate.update(WebRequest.this, pBytesRead, pContentLength);
                    }
                });
            }
            // Parse the request
            List items = upload.parseRequest(this);
            parseParameters();
            Iterator itr = items.iterator();
            FileItem fi;
            File f = null;
            while (itr.hasNext()) {
                fi = (FileItem) itr.next();
                // else condition handles the submit button input
                if (!fi.isFormField()) {
                    try {
                        f = File.createTempFile("jwt", "jwt");
                        fi.write(f);
                        fi.delete();
                    } catch (IOException e) {
                        logger.error("IOException creating temp file {}", f.getAbsolutePath(), e);
                    } catch (Exception e) {
                        logger.error("Exception creating temp file {}", f.getAbsolutePath(), e);
                    }
                    List<UploadedFile> files = files_.get(fi.getFieldName());
                    if (files == null) {
                        files = new ArrayList<UploadedFile>();
                        files_.put(fi.getFieldName(), files);
                    }
                    files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType()));
                } else {
                    String[] v = parameters_.get(fi.getFieldName());
                    if (v == null)
                        v = new String[1];
                    else {
                        String[] newv = new String[v.length + 1];
                        for (int i = 0; i < v.length; ++i) newv[i] = v[i];
                        v = newv;
                    }
                    v[v.length - 1] = fi.getString();
                    parameters_.put(fi.getFieldName(), v);
                }
            }
        } catch (FileUploadException e) {
            logger.info("FileUploadException", e);
        }
    } else
        parseParameters();
}
Also used : IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 90 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project iaf by ibissource.

the class RestServiceDispatcher method dispatchRequest.

/**
 * Dispatch a request.
 * @param uri the name of the IReceiver object
 * @param request the <code>String</code> with the request/input
 * @return String with the result of processing the <code>request</code> through the <code>serviceName</code>
 */
public String dispatchRequest(String restPath, String uri, HttpServletRequest httpServletRequest, String contentType, String request, PipeLineSession context, HttpServletResponse httpServletResponse, ServletContext servletContext) throws ListenerException {
    String method = httpServletRequest.getMethod();
    if (log.isTraceEnabled())
        log.trace("searching listener for uri [" + uri + "] method [" + method + "]");
    String matchingPattern = findMatchingPattern(uri);
    if (matchingPattern == null) {
        throw new ListenerException("no REST listener configured for uri [" + uri + "]");
    }
    Map<String, Object> methodConfig = getMethodConfig(matchingPattern, method);
    if (methodConfig == null) {
        throw new ListenerException("No REST listener specified for uri [" + uri + "] method [" + method + "]");
    }
    context.put("restPath", restPath);
    context.put("uri", uri);
    context.put("method", method);
    String etag = null;
    String ifNoneMatch = httpServletRequest.getHeader("If-None-Match");
    if (ifNoneMatch != null && !ifNoneMatch.isEmpty()) {
        context.put("if-none-match", ifNoneMatch);
        etag = ifNoneMatch;
    }
    String ifMatch = httpServletRequest.getHeader("If-Match");
    if (ifMatch != null && !ifMatch.isEmpty()) {
        context.put("if-match", ifMatch);
        etag = ifMatch;
    }
    context.put("contentType", contentType);
    context.put("userAgent", httpServletRequest.getHeader("User-Agent"));
    ServiceClient listener = (ServiceClient) methodConfig.get(KEY_LISTENER);
    String etagKey = (String) methodConfig.get(KEY_ETAG_KEY);
    String contentTypeKey = (String) methodConfig.get(KEY_CONTENT_TYPE_KEY);
    Principal principal = null;
    if (httpServletRequest != null) {
        principal = httpServletRequest.getUserPrincipal();
        if (principal != null) {
            context.put("principal", principal.getName());
        }
    }
    String ctName = Thread.currentThread().getName();
    try {
        boolean writeToSecLog = false;
        if (listener instanceof RestListener) {
            RestListener restListener = (RestListener) listener;
            if (restListener.isRetrieveMultipart()) {
                if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
                    try {
                        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
                        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                        List<FileItem> items = servletFileUpload.parseRequest(httpServletRequest);
                        for (FileItem item : items) {
                            if (item.isFormField()) {
                                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                                String fieldName = item.getFieldName();
                                String fieldValue = item.getString();
                                log.trace("setting parameter [" + fieldName + "] to [" + fieldValue + "]");
                                context.put(fieldName, fieldValue);
                            } else {
                                // Process form file field (input type="file").
                                String fieldName = item.getFieldName();
                                String fieldNameName = fieldName + "Name";
                                String fileName = FilenameUtils.getName(item.getName());
                                if (log.isTraceEnabled())
                                    log.trace("setting parameter [" + fieldNameName + "] to [" + fileName + "]");
                                context.put(fieldNameName, fileName);
                                InputStream inputStream = item.getInputStream();
                                if (inputStream.available() > 0) {
                                    log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                                    context.put(fieldName, inputStream);
                                } else {
                                    log.trace("setting parameter [" + fieldName + "] to [" + null + "]");
                                    context.put(fieldName, null);
                                }
                            }
                        }
                    } catch (FileUploadException e) {
                        throw new ListenerException(e);
                    } catch (IOException e) {
                        throw new ListenerException(e);
                    }
                }
            }
            writeToSecLog = restListener.isWriteToSecLog();
            if (writeToSecLog) {
                context.put("writeSecLogMessage", restListener.isWriteSecLogMessage());
            }
            boolean authorized = false;
            if (principal == null) {
                authorized = true;
            } else {
                String authRoles = restListener.getAuthRoles();
                if (StringUtils.isNotEmpty(authRoles)) {
                    StringTokenizer st = new StringTokenizer(authRoles, ",;");
                    while (st.hasMoreTokens()) {
                        String authRole = st.nextToken();
                        if (httpServletRequest.isUserInRole(authRole)) {
                            authorized = true;
                        }
                    }
                }
            }
            if (!authorized) {
                throw new ListenerException("Not allowed for uri [" + uri + "]");
            }
            Thread.currentThread().setName(restListener.getName() + "[" + ctName + "]");
        }
        if (etagKey != null)
            context.put(etagKey, etag);
        if (contentTypeKey != null)
            context.put(contentTypeKey, contentType);
        if (log.isTraceEnabled())
            log.trace("dispatching request, uri [" + uri + "] listener pattern [" + matchingPattern + "] method [" + method + "] etag [" + etag + "] contentType [" + contentType + "]");
        if (httpServletRequest != null)
            context.put(PipeLineSession.HTTP_REQUEST_KEY, httpServletRequest);
        if (httpServletResponse != null)
            context.put(PipeLineSession.HTTP_RESPONSE_KEY, httpServletResponse);
        if (servletContext != null)
            context.put(PipeLineSession.SERVLET_CONTEXT_KEY, servletContext);
        if (writeToSecLog) {
            secLog.info(HttpUtils.getExtendedCommandIssuedBy(httpServletRequest));
        }
        // Caching: check for etags
        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.indexOf("?") > -1) {
            uri = uri.split("\\?")[0];
        }
        String etagCacheKey = restPath + "_" + uri;
        if (cache != null && cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            if (ifNoneMatch != null && ifNoneMatch.equalsIgnoreCase(cachedEtag) && method.equalsIgnoreCase("GET")) {
                // Exit with 304
                context.put("exitcode", 304);
                if (log.isDebugEnabled())
                    log.trace("aborting request with status 304, matched if-none-match [" + ifNoneMatch + "]");
                return null;
            }
            if (ifMatch != null && !ifMatch.equalsIgnoreCase(cachedEtag) && !method.equalsIgnoreCase("GET")) {
                // Exit with 412
                context.put("exitcode", 412);
                if (log.isDebugEnabled())
                    log.trace("aborting request with status 412, matched if-match [" + ifMatch + "] method [" + method + "]");
                return null;
            }
        }
        String result;
        try {
            result = listener.processRequest(null, new Message(request), context).asString();
        } catch (IOException e) {
            throw new ListenerException(e);
        }
        // Caching: pipeline has been processed, save etag
        if (result != null && cache != null && context.containsKey("etag")) {
            // In case the eTag has manually been set and the pipeline exited in error state...
            cache.put(etagCacheKey, context.get("etag"));
        }
        if (result == null && !context.containsKey("exitcode")) {
            log.warn("result is null!");
        }
        return result;
    } finally {
        if (listener instanceof RestListener) {
            Thread.currentThread().setName(ctName);
        }
    }
}
Also used : Message(nl.nn.adapterframework.stream.Message) InputStream(java.io.InputStream) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ListenerException(nl.nn.adapterframework.core.ListenerException) StringTokenizer(java.util.StringTokenizer) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServiceClient(nl.nn.adapterframework.receivers.ServiceClient) Principal(java.security.Principal) FileUploadException(org.apache.commons.fileupload.FileUploadException)

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