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.guvnor.m2repo.backend.server.helpers.HttpPostHelper.java

@SuppressWarnings("rawtypes")
private FormData extractFormData(final HttpServletRequest request) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    FormData data = new FormData();
    GAV emptyGAV = new GAV();
    try {/*ww  w.  ja  va 2s.  c  o m*/
        List items = upload.parseRequest(request);
        Iterator it = items.iterator();
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (!item.isFormField()) {
                data.setFile(item);
            }

            if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.GROUP_ID)) {
                emptyGAV.setGroupId(item.getString());
            } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.ARTIFACT_ID)) {
                emptyGAV.setArtifactId(item.getString());
            } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.VERSION_ID)) {
                emptyGAV.setVersion(item.getString());
            }
        }

        if (isNullOrEmpty(emptyGAV.getGroupId()) || isNullOrEmpty(emptyGAV.getArtifactId())
                || isNullOrEmpty(emptyGAV.getVersion())) {
            data.setGav(null);
        } else {
            data.setGav(emptyGAV);
        }

        return data;

    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}

From source file:org.iplantc.phyloviewer.viewer.server.ParseTreeService.java

/**
 * Accepts a tree for parsing and storage, and returns a URL to view the tree.  
 * May return before the tree has finished importing.
 * //from ww  w. j av a2s  .  c o  m
 * @param request has the following parameters:
 * <pre>
 * newickData or nexml: a string representing the tree data
 * name (optional): the label that is given to the newick tree. 
 *    Nexml documents already have an attribute for tree label, so they don't use this parameter.
 * </pre>
 * 
 * @param response contains the URL to view the tree
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    Logger.getLogger("org.iplantc.phyloviewer").log(Level.FINE, "Received tree post request");

    PrintWriter writer = getWriter(response);

    Map<String, String[]> parameters = null;
    try {
        Logger.getLogger("org.iplantc.phyloviewer").log(Level.FINE, "Reading request parameters");
        parameters = getParameters(request);
    } catch (FileUploadException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writer.println(e.getMessage());
        writer.flush();
        writer.close();
        return;
    }

    try {
        String id = parseTree.saveTree(parameters);

        if (id != null) {
            Logger.getLogger("org.iplantc.phyloviewer").log(Level.FINE, "Returning response");
            response.setStatus(HttpServletResponse.SC_ACCEPTED);

            String viewURL = getViewURL(id, request);
            response.setHeader("Location", viewURL);
            writer.println(viewURL);
        } else {
            Logger.getLogger("org.iplantc.phyloviewer").log(Level.FINE, "No trees found. Returning response");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            writer.println("Bad request: No tree data found.");
        }
    } catch (ParserException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writer.println(e.getMessage());
        e.printStackTrace(writer);
    } catch (SAXException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writer.println(e.getMessage());
        e.printStackTrace(writer);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        writer.println(e.getMessage());
        e.printStackTrace(writer);
    }

    writer.flush();
    writer.close();
}

From source file:org.jahia.tools.files.FileUpload.java

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException//from   w  w w.  j a  v  a 2 s  .c o  m
 */
protected void init() throws IOException {

    params = new HashMap<String, List<String>>();
    paramsContentType = new HashMap<String, String>();
    files = new HashMap<String, DiskFileItem>();
    filesByFieldName = new HashMap<String, DiskFileItem>();

    parseQueryString();

    if (checkSavePath(savePath)) {
        try {
            final ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            DiskFileItemFactory factory = null;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final List<String> v;
                    if (params.containsKey(name)) {
                        v = params.get(name);
                    } else {
                        v = new ArrayList<String>();
                        params.put(name, v);
                    }
                    v.add(Streams.asString(stream, encoding));
                    paramsContentType.put(name, item.getContentType());
                } else {
                    if (factory == null) {
                        factory = new DiskFileItemFactory();
                        factory.setSizeThreshold(1);
                        factory.setRepository(new File(savePath));
                    }
                    DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(),
                            item.getContentType(), item.isFormField(), item.getName());
                    try {
                        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                    } catch (FileUploadIOException e) {
                        throw (FileUploadException) e.getCause();
                    } catch (IOException e) {
                        throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                                + " request failed. " + e.getMessage(), e);
                    }
                    final FileItemHeaders fih = item.getHeaders();
                    fileItem.setHeaders(fih);
                    if (fileItem.getSize() > 0) {
                        files.put(fileItem.getStoreLocation().getName(), fileItem);
                        filesByFieldName.put(fileItem.getFieldName(), fileItem);
                    }
                }
            }
        } catch (FileUploadException ioe) {
            logger.error("Error while initializing FileUpload class:", ioe);
            throw new IOException(ioe.getMessage());
        }
    } else {
        logger.error("FileUpload::init storage path does not exists or can write");
        throw new IOException("FileUpload::init storage path does not exists or cannot write");
    }
}

From source file:org.liquidsite.core.web.MultiPartRequest.java

/**
 * Creates a new multi-part request.//from   w  w w.jav  a2s . c  o m
 *
 * @param context        the servlet context
 * @param request        the HTTP request
 * @param response       the HTTP response
 * @param tempDir        the temporary upload directory
 * @param maxSize        the maximum upload size (in bytes)
 *
 * @throws ServletException if the request couldn't be parsed
 *             correctly
 */
public MultiPartRequest(ServletContext context, HttpServletRequest request, HttpServletResponse response,
        String tempDir, int maxSize) throws ServletException {

    super(context, request, response);
    this.uploadDir = tempDir;
    this.uploadSize = maxSize;
    try {
        parse(request);
    } catch (FileUploadException e) {
        LOG.error(e.getMessage());
        throw new ServletException("Couldn't handle multipart request: " + e.getMessage());
    }
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*w  w w .j  av  a2 s .  c o m*/
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}

From source file:org.musicrecital.webapp.pages.FileUpload.java

Object onUploadException(FileUploadException exception) {
    logger.error(String.format("Upload exception: %s ", exception.getMessage()));
    alertManager.alert(Duration.TRANSIENT, Severity.ERROR, messages.get("maxLengthExceeded"));
    return this;
}

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

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  w w  .ja  v  a2s. 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 (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);

        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 = FastMap.newInstance();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes = {};
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            //String fn = fi.getName();
            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 = FastMap.newInstance();
        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");
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]drid:" + drid, module);
        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 = FastMap.newInstance();
            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);
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]ftlDataResourceId:" + ftlDataResourceId, module);
        // Create or update summary text subContent
        if (passedParams.containsKey("summaryData")) {
            Map<String, Object> sumContext = FastMap.newInstance();
            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("contentPurposeList", contentPurposeList);
            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 = FastMap.newInstance();
            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", contentPurposeList);
            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 = FastMap.newInstance();
        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 = (String)passedParams.get("dataResourceTypeId");
            //if (UtilValidate.isEmpty(dataResourceTypeId))
            //dataResourceTypeId = "IMAGE_OBJECT";
            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");
            // String rootDir = request.getSession().getServletContext().getRealPath("/");
            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 (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]currentAuthorAssocList " + currentAuthorAssocList, module);
            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);
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]newTrail: " + newTrail, module);
        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.ofbiz.content.content.UploadContentAndImage.java

public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
    try {/*from ww  w.j  a  v  a 2 s .  co  m*/
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

        ServletFileUpload dfu = new ServletFileUpload(
                new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]DiskFileUpload " + dfu, module);
        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 (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);

        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 = FastMap.newInstance();
        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 fn = fi.getName();
            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.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.
 *//*  www  . j av  a  2  s. c om*/
// TODO: This method is not used and should be removed. amb
public static String uploadAndStoreImage(HttpServletRequest request, String idField, String uploadField) {
    //Delegator delegator = (Delegator) request.getAttribute("delegator");

    //String idFieldValue = null;
    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 = FastMap.newInstance();
    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 fn = fi.getName();
        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.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.
 *//*  w w  w.  j  a v a 2 s  .  c  om*/
public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) {

    //Debug.logVerbose("in uploadAndStoreImage", "");
    Locale locale = UtilHttp.getLocale(request);

    Map<String, Object> results = FastMap.newInstance();
    Map<String, String> formInput = FastMap.newInstance();
    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);
        //Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
        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);
            //Debug.logVerbose("in uploadAndStoreImage, fieldName:" + fieldName + " fieldStr:" + 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);
        //Debug.logWarning("[DataEvents.uploadImage] imageFi(" + imageFi + ") is null", module);
        return null;
    }

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

    //Debug.logVerbose("in uploadAndStoreImage, results:" + results, "");
    return results;
}