Example usage for org.apache.commons.fileupload FileItem get

List of usage examples for org.apache.commons.fileupload FileItem get

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem get.

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:net.sourceforge.subsonic.controller.AvatarUploadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }//from  ww w  .  j a v  a 2  s.  c o  m

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}

From source file:net.sourceforge.subsonic.controller.MediaFolderSettingsController.java

private Map<String, String> getParameters(HttpServletRequest request) throws FileUploadException {

    keyBytes = null;//from ww w . ja v a 2 s  . c o  m
    Map<String, String> parameters = new HashMap<String, String>();
    if (ServletFileUpload.isMultipartContent(request)) {

        Map<String, Object> map = new HashMap<String, Object>();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = upload.parseRequest(request);

        // Look for file items.
        for (Object o : items) {
            FileItem item = (FileItem) o;

            if (!item.isFormField()) {
                byte[] data = item.get();

                if (data.length > 0) {
                    keyBytes = data;
                }
                break;
            } else {
                parameters.put(item.getFieldName(), item.getString());
            }
        }

        return parameters;
    }

    for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
        String key = e.nextElement();
        parameters.put(key, request.getParameter(key));
    }
    return parameters;

}

From source file:net.sourceforge.subsonic.controller.SpotifyKeyUploadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }/*from  www .ja  v  a 2  s.c  o  m*/

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        if (!item.isFormField()) {
            byte[] data = item.get();

            if (data.length > 0) {
                createKey(data, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload spotify key. Empty file.");
            }
            break;
        }
    }

    map.put("username", username);
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}

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

/** Get file parameter, as a byte array.
*//*from w w  w. ja v a 2s.c o m*/
@Override
public byte[] getBinaryBytes(String name) {
    if (request != null)
        return null;

    ArrayList list = (ArrayList) variableMap.get(name);
    if (list == null)
        return null;

    Object x = list.get(0);
    if (x instanceof String)
        return null;

    FileItem item = (FileItem) x;
    if (item.isFormField())
        return null;

    return item.get();
}

From source file:org.apache.myfaces.webapp.filter.MultipartRequestWrapper.java

private void parseRequest() {
    if (cacheFileSizeErrors) {
        fileUpload = new ServletChacheFileSizeErrorsFileUpload();
    } else {/* www .j  av  a2s.c om*/
        fileUpload = new ServletFileUpload();
    }
    //fileUpload.setFileItemFactory(new DefaultFileItemFactory()); //USE DiskFileItemFactory
    fileUpload.setSizeMax(maxSize);
    fileUpload.setFileSizeMax(maxFileSize);

    //fileUpload.setSizeThreshold(thresholdSize); //Pass thresholdSize as param for DiskFileItemFactory

    //if(repositoryPath != null && repositoryPath.trim().length()>0)
    //    fileUpload.setRepositoryPath(repositoryPath);

    if (repositoryPath != null && repositoryPath.trim().length() > 0) {
        fileUpload.setFileItemFactory(new DiskFileItemFactory(thresholdSize, new File(repositoryPath)));
    } else {
        fileUpload.setFileItemFactory(
                new DiskFileItemFactory(thresholdSize, new File(System.getProperty("java.io.tmpdir"))));
    }

    String charset = request.getCharacterEncoding();
    fileUpload.setHeaderEncoding(charset);

    List requestParameters = null;

    try {
        if (cacheFileSizeErrors) {
            requestParameters = ((ServletChacheFileSizeErrorsFileUpload) fileUpload)
                    .parseRequestCatchingFileSizeErrors(request, fileUpload);
        } else {
            requestParameters = fileUpload.parseRequest(request);
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // Since commons-fileupload does not allow to continue processing files
        // if this exception is thrown, we can't do anything else.
        // So, the current request is rejected and we can't restore state, so 
        // this request is dealt like a new request, but note that caching the params
        // below it is possible to detect if the current request has been aborted
        // or not.
        // Note that if cacheFileSizeErrors is true, this is not thrown, so the request
        // is not aborted unless other different error occur.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "fileSizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxFileSize));

        if (log.isWarnEnabled())
            log.warn("FileSizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // This exception is thrown when the max request size has been reached.
        // In this case, the current request is rejected. The current 
        // request is dealt like a new request, but note that caching the params below
        // params it is possible to detect if the current request has been aborted
        // or not.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "sizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxSize));

        if (log.isWarnEnabled())
            log.warn("SizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadException fue) {
        if (log.isErrorEnabled())
            log.error("Exception while uploading file.", fue);

        requestParameters = Collections.EMPTY_LIST;
    }

    parametersMap = new HashMap(requestParameters.size());
    fileItems = new HashMap();

    for (Iterator iter = requestParameters.iterator(); iter.hasNext();) {
        FileItem fileItem = (FileItem) iter.next();

        if (fileItem.isFormField()) {
            String name = fileItem.getFieldName();

            // The following code avoids commons-fileupload charset problem.
            // After fixing commons-fileupload, this code should be
            //
            //     String value = fileItem.getString();
            //
            String value = null;
            if (charset == null) {
                value = fileItem.getString();
            } else {
                try {
                    value = new String(fileItem.get(), charset);
                } catch (UnsupportedEncodingException e) {
                    value = fileItem.getString();
                }
            }

            addTextParameter(name, value);
        } else { // fileItem is a File
            if (fileItem.getName() != null) {
                fileItems.put(fileItem.getFieldName(), fileItem);
            }
        }
    }

    //Add the query string paramters
    /* This code does only works if is true the assumption that query params
     * are the same from start of the request. But it is possible
     * use jsp:include and jsp:param to set query params after
     * the request is parsed.
    for (Iterator it = request.getParameterMap().entrySet().iterator(); it.hasNext(); )
    {
    Map.Entry entry = (Map.Entry)it.next();
            
    Object value = entry.getValue();
            
    if(value instanceof String[])
    {
        String[] valuesArray = (String[])entry.getValue();
        for (int i = 0; i < valuesArray.length; i++)
        {
            addTextParameter((String)entry.getKey(), valuesArray[i]);
        }
    }
    else if(value instanceof String)
    {
        String strValue = (String)entry.getValue();
        addTextParameter((String)entry.getKey(), strValue);
    }
    else if(value != null)
        throw new IllegalStateException("value of type : "+value.getClass()+" for key : "+
                entry.getKey()+" cannot be handled.");
            
    }
    */
}

From source file:org.apache.myfaces.webapp.filter.PortletMultipartRequestWrapper.java

private void parseRequest() {
    if (cacheFileSizeErrors) {
        fileUpload = new PortletChacheFileSizeErrorsFileUpload();
    } else {//from   ww  w . j  av a2s  . c  o m
        fileUpload = new PortletFileUpload();
    }

    fileUpload.setSizeMax(maxSize);
    fileUpload.setFileSizeMax(maxFileSize);

    //fileUpload.setSizeThreshold(thresholdSize);

    if (repositoryPath != null && repositoryPath.trim().length() > 0) {
        //fileUpload.setRepositoryPath(repositoryPath);
        fileUpload.setFileItemFactory(new DiskFileItemFactory(thresholdSize, new File(repositoryPath)));
    } else {
        fileUpload.setFileItemFactory(
                new DiskFileItemFactory(thresholdSize, new File(System.getProperty("java.io.tmpdir"))));
    }

    String charset = request.getCharacterEncoding();
    fileUpload.setHeaderEncoding(charset);

    List requestParameters = null;

    try {
        if (cacheFileSizeErrors) {
            requestParameters = ((PortletChacheFileSizeErrorsFileUpload) fileUpload)
                    .parseRequestCatchingFileSizeErrors(request, fileUpload);
        } else {
            requestParameters = fileUpload.parseRequest(request);
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // Since commons-fileupload does not allow to continue processing files
        // if this exception is thrown, we can't do anything else.
        // So, the current request is rejected and we can't restore state, so 
        // this request is dealt like a new request, but note that caching the params
        // below it is possible to detect if the current request has been aborted
        // or not.
        // Note that if cacheFileSizeErrors is true, this is not thrown, so the request
        // is not aborted unless other different error occur.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "fileSizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxFileSize));

        if (log.isWarnEnabled())
            log.warn("FileSizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // This exception is thrown when the max request size has been reached.
        // In this case, the current request is rejected. The current 
        // request is dealt like a new request, but note that caching the params below
        // params it is possible to detect if the current request has been aborted
        // or not.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "sizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxSize));

        if (log.isWarnEnabled())
            log.warn("SizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadException fue) {
        if (log.isErrorEnabled())
            log.error("Exception while uploading file.", fue);

        requestParameters = Collections.EMPTY_LIST;
    }

    parametersMap = new HashMap(requestParameters.size());
    fileItems = new HashMap();

    for (Iterator iter = requestParameters.iterator(); iter.hasNext();) {
        FileItem fileItem = (FileItem) iter.next();

        if (fileItem.isFormField()) {
            String name = fileItem.getFieldName();

            // The following code avoids commons-fileupload charset problem.
            // After fixing commons-fileupload, this code should be
            //
            //     String value = fileItem.getString();
            //
            String value = null;
            if (charset == null) {
                value = fileItem.getString();
            } else {
                try {
                    value = new String(fileItem.get(), charset);
                } catch (UnsupportedEncodingException e) {
                    value = fileItem.getString();
                }
            }

            addTextParameter(name, value);
        } else { // fileItem is a File
            if (fileItem.getName() != null) {
                fileItems.put(fileItem.getFieldName(), fileItem);
            }
        }
    }

    //Add the query string paramters
    for (Iterator it = request.getParameterMap().entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();

        Object value = entry.getValue();

        if (value instanceof String[]) {
            String[] valuesArray = (String[]) entry.getValue();
            for (int i = 0; i < valuesArray.length; i++) {
                addTextParameter((String) entry.getKey(), valuesArray[i]);
            }
        } else if (value instanceof String) {
            String strValue = (String) entry.getValue();
            addTextParameter((String) entry.getKey(), strValue);
        } else if (value != null)
            throw new IllegalStateException("value of type : " + value.getClass() + " for key : "
                    + entry.getKey() + " cannot be handled.");

    }
}

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

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {/*ww w.j  a  v  a  2s.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. ja  va 2 s.  c o m*/
        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.
 */// w w w . j a  v  a  2  s.c  o m
// 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   www  . 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;
}