Search in sources :

Example 46 with FileItem

use of org.apache.commons.fileupload.FileItem in project ofbiz-framework by apache.

the class UploadContentAndImage method uploadContentAndImage.

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {
        Locale locale = UtilHttp.getLocale(request);
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        List<FileItem> lst = null;
        try {
            lst = UtilGenerics.checkList(dfu.parseRequest(request));
        } catch (FileUploadException e4) {
            request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
            Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
            return "error";
        }
        if (lst.size() == 0) {
            String errMsg = UtilProperties.getMessage(UploadContentAndImage.err_resource, "uploadContentAndImage.no_files_uploaded", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
            return "error";
        }
        Map<String, Object> passedParams = new HashMap<String, Object>();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes = {};
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                String fieldStr = fi.getString();
                passedParams.put(fieldName, fieldStr);
            } else if ("imageData".equals(fieldName)) {
                imageFi = fi;
                imageBytes = imageFi.get();
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }
        TransactionUtil.begin();
        List<String> contentPurposeList = ContentWorker.prepContentPurposeList(passedParams);
        passedParams.put("contentPurposeList", contentPurposeList);
        String entityOperation = (String) passedParams.get("entityOperation");
        String passedContentId = (String) passedParams.get("ftlContentId");
        List<String> targetOperationList = ContentWorker.prepTargetOperationList(passedParams, entityOperation);
        passedParams.put("targetOperationList", targetOperationList);
        // Create or update FTL template
        Map<String, Object> ftlContext = new HashMap<String, Object>();
        ftlContext.put("userLogin", userLogin);
        ftlContext.put("contentId", passedParams.get("ftlContentId"));
        ftlContext.put("ownerContentId", passedParams.get("ownerContentId"));
        String contentTypeId = (String) passedParams.get("contentTypeId");
        ftlContext.put("contentTypeId", contentTypeId);
        ftlContext.put("statusId", passedParams.get("statusId"));
        ftlContext.put("contentPurposeList", UtilMisc.toList(passedParams.get("contentPurposeList")));
        ftlContext.put("contentPurposeList", contentPurposeList);
        ftlContext.put("targetOperationList", targetOperationList);
        ftlContext.put("contentName", passedParams.get("contentName"));
        ftlContext.put("dataTemplateTypeId", passedParams.get("dataTemplateTypeId"));
        ftlContext.put("description", passedParams.get("description"));
        ftlContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
        String drid = (String) passedParams.get("dataResourceId");
        ftlContext.put("dataResourceId", drid);
        // inhibits persistence of DataResource, because it already exists
        ftlContext.put("dataResourceTypeId", null);
        String contentIdTo = (String) passedParams.get("contentIdTo");
        ftlContext.put("contentIdTo", contentIdTo);
        String contentAssocTypeId = (String) passedParams.get("contentAssocTypeId");
        // Don't post assoc at this time
        ftlContext.put("contentAssocTypeId", null);
        Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
        if (ServiceUtil.isError(ftlResults)) {
            String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            TransactionUtil.rollback();
            return "error";
        }
        String ftlContentId = (String) ftlResults.get("contentId");
        if (UtilValidate.isNotEmpty(contentIdTo)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fromDate", UtilDateTime.nowTimestamp());
            map.put("contentId", ftlContentId);
            map.put("contentIdTo", contentIdTo);
            map.put("userLogin", userLogin);
            if (UtilValidate.isEmpty(contentAssocTypeId) && UtilValidate.isEmpty(passedContentId) && UtilValidate.isNotEmpty(contentIdTo)) {
                // switch the association order because we are really not linking to the forum
                // but showing that this content is released to that forum.
                map.put("contentIdTo", ftlContentId);
                map.put("contentId", contentIdTo);
                map.put("contentAssocTypeId", "PUBLISH_RELEASE");
            } else if ("PUBLISH_LINK".equals(contentAssocTypeId)) {
                map.put("contentAssocTypeId", "PUBLISH_LINK");
                String publishOperation = (String) passedParams.get("publishOperation");
                if (UtilValidate.isEmpty(publishOperation)) {
                    publishOperation = "CONTENT_PUBLISH";
                }
                map.put("targetOperationList", StringUtil.split(publishOperation, "|"));
                map.put("targetOperationString", null);
            } else {
                map.put("contentAssocTypeId", contentAssocTypeId);
            }
            if (UtilValidate.isNotEmpty(map.get("contentAssocTypeId"))) {
                ftlResults = dispatcher.runSync("createContentAssoc", map);
                if (ServiceUtil.isError(ftlResults)) {
                    String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                    request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                    Debug.logError(errorMessage, module);
                    TransactionUtil.rollback();
                    return "error";
                }
            }
        }
        if (UtilValidate.isEmpty(ftlContentId)) {
            ftlContentId = passedContentId;
        }
        String ftlDataResourceId = drid;
        if (Debug.infoOn())
            Debug.logInfo("[UploadContentAndImage]ftlContentId:" + ftlContentId, module);
        // Create or update summary text subContent
        if (passedParams.containsKey("summaryData")) {
            Map<String, Object> sumContext = new HashMap<String, Object>();
            sumContext.put("userLogin", userLogin);
            sumContext.put("contentId", passedParams.get("sumContentId"));
            sumContext.put("ownerContentId", ftlContentId);
            sumContext.put("contentTypeId", "DOCUMENT");
            sumContext.put("statusId", passedParams.get("statusId"));
            sumContext.put("contentPurposeList", UtilMisc.toList("SUMMARY"));
            sumContext.put("targetOperationList", targetOperationList);
            sumContext.put("contentName", passedParams.get("contentName"));
            sumContext.put("description", passedParams.get("description"));
            sumContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            sumContext.put("dataResourceId", passedParams.get("sumDataResourceId"));
            sumContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            sumContext.put("contentIdTo", ftlContentId);
            sumContext.put("contentAssocTypeId", "SUB_CONTENT");
            sumContext.put("textData", passedParams.get("summaryData"));
            sumContext.put("mapKey", "SUMMARY");
            sumContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> sumResults = dispatcher.runSync("persistContentAndAssoc", sumContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Create or update electronic text subContent
        if (passedParams.containsKey("textData")) {
            Map<String, Object> txtContext = new HashMap<String, Object>();
            txtContext.put("userLogin", userLogin);
            txtContext.put("contentId", passedParams.get("txtContentId"));
            txtContext.put("ownerContentId", ftlContentId);
            txtContext.put("contentTypeId", "DOCUMENT");
            txtContext.put("statusId", passedParams.get("statusId"));
            txtContext.put("contentPurposeList", UtilMisc.toList("MAIN_ARTICLE"));
            txtContext.put("targetOperationList", targetOperationList);
            txtContext.put("contentName", passedParams.get("contentName"));
            txtContext.put("description", passedParams.get("description"));
            txtContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            txtContext.put("dataResourceId", passedParams.get("txtDataResourceId"));
            txtContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            txtContext.put("contentIdTo", ftlContentId);
            txtContext.put("contentAssocTypeId", "SUB_CONTENT");
            txtContext.put("textData", passedParams.get("textData"));
            txtContext.put("mapKey", "ARTICLE");
            txtContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> txtResults = dispatcher.runSync("persistContentAndAssoc", txtContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Create or update image subContent
        Map<String, Object> imgContext = new HashMap<String, Object>();
        if (imageBytes.length > 0) {
            imgContext.put("userLogin", userLogin);
            imgContext.put("contentId", passedParams.get("imgContentId"));
            imgContext.put("ownerContentId", ftlContentId);
            imgContext.put("contentTypeId", "DOCUMENT");
            imgContext.put("statusId", passedParams.get("statusId"));
            imgContext.put("contentName", passedParams.get("contentName"));
            imgContext.put("description", passedParams.get("description"));
            imgContext.put("contentPurposeList", contentPurposeList);
            imgContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            imgContext.put("targetOperationList", targetOperationList);
            imgContext.put("dataResourceId", passedParams.get("imgDataResourceId"));
            String dataResourceTypeId = "IMAGE_OBJECT";
            imgContext.put("dataResourceTypeId", dataResourceTypeId);
            imgContext.put("contentIdTo", ftlContentId);
            imgContext.put("contentAssocTypeId", "SUB_CONTENT");
            imgContext.put("imageData", imageBytes);
            imgContext.put("mapKey", "IMAGE");
            imgContext.put("dataTemplateTypeId", "NONE");
            imgContext.put("rootDir", "rootDir");
            if (Debug.infoOn())
                Debug.logInfo("[UploadContentAndImage]imgContext " + imgContext, module);
            Map<String, Object> imgResults = dispatcher.runSync("persistContentAndAssoc", imgContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Check for existing AUTHOR link
        String userLoginId = userLogin.getString("userLoginId");
        GenericValue authorContent = EntityQuery.use(delegator).from("Content").where("contentId", userLoginId).cache().queryOne();
        if (authorContent != null) {
            long currentAuthorAssocCount = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", ftlContentId, "contentIdTo", userLoginId, "contentAssocTypeId", "AUTHOR").filterByDate().queryCount();
            if (currentAuthorAssocCount == 0) {
                // Don't want to bother with permission checking on this association
                GenericValue authorAssoc = delegator.makeValue("ContentAssoc");
                authorAssoc.set("contentId", ftlContentId);
                authorAssoc.set("contentIdTo", userLoginId);
                authorAssoc.set("contentAssocTypeId", "AUTHOR");
                authorAssoc.set("fromDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("createdByUserLogin", userLoginId);
                authorAssoc.set("lastModifiedByUserLogin", userLoginId);
                authorAssoc.set("createdDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("lastModifiedDate", UtilDateTime.nowTimestamp());
                authorAssoc.create();
            }
        }
        request.setAttribute("dataResourceId", ftlDataResourceId);
        request.setAttribute("drDataResourceId", ftlDataResourceId);
        request.setAttribute("contentId", ftlContentId);
        request.setAttribute("masterContentId", ftlContentId);
        request.setAttribute("contentIdTo", contentIdTo);
        String newTrail = passedParams.get("nodeTrailCsv") + "," + ftlContentId;
        request.setAttribute("nodeTrailCsv", newTrail);
        request.setAttribute("passedParams", passedParams);
        TransactionUtil.commit();
    } catch (GenericEntityException | GenericServiceException e) {
        Debug.logError(e, "[UploadContentAndImage] ", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        try {
            TransactionUtil.rollback();
        } catch (GenericTransactionException e2) {
            request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
            return "error";
        }
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 47 with FileItem

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

the class UploadFileDebugServlet method doPost.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String relativePath = PentahoSystem.getSystemSetting("file-upload-defaults/relative-path", // $NON-NLS-1$
        String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH));
        String maxFileLimit = PentahoSystem.getSystemSetting("file-upload-defaults/max-file-limit", // $NON-NLS-1$
        String.valueOf(MAX_FILE_SIZE));
        String maxFolderLimit = PentahoSystem.getSystemSetting("file-upload-defaults/max-folder-limit", // $NON-NLS-1$
        String.valueOf(MAX_FOLDER_SIZE));
        IPentahoSession session = PentahoSessionHolder.getSession();
        // $NON-NLS-1$
        response.setContentType("text/plain");
        FileItem uploadItem = getFileItem(request);
        if (uploadItem == null) {
            // $NON-NLS-1$
            String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0001_NO_FILE_TO_UPLOAD");
            response.getWriter().write(error);
            return;
        }
        if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
            // $NON-NLS-1$
            String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0003_FILE_TOO_BIG");
            response.getWriter().write(error);
            return;
        }
        String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);
        File pathDir = new File(path);
        // create the path if it doesn't exist yet
        if (!pathDir.exists()) {
            pathDir.mkdirs();
        }
        if (uploadItem.getSize() + getFolderSize(new File(path)) > Long.parseLong(maxFolderLimit)) {
            String error = // $NON-NLS-1$
            Messages.getErrorString("UploadFileDebugServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED");
            response.getWriter().write(error);
            return;
        }
        // $NON-NLS-1$
        String filename = request.getParameter("file_name");
        if (StringUtils.isEmpty(filename)) {
            filename = UUIDUtil.getUUID().toString();
        }
        // $NON-NLS-1$
        String temporary = request.getParameter("mark_temporary");
        boolean isTemporary = false;
        if (temporary != null) {
            isTemporary = Boolean.valueOf(temporary);
        }
        File file;
        if (isTemporary) {
            File tempDir = new File(PentahoSystem.getApplicationContext().getSolutionPath("system/tmp"));
            if (tempDir.exists() == false) {
                tempDir.mkdir();
            }
            // $NON-NLS-1$
            file = PentahoSystem.getApplicationContext().createTempFile(session, filename, ".tmp", true);
        } else {
            file = new File(path + File.separatorChar + filename);
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] fileContents = uploadItem.get();
        outputStream.write(fileContents);
        outputStream.flush();
        outputStream.close();
        response.getWriter().write(file.getName());
    } catch (Exception e) {
        String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0005_UNKNOWN_ERROR", // $NON-NLS-1$
        e.getLocalizedMessage());
        response.getWriter().write(error);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 48 with FileItem

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

the class ServletRequest method parseRequestParameters.

@Override
public void parseRequestParameters(Map<String, String> params, Map<String, io.milton.http.FileItem> files) throws RequestParseException {
    try {
        if (isMultiPart()) {
            log.trace("parseRequestParameters: isMultiPart");
            UploadListener listener = new UploadListener();
            MonitoredDiskFileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            parseQueryString(params);
            for (Object o : items) {
                FileItem item = (FileItem) o;
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                } else {
                    // See http://jira.ettrema.com:8080/browse/MIL-118 - ServletRequest#parseRequestParameters overwrites multiple file uploads when using input type="file" multiple="multiple"
                    String itemKey = item.getFieldName();
                    if (files.containsKey(itemKey)) {
                        int count = 1;
                        while (files.containsKey(itemKey + count)) {
                            count++;
                        }
                        itemKey = itemKey + count;
                    }
                    files.put(itemKey, new FileItemWrapper(item));
                }
            }
        } else {
            for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
                String nm = (String) en.nextElement();
                String[] vals = request.getParameterValues(nm);
                if (vals.length == 1) {
                    params.put(nm, vals[0]);
                } else {
                    StringBuilder sb = new StringBuilder();
                    for (String s : vals) {
                        sb.append(s).append(",");
                    }
                    if (sb.length() > 0) {
                        // remove last comma
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    params.put(nm, sb.toString());
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new RequestParseException("FileUploadException", ex);
    } catch (Throwable ex) {
        throw new RequestParseException(ex.getMessage(), ex);
    }
}
Also used : Enumeration(java.util.Enumeration) UploadListener(io.milton.servlet.upload.UploadListener) FileItem(org.apache.commons.fileupload.FileItem) RequestParseException(io.milton.http.RequestParseException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ArrayList(java.util.ArrayList) List(java.util.List) MonitoredDiskFileItemFactory(io.milton.servlet.upload.MonitoredDiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 49 with FileItem

use of org.apache.commons.fileupload.FileItem in project structr by structr.

the class DeploymentServlet method doPost.

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
    try (final Tx tx = StructrApp.getInstance().tx()) {
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream().write("ERROR (400): Request does not contain multipart content.\n".getBytes("UTF-8"));
            return;
        }
        final SecurityContext securityContext;
        try {
            securityContext = getConfig().getAuthenticator().initializeAndExamineRequest(request, response);
        } catch (AuthenticationException ae) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getOutputStream().write("ERROR (401): Invalid user or password.\n".getBytes("UTF-8"));
            return;
        }
        if (securityContext.getUser(false) == null && !Settings.DeploymentAllowAnonymousUploads.getValue()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getOutputStream().write("ERROR (401): Anonymous uploads forbidden.\n".getBytes("UTF-8"));
            return;
        }
        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);
        request.setCharacterEncoding("UTF-8");
        // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
        response.setCharacterEncoding("UTF-8");
        // don't continue on redirects
        if (response.getStatus() == 302) {
            return;
        }
        final String pathInfo = request.getPathInfo();
        String type = null;
        if (StringUtils.isNotBlank(pathInfo)) {
            type = SchemaHelper.normalizeEntityName(StringUtils.stripStart(pathInfo.trim(), "/"));
        }
        uploader.setFileSizeMax(MEGABYTE * Settings.DeploymentMaxFileSize.getValue());
        uploader.setSizeMax(MEGABYTE * Settings.DeploymentMaxRequestSize.getValue());
        response.setContentType("text/html");
        final List<FileItem> fileItemsList = uploader.parseRequest(request);
        final Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        final Map<String, Object> params = new HashMap<>();
        while (fileItemsIterator.hasNext()) {
            final FileItem item = fileItemsIterator.next();
            try {
                final String directoryPath = "/tmp/" + UUID.randomUUID();
                final String filePath = directoryPath + ".zip";
                File file = new File(filePath);
                Files.write(IOUtils.toByteArray(item.getInputStream()), file);
                unzip(file, directoryPath);
                DeployCommand deployCommand = StructrApp.getInstance(securityContext).command(DeployCommand.class);
                final Map<String, Object> attributes = new HashMap<>();
                attributes.put("source", directoryPath + "/" + StringUtils.substringBeforeLast(item.getName(), "."));
                deployCommand.execute(attributes);
                file.deleteOnExit();
                File dir = new File(directoryPath);
                dir.deleteOnExit();
            } catch (IOException ex) {
                logger.warn("Could not upload file", ex);
            }
        }
        tx.success();
    } catch (FrameworkException | IOException | FileUploadException t) {
        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : DeployCommand(org.structr.web.maintenance.DeployCommand) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) HashMap(java.util.HashMap) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) SecurityContext(org.structr.common.SecurityContext) ZipFile(java.util.zip.ZipFile) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 50 with FileItem

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

Aggregations

FileItem (org.apache.commons.fileupload.FileItem)165 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)78 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)59 File (java.io.File)55 IOException (java.io.IOException)51 ArrayList (java.util.ArrayList)40 HashMap (java.util.HashMap)32 ServletException (javax.servlet.ServletException)30 List (java.util.List)27 InputStream (java.io.InputStream)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)23 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)16 Map (java.util.Map)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)10 Test (org.junit.Test)10 Iterator (java.util.Iterator)9 FileItemWrap (com.github.bordertech.wcomponents.file.FileItemWrap)8 Locale (java.util.Locale)8