Example usage for org.apache.commons.fileupload FileUploadException getMessage

List of usage examples for org.apache.commons.fileupload FileUploadException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.activiti.rest.api.repository.BaseModelSourceResource.java

@Put
public InputRepresentation setModelSource(Representation representation) {
    if (authenticate() == false)
        return null;

    Model model = getModelFromRequest();

    if (!MediaType.MULTIPART_FORM_DATA.isCompatible(representation.getMediaType())) {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(),
                "The request should be of type 'multipart/form-data'.", null, null);
    }// ww  w . j a va2 s.  co  m

    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    try {
        FileItem uploadItem = null;
        List<FileItem> items = upload.parseRepresentation(representation);
        for (FileItem fileItem : items) {
            uploadItem = fileItem;
        }
        if (uploadItem == null) {
            throw new ActivitiIllegalArgumentException("No file content was found in request body.");
        }

        int size = ((Long) uploadItem.getSize()).intValue();

        // Copy file-body in a bytearray as the engine requires this
        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size);
        IOUtils.copy(uploadItem.getInputStream(), bytesOutput);

        byte[] byteArray = bytesOutput.toByteArray();
        setModelSource(model, byteArray);

        return new InputRepresentation(new ByteArrayInputStream(byteArray), MediaType.APPLICATION_OCTET_STREAM);

    } catch (FileUploadException e) {
        throw new ActivitiException("Error with uploaded file: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ActivitiException("Error while reading uploaded file: " + e.getMessage(), e);
    }
}

From source file:org.activiti.rest.service.api.identity.UserPictureResource.java

@Put
public void updateUserPicture(Representation representation) {
    if (authenticate() == false)
        return;/* w  ww .j  a v  a 2s.  co m*/
    User user = getUserFromRequest();

    if (!MediaType.MULTIPART_FORM_DATA.isCompatible(representation.getMediaType())) {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(),
                "The request should be of type 'multipart/form-data'.", null, null);
    }

    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    try {
        FileItem uploadItem = null;
        List<FileItem> items = upload.parseRepresentation(representation);
        String mimeType = MediaType.IMAGE_JPEG.toString();

        for (FileItem fileItem : items) {
            if (fileItem.isFormField()) {
                if ("mimeType".equals(fileItem.getFieldName())) {
                    mimeType = fileItem.getString("UTF-8");
                }
            } else if (fileItem.getName() != null) {
                uploadItem = fileItem;
            }
        }

        if (uploadItem == null) {
            throw new ActivitiIllegalArgumentException("No file content was found in request body.");
        }

        int size = ((Long) uploadItem.getSize()).intValue();

        // Copy file-body in a bytearray as the engine requires this
        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size);
        IOUtils.copy(uploadItem.getInputStream(), bytesOutput);

        Picture newPicture = new Picture(bytesOutput.toByteArray(), mimeType);
        ActivitiUtil.getIdentityService().setUserPicture(user.getId(), newPicture);

    } catch (FileUploadException e) {
        throw new ActivitiException("Error with uploaded file: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ActivitiException("Error while reading uploaded file: " + e.getMessage(), e);
    }
}

From source file:org.air.standard.web.presentation.FileUploadHandler.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from  ww  w .  j a  va 2 s .c  o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    _logger.debug("FileUploadhandler fired!");

    String initParameterFileType = getServletConfig().getInitParameter("fileType");

    String ooExecPath = null;
    String ooSpreadsheetPath = null;
    File uploadedFile = null;

    try {
        InitialContext context = new InitialContext();

        ooExecPath = request.getSession().getServletContext().getInitParameter("ooExecPath");
        ooSpreadsheetPath = request.getSession().getServletContext().getInitParameter("ooSpreadsheetPath");
        //          ooExecPath = container.getInitParameter("ooExecPath");
        //          ooSpreadsheetPath = container.getInitParameter("ooSpreadsheetPath");
        //         ooExecPath = (String) context.lookup("java:comp/env/ooExecPath");
        //         ooSpreadsheetPath = (String) context
        //               .lookup("java:comp/env/ooSpreadsheetPath");

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // LoggerFactory.LogInfo("TEST File upload MANAGER", getClass());
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                // Parse the request
                _logger.debug("Before parseRequest");
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                BufferedInputStream buf = null;
                ServletOutputStream stream = null;
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        if (fileName.isEmpty())
                            throw new InvalidArgumentException("File to Upload ", "not empty");
                        _logger.debug("Parsed file file " + fileName);
                        File uploadDirectory = new File(ooSpreadsheetPath);
                        if (!uploadDirectory.exists()) {
                            boolean status = uploadDirectory.mkdirs();
                        }
                        if (!uploadDirectory.exists())
                            throw new ContentStandardException(
                                    "Problems accessing " + ooSpreadsheetPath + "server directory");
                        // just so that we do not have a name clash
                        // we will prefix the current time stamp to the file
                        // name.
                        Date date = new Date();

                        String filePath = ooSpreadsheetPath + "/" + date.getTime() + fileName;
                        uploadedFile = new File(filePath);
                        /*if (!uploadedFile.canWrite()
                              || !uploadedFile.canRead())
                           throw new ContentStandardException(
                                 "Problem with read or write access to files in "
                            + ooSpreadsheetPath
                            + " server directory");
                            */
                        /*
                         * System.out.println(uploadedFile.getAbsolutePath())
                         * ;
                         */
                        item.write(uploadedFile);
                        _logger.debug("Wrote temp file " + uploadedFile.getAbsolutePath());

                    }
                }
            } catch (SecurityException se) {
                // can be thrown by canWrite, canRead, exists, mkdirs calls
                // if server is not configured with correct access rights
                _logger.error("Problem with access rights to " + ooSpreadsheetPath + " service directory. "
                        + se.getMessage());

                displayError(se, response);
                return;
            } catch (ContentStandardException cse) {
                _logger.error(cse.getMessage());
                displayError(cse, response);
                return;
            } catch (InvalidArgumentException iae) {
                // EF: do not use displayError because it sets
                // SC_INTERNAL_SERVLET_ERROR and this is not the case!
                _logger.error("FileUploadException: " + iae.getMessage());
                ReturnStatus<Exception> status = new ReturnStatus<Exception>("failed");
                status.setPayload(null);
                status.appendToErrors(iae.getMessage());

                ObjectMapper mapper = new ObjectMapper();
                String statusJson = mapper.writeValueAsString(status);
                // serialize the status object.
                response.setContentType("application/json");
                response.getOutputStream().print(statusJson);
                return;

            } catch (FileUploadException e) {
                e.printStackTrace();
                _logger.error("FileUpload Exception: " + e.getMessage());
                displayError(e, response);
                return;
            } catch (Exception e) {
                _logger.error("Problem parsing request/creating temp file : " + e.getMessage());
                e.printStackTrace();
                displayError(e, response);
                return;
            }

        }
        /* System.out.println("CONFIG FILE:::" + ooExecPath); */
    } catch (NamingException ex) {
        /* System.out.println("exception in jndi lookup"); */
        _logger.error("NamingException in jndi lookup" + ex.getMessage());
        displayError(ex, response);
        return;
    }

    ObjectMapper mapper = new ObjectMapper();
    String statusJson = null;
    try {
        ReturnStatus<String> status = new ReturnStatus<String>("success");
        //TODO Shiva how to get the bean factory here so that we can remove (new WebUserInformation()) and call the bean instead?
        String sessionKey = (new WebUserInformation()).getSessionKey();
        // clear out existing staging tables for this session key.
        LoaderTablesDAO dao = new LoaderTablesDAO();
        dao.loaderClear(sessionKey);

        // tell DB what kind of upload we are doing - full or partial.
        PublicationDAO publicationDAO = new PublicationDAO();
        if (initParameterFileType.equalsIgnoreCase("full")) {
            publicationDAO.importPublication(sessionKey);

        } else if (initParameterFileType.equalsIgnoreCase("partial")) {
            publicationDAO.partialImportPublication(sessionKey);
        }

        _logger.debug("About to call importFromFile for " + uploadedFile.getAbsolutePath());
        OpenOfficeImporter openOfficeImporter = new OpenOfficeImporter();

        openOfficeImporter.importFromFile(ooExecPath, uploadedFile.getAbsolutePath(), sessionKey, status);
        _logger.debug("Finished importFromFile  for" + uploadedFile.getAbsolutePath() + " status is "
                + status.getStatus());
        statusJson = mapper.writeValueAsString(status);
        // serialize the status object.
        response.setContentType("application/json");
        response.getOutputStream().print(statusJson);
        _logger.debug("Sent json response ");

    } catch (Exception exp) {
        _logger.error("Exception after temp file created " + exp.getMessage());
        exp.printStackTrace();
        displayError(exp, response);
    }
}

From source file:org.apache.click.control.Form.java

/**
 * Validate the request for any file upload (multipart) errors.
 * <p/>/*w  w w.j a va 2s.c  o  m*/
 * A form error message is displayed if a file upload error occurs.
 * These messages are defined in the resource bundle:
 * <blockquote>
 * <ul>
 *   <li>/click-control.properties
 *     <ul>
 *       <li>file-size-limit-exceeded-error</li>
 *       <li>post-size-limit-exceeded-error</li>
 *     </ul>
 *   </li>
 * </ul>
 * </blockquote>
 */
protected void validateFileUpload() {
    setError(null);

    Exception exception = (Exception) getContext().getRequest()
            .getAttribute(FileUploadService.UPLOAD_EXCEPTION);

    if (!(exception instanceof FileUploadException)) {
        return;
    }

    FileUploadException fue = (FileUploadException) exception;

    String key = null;
    Object args[] = null;

    if (fue instanceof SizeLimitExceededException) {
        SizeLimitExceededException se = (SizeLimitExceededException) fue;

        key = "post-size-limit-exceeded-error";

        args = new Object[2];
        args[0] = se.getPermittedSize();
        args[1] = se.getActualSize();
        setError(getMessage(key, args));

    } else if (fue instanceof FileSizeLimitExceededException) {
        FileSizeLimitExceededException fse = (FileSizeLimitExceededException) fue;

        key = "file-size-limit-exceeded-error";

        // Parse the FileField name from the message
        String msg = fue.getMessage();
        int start = 10;
        int end = msg.indexOf(' ', start);
        String fieldName = fue.getMessage().substring(start, end);

        args = new Object[3];
        args[0] = ClickUtils.toLabel(fieldName);
        args[1] = fse.getPermittedSize();
        args[2] = fse.getActualSize();
        setError(getMessage(key, args));
    }
}

From source file:org.apache.geronimo.console.bundlemanager.BundleManagerPortlet.java

/******************************
 * Install Action//from  www.j a  v a2 s .c  om
 ******************************/
private void processInstallAction(ActionRequest request, BundleContext bundleContext,
        StartLevel startLevelService) throws PortletException, IOException {
    if (!PortletFileUpload.isMultipartContent(request)) {
        throw new PortletException("Expected file upload");
    }

    // use commons-fileupload to process the request
    File rootDir = new File(System.getProperty("java.io.tmpdir"));
    PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory(10240, rootDir));

    File bundleFile = null;
    String startAfterInstalled = null;
    String str_startLevel = null;

    List<?> items;
    try {
        items = uploader.parseRequest(request);
    } catch (FileUploadException e) {
        addErrorMessage(request, getLocalizedString(request, "consolebase.bundlemanager.err.file.uploadError"));
        logger.error("FileUploadException", e);
        return;
    }

    // deal with the multipart form data items;
    for (Iterator<?> i = items.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        if (!item.isFormField()) {
            String fieldName = item.getFieldName();
            String fileName = item.getName().trim();
            if (fileName.length() != 0) {
                int index = fileName.lastIndexOf('\\');
                if (index != -1) {
                    fileName = fileName.substring(index + 1);
                }
                if ("bundleFile".equals(fieldName)) {
                    bundleFile = new File(rootDir, fileName);
                }
            }
            if (bundleFile != null) {
                try {
                    item.write(bundleFile);
                } catch (Exception e) {
                    addErrorMessage(request,
                            getLocalizedString(request, "consolebase.bundlemanager.err.file.writeError"));
                    logger.error("Exception", e);
                    return;
                }
            } else {
                //should never happen
                addErrorMessage(request,
                        getLocalizedString(request, "consolebase.bundlemanager.err.file.nullError"));
                logger.error("The uploaded file is null!");
                return;
            }
        } else {
            if ("startAfterInstalled".equalsIgnoreCase(item.getFieldName())) {
                startAfterInstalled = item.getString();
            } else if ("startLevel".equalsIgnoreCase(item.getFieldName())) {
                str_startLevel = item.getString();
            }
        }
    }

    // install the uploaded bundle file
    String url = "file:///" + bundleFile.getCanonicalPath();

    Bundle installedBundle;
    try {
        installedBundle = bundleContext.installBundle(url);
        addInfoMessage(request, getLocalizedString(request, "consolebase.bundlemanager.info.install",
                installedBundle.getSymbolicName(), installedBundle.getBundleId()));
    } catch (BundleException e) {
        addErrorMessage(request,
                getLocalizedString(request, "consolebase.bundlemanager.err.actionError") + "install",
                e.getMessage());
        logger.error("BundleException", e);
        return;
    }

    // set start level for the installed bundle
    int startLevel = -1;
    try {
        startLevel = Integer.parseInt(str_startLevel);
    } catch (NumberFormatException e) {
        // if can't generated, use the default initialBundleStartLevel
    }
    int defaultStartLevel = startLevelService.getInitialBundleStartLevel();
    if (startLevel != defaultStartLevel && startLevel >= 0) {
        startLevelService.setBundleStartLevel(installedBundle, startLevel);
    }

    // if check box "Start" checked, then start the bundle
    if ("yes".equals(startAfterInstalled)) {
        try {
            installedBundle.start();
            addInfoMessage(request, getLocalizedString(request, "consolebase.bundlemanager.info.start",
                    installedBundle.getSymbolicName(), installedBundle.getBundleId()));
        } catch (BundleException e) {
            addErrorMessage(request,
                    getLocalizedString(request, "consolebase.bundlemanager.err.actionError") + "start",
                    e.getMessage());
            logger.error("BundleException", e);
            return;
        }

    }
}

From source file:org.apache.manifoldcf.ui.multipart.MultipartWrapper.java

/** Constructor.
*//* ww  w .  java2  s.co  m*/
public MultipartWrapper(HttpServletRequest request, AdminProfile adminProfile) throws ManifoldCFException {
    this.adminProfile = adminProfile;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        this.request = request;
        return;
    }

    // It is multipart!

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    try {
        characterEncoding = request.getCharacterEncoding();
        // Handle broken tomcat; characterEncoding always comes back null for tomcat4
        if (characterEncoding == null)
            characterEncoding = "utf8";
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String name = item.getFieldName();
            ArrayList list = (ArrayList) variableMap.get(name);
            if (list == null) {
                list = new ArrayList();
                variableMap.put(name, list);
            } else {
                if (((FileItem) list.get(0)).isFormField() != item.isFormField())
                    throw new ManifoldCFException(
                            "Illegal form data; posted form has the same name for different data types ('"
                                    + name + "')!");
            }
            list.add(item);
        }
    } catch (FileUploadException e) {
        throw new ManifoldCFException("Problem uploading file: " + e.getMessage(), e);
    }
}

From source file:org.apache.ofbiz.content.content.UploadContentAndImage.java

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {/*from ww  w.  j a v  a  2 s.c o m*/
        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 (fieldName.equals("imageData")) {
                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);
        ftlContext.put("dataResourceTypeId", null); // inhibits persistence of DataResource, because it already exists
        String contentIdTo = (String) passedParams.get("contentIdTo");
        ftlContext.put("contentIdTo", contentIdTo);
        String contentAssocTypeId = (String) passedParams.get("contentAssocTypeId");
        ftlContext.put("contentAssocTypeId", null); // Don't post assoc at this time
        Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
        boolean isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
        if (isError) {
            request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
            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 (contentAssocTypeId.equals("PUBLISH_LINK")) {
                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);
                isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
                if (isError) {
                    request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
                    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);
            isError = ModelService.RESPOND_ERROR.equals(sumResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", sumResults.get(ModelService.ERROR_MESSAGE));
                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);
            isError = ModelService.RESPOND_ERROR.equals(txtResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", txtResults.get(ModelService.ERROR_MESSAGE));
                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);
            isError = ModelService.RESPOND_ERROR.equals(imgResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", imgResults.get(ModelService.ERROR_MESSAGE));
                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 (Exception 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";
}

From source file:org.apache.ofbiz.content.content.UploadContentAndImage.java

public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
    try {//from w ww .  j a  v a  2s.c om
        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) {
            request.setAttribute("_ERROR_MESSAGE_", "No files uploaded");
            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 = {};
        passedParams.put("userLogin", userLogin);
        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 (fieldName.startsWith("imageData")) {
                imageFi = fi;
                String fileName = fi.getName();
                passedParams.put("drObjectInfo", fileName);
                String contentType = fi.getContentType();
                passedParams.put("drMimeTypeId", contentType);
                imageBytes = imageFi.get();
                passedParams.put(fieldName, imageBytes);
                if (Debug.infoOn()) {
                    Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
                }
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }

        // The number of multi form rows is retrieved
        int rowCount = UtilHttp.getMultiFormRowCount(request);
        if (rowCount < 1) {
            rowCount = 1;
        }
        TransactionUtil.begin();
        for (int i = 0; i < rowCount; i++) {
            String suffix = "_o_" + i;
            if (i == 0) {
                suffix = "";
            }
            String returnMsg = processContentUpload(passedParams, suffix, request);
            if (returnMsg.equals("error")) {
                try {
                    TransactionUtil.rollback();
                } catch (GenericTransactionException e2) {
                    ServiceUtil.setMessages(request, e2.getMessage(), null, null);
                    return "error";
                }
                return "error";
            }
        }
        TransactionUtil.commit();
    } catch (Exception 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";
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

/**
 * Uploads image data from a form and stores it in ImageDataResource. Expects key data in a field identified by the "idField" value and the binary data
 * to be in a field id'd by uploadField.
 *//*from  w  ww.j a va 2s. com*/
// TODO: This method is not used and should be removed. amb
public static String uploadAndStoreImage(HttpServletRequest request, String idField, String uploadField) {
    ServletFileUpload fu = new ServletFileUpload(
            new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
    List<FileItem> lst = null;
    Locale locale = UtilHttp.getLocale(request);

    try {
        lst = UtilGenerics.checkList(fu.parseRequest(request));
    } catch (FileUploadException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    if (lst.size() == 0) {
        String errMsg = UtilProperties.getMessage(DataResourceWorker.err_resource,
                "dataResourceWorker.no_files_uploaded", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
        return "error";
    }

    // This code finds the idField and the upload FileItems
    FileItem fi = null;
    FileItem imageFi = null;
    String imageFileName = null;
    Map<String, Object> passedParams = new HashMap<String, Object>();
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    passedParams.put("userLogin", userLogin);
    byte[] imageBytes = null;
    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 (fieldName.startsWith("imageData")) {
            imageFi = fi;
            imageBytes = imageFi.get();
            passedParams.put(fieldName, imageBytes);
            imageFileName = imageFi.getName();
            passedParams.put("drObjectInfo", imageFileName);
            if (Debug.infoOn())
                Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
        }
    }

    if (imageBytes != null && imageBytes.length > 0) {
        String mimeType = getMimeTypeFromImageFileName(imageFileName);
        if (UtilValidate.isNotEmpty(mimeType)) {
            passedParams.put("drMimeTypeId", mimeType);
            try {
                String returnMsg = UploadContentAndImage.processContentUpload(passedParams, "", request);
                if (returnMsg.equals("error")) {
                    return "error";
                }
            } catch (GenericServiceException e) {
                request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
                return "error";
            }
        } else {
            request.setAttribute("_ERROR_MESSAGE_", "mimeType is empty.");
            return "error";
        }
    }
    return "success";
}

From source file:org.apache.ofbiz.content.layout.LayoutWorker.java

/**
 * Uploads image data from a form and stores it in ImageDataResource.
 * Expects key data in a field identitified by the "idField" value
 * and the binary data to be in a field id'd by uploadField.
 *//*from  w w  w  .j  a  va  2 s. c o  m*/
public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) {
    Locale locale = UtilHttp.getLocale(request);

    Map<String, Object> results = new HashMap<String, Object>();
    Map<String, String> formInput = new HashMap<String, String>();
    results.put("formInput", formInput);
    ServletFileUpload fu = new ServletFileUpload(
            new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));
    List<FileItem> lst = null;
    try {
        lst = UtilGenerics.checkList(fu.parseRequest(request));
    } catch (FileUploadException e4) {
        return ServiceUtil.returnError(e4.getMessage());
    }

    if (lst.size() == 0) {
        String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale));
    }

    // This code finds the idField and the upload FileItems
    FileItem fi = null;
    FileItem imageFi = null;
    for (int i = 0; i < lst.size(); i++) {
        fi = lst.get(i);
        String fieldName = fi.getFieldName();
        String fieldStr = fi.getString();
        if (fi.isFormField()) {
            formInput.put(fieldName, fieldStr);
            request.setAttribute(fieldName, fieldStr);
        }
        if (fieldName.equals(uploadField)) {
            imageFi = fi;
            //MimeType of upload file
            results.put("uploadMimeType", fi.getContentType());
        }
    }

    if (imageFi == null) {
        String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.image_null",
                UtilMisc.toMap("imageFi", imageFi), locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return null;
    }

    byte[] imageBytes = imageFi.get();
    ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes);
    results.put("imageData", byteWrap);
    results.put("imageFileName", imageFi.getName());
    return results;
}