Search in sources :

Example 11 with MiniLangException

use of org.apache.ofbiz.minilang.MiniLangException in project ofbiz-framework by apache.

the class LimitedSubContentCacheTransform method getWriter.

@Override
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
    final StringBuilder buf = new StringBuilder();
    final Environment env = Environment.getCurrentEnvironment();
    final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    FreeMarkerWorker.getSiteParameters(request, templateRoot);
    final Map<String, Object> savedValuesUp = new HashMap<>();
    FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
    final Map<String, Object> savedValues = new HashMap<>();
    FreeMarkerWorker.overrideWithArgs(templateRoot, args);
    String contentAssocTypeId = (String) templateRoot.get("contentAssocTypeId");
    if (UtilValidate.isEmpty(contentAssocTypeId)) {
        contentAssocTypeId = "SUB_CONTENT";
        templateRoot.put("contentAssocTypeId ", contentAssocTypeId);
    }
    final Map<String, GenericValue> pickedEntityIds = new HashMap<>();
    List<String> assocTypes = StringUtil.split(contentAssocTypeId, "|");
    String contentPurposeTypeId = (String) templateRoot.get("contentPurposeTypeId");
    List<String> purposeTypes = StringUtil.split(contentPurposeTypeId, "|");
    templateRoot.put("purposeTypes", purposeTypes);
    Locale locale = (Locale) templateRoot.get("locale");
    if (locale == null) {
        locale = Locale.getDefault();
        templateRoot.put("locale", locale);
    }
    Map<String, Object> whenMap = new HashMap<>();
    whenMap.put("followWhen", templateRoot.get("followWhen"));
    whenMap.put("pickWhen", templateRoot.get("pickWhen"));
    whenMap.put("returnBeforePickWhen", templateRoot.get("returnBeforePickWhen"));
    whenMap.put("returnAfterPickWhen", templateRoot.get("returnAfterPickWhen"));
    templateRoot.put("whenMap", whenMap);
    String fromDateStr = (String) templateRoot.get("fromDateStr");
    Timestamp fromDate = null;
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        fromDate = UtilDateTime.toTimestamp(fromDateStr);
    }
    if (fromDate == null) {
        fromDate = UtilDateTime.nowTimestamp();
    }
    String limitSize = (String) templateRoot.get("limitSize");
    final int returnLimit = Integer.parseInt(limitSize);
    String orderBy = (String) templateRoot.get("orderBy");
    // NOTE this was looking for subContentId, but that doesn't make ANY sense, so changed to contentId
    String contentId = (String) templateRoot.get("contentId");
    templateRoot.put("contentId", null);
    templateRoot.put("subContentId", null);
    Map<String, Object> results = null;
    String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId");
    try {
        results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", fromDate, null, assocTypes, null, Boolean.TRUE, contentAssocPredicateId, orderBy);
    } catch (MiniLangException | GenericEntityException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    List<GenericValue> longList = UtilGenerics.checkList(results.get("entityList"));
    templateRoot.put("entityList", longList);
    return new LoopWriter(out) {

        @Override
        public void write(char[] cbuf, int off, int len) {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public int onStart() throws TemplateModelException, IOException {
            boolean inProgress = false;
            if (pickedEntityIds.size() < returnLimit) {
                inProgress = getNextMatchingEntity(templateRoot, delegator, env);
            }
            FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
            if (inProgress) {
                return TransformControl.EVALUATE_BODY;
            }
            return TransformControl.SKIP_BODY;
        }

        @Override
        public int afterBody() throws TemplateModelException, IOException {
            FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
            List<Map<String, ? extends Object>> list = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
            List<Map<String, ? extends Object>> subList = list.subList(0, list.size() - 1);
            templateRoot.put("globalNodeTrail", subList);
            env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(subList, env));
            boolean inProgress = false;
            if (pickedEntityIds.size() < returnLimit) {
                inProgress = getNextMatchingEntity(templateRoot, delegator, env);
            }
            FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
            if (inProgress) {
                return TransformControl.REPEAT_EVALUATION;
            }
            return TransformControl.END_EVALUATION;
        }

        @Override
        public void close() throws IOException {
            FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
            String wrappedContent = buf.toString();
            out.write(wrappedContent);
        }

        public boolean prepCtx(Delegator delegator, Map<String, Object> ctx, Environment env, GenericValue view) throws GeneralException {
            String subContentIdSub = (String) view.get("contentId");
            // This order is taken so that the dataResourceType can be overridden in the transform arguments.
            String subDataResourceTypeId = (String) ctx.get("subDataResourceTypeId");
            if (UtilValidate.isEmpty(subDataResourceTypeId)) {
                subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
            // TODO: If this value is still empty then it is probably necessary to get a value from
            // the parent context. But it will already have one and it is the same context that is
            // being passed.
            }
            String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, ctx);
            Map<String, Object> trailNode = ContentWorker.makeNode(view);
            Map<String, Object> whenMap = UtilGenerics.checkMap(ctx.get("whenMap"));
            ContentWorker.checkConditions(delegator, trailNode, null, whenMap);
            Boolean isReturnBeforeObj = (Boolean) trailNode.get("isReturnBefore");
            Boolean isPickObj = (Boolean) trailNode.get("isPick");
            Boolean isFollowObj = (Boolean) trailNode.get("isFollow");
            if ((isReturnBeforeObj == null || !isReturnBeforeObj.booleanValue()) && ((isPickObj != null && isPickObj.booleanValue()) || (isFollowObj != null && isFollowObj.booleanValue()))) {
                List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(ctx.get("globalNodeTrail"));
                if (globalNodeTrail == null) {
                    globalNodeTrail = new LinkedList<>();
                }
                globalNodeTrail.add(trailNode);
                ctx.put("globalNodeTrail", globalNodeTrail);
                String csvTrail = ContentWorker.nodeTrailToCsv(globalNodeTrail);
                ctx.put("nodeTrailCsv", csvTrail);
                int indentSz = globalNodeTrail.size();
                ctx.put("indent", Integer.valueOf(indentSz));
                ctx.put("subDataResourceTypeId", subDataResourceTypeId);
                ctx.put("mimeTypeId", mimeTypeId);
                ctx.put("subContentId", subContentIdSub);
                ctx.put("content", view);
                env.setVariable("subDataResourceTypeId", FreeMarkerWorker.autoWrap(subDataResourceTypeId, env));
                env.setVariable("indent", FreeMarkerWorker.autoWrap(Integer.valueOf(indentSz), env));
                env.setVariable("nodeTrailCsv", FreeMarkerWorker.autoWrap(csvTrail, env));
                env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(globalNodeTrail, env));
                env.setVariable("content", FreeMarkerWorker.autoWrap(view, env));
                env.setVariable("mimeTypeId", FreeMarkerWorker.autoWrap(mimeTypeId, env));
                env.setVariable("subContentId", FreeMarkerWorker.autoWrap(subContentIdSub, env));
                return true;
            }
            return false;
        }

        public GenericValue getRandomEntity() {
            GenericValue pickEntity = null;
            List<GenericValue> lst = UtilGenerics.checkList(templateRoot.get("entityList"));
            if (Debug.verboseOn()) {
                Debug.logVerbose("in limited, lst:" + lst, "");
            }
            while (pickEntity == null && lst.size() > 0) {
                double randomValue = Math.random();
                int idx = (int) (lst.size() * randomValue);
                pickEntity = lst.get(idx);
                String pickEntityId = pickEntity.getString("contentId");
                if (pickedEntityIds.get(pickEntityId) == null) {
                    pickedEntityIds.put(pickEntityId, pickEntity);
                    lst.remove(idx);
                } else {
                    pickEntity = null;
                }
            }
            return pickEntity;
        }

        public boolean getNextMatchingEntity(Map<String, Object> templateRoot, Delegator delegator, Environment env) throws IOException {
            boolean matchFound = false;
            GenericValue pickEntity = getRandomEntity();
            while (pickEntity != null && !matchFound) {
                try {
                    matchFound = prepCtx(delegator, templateRoot, env, pickEntity);
                } catch (GeneralException e) {
                    throw new IOException(e.getMessage());
                }
                if (!matchFound) {
                    pickEntity = getRandomEntity();
                }
            }
            return matchFound;
        }
    };
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) HttpServletRequest(javax.servlet.http.HttpServletRequest) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) IOException(java.io.IOException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 12 with MiniLangException

use of org.apache.ofbiz.minilang.MiniLangException in project ofbiz-framework by apache.

the class ContentWorker method getSubContentCache.

public static GenericValue getSubContentCache(Delegator delegator, String contentId, String mapKey, GenericValue userLogin, List<String> assocTypes, Timestamp fromDate, Boolean nullThruDatesOnly, String contentAssocPredicateId) throws GenericEntityException {
    GenericValue view = null;
    if (contentId == null) {
        Debug.logError("ContentId is null", module);
        return view;
    }
    Map<String, Object> results = null;
    List<String> contentTypes = null;
    try {
        // NOTE DEJ20060610: Changed "From" to "To" because it makes the most sense for sub-content renderings using a root-contentId and mapKey to determine the sub-contentId to have the ContentAssoc go from the root to the sub, ie try to determine the contentIdTo from the contentId and mapKey
        // This shouldn't be changed from "To" to "From", but if desired could be parameterized to make this selectable in higher up calling methods
        results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, mapKey, "To", fromDate, null, assocTypes, contentTypes, nullThruDatesOnly, contentAssocPredicateId, null);
    } catch (MiniLangException e) {
        throw new RuntimeException(e.getMessage());
    }
    List<GenericValue> entityList = UtilGenerics.checkList(results.get("entityList"));
    if (UtilValidate.isEmpty(entityList)) {
    // throw new IOException("No subcontent found.");
    } else {
        view = entityList.get(0);
    }
    return view;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) MiniLangException(org.apache.ofbiz.minilang.MiniLangException)

Example 13 with MiniLangException

use of org.apache.ofbiz.minilang.MiniLangException in project ofbiz-framework by apache.

the class LayoutEvents method cloneLayout.

public static String cloneLayout(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    HttpSession session = request.getSession();
    Locale locale = UtilHttp.getLocale(request);
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    String contentId = (String) paramMap.get("contentId");
    if (Debug.verboseOn())
        Debug.logVerbose("in cloneLayout, contentId:" + contentId, "");
    if (UtilValidate.isEmpty(contentId)) {
        String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.content_id_empty", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String contentIdTo = (String) paramMap.get("contentIdTo");
    if (Debug.verboseOn())
        Debug.logVerbose("in cloneLayout, contentIdTo:" + contentIdTo, "");
    GenericValue content = null;
    GenericValue newContent = null;
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    String userLoginId = (String) userLogin.get("userLoginId");
    List<GenericValue> entityList = null;
    String newId = null;
    String newDataResourceId = null;
    try {
        content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
        if (Debug.verboseOn())
            Debug.logVerbose("in cloneLayout, content:" + content, "");
        if (content == null) {
            String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.content_empty", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        newContent = delegator.makeValue("Content", content);
        if (Debug.verboseOn())
            Debug.logVerbose("in cloneLayout, newContent:" + newContent, "");
        String oldName = (String) content.get("contentName");
        newId = delegator.getNextSeqId("Content");
        newContent.set("contentId", newId);
        String dataResourceId = (String) content.get("dataResourceId");
        GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
        if (dataResource != null) {
            GenericValue newDataResource = delegator.makeValue("DataResource", dataResource);
            if (Debug.verboseOn())
                Debug.logVerbose("in cloneLayout, newDataResource:" + newDataResource, "");
            String dataResourceName = "Copy:" + (String) dataResource.get("dataResourceName");
            newDataResource.set("dataResourceName", dataResourceName);
            newDataResourceId = delegator.getNextSeqId("DataResource");
            newDataResource.set("dataResourceId", newDataResourceId);
            newDataResource.set("createdDate", UtilDateTime.nowTimestamp());
            newDataResource.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            newDataResource.set("createdByUserLogin", userLoginId);
            newDataResource.set("lastModifiedByUserLogin", userLoginId);
            newDataResource.create();
        }
        newContent.set("contentName", "Copy - " + oldName);
        newContent.set("createdDate", UtilDateTime.nowTimestamp());
        newContent.set("lastModifiedDate", UtilDateTime.nowTimestamp());
        newContent.set("createdByUserLogin", userLoginId);
        newContent.set("lastModifiedByUserLogin", userLoginId);
        newContent.create();
        if (Debug.verboseOn())
            Debug.logVerbose("in cloneLayout, newContent:" + newContent, "");
        GenericValue newContentAssoc = delegator.makeValue("ContentAssoc");
        newContentAssoc.set("contentId", newId);
        newContentAssoc.set("contentIdTo", "TEMPLATE_MASTER");
        newContentAssoc.set("contentAssocTypeId", "SUB_CONTENT");
        newContentAssoc.set("fromDate", UtilDateTime.nowTimestamp());
        newContentAssoc.create();
        if (Debug.verboseOn())
            Debug.logVerbose("in cloneLayout, newContentAssoc:" + newContentAssoc, "");
    } catch (GenericEntityException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }
    Map<String, Object> serviceIn = new HashMap<String, Object>();
    Map<String, Object> results = null;
    serviceIn.put("fromDate", UtilDateTime.nowTimestamp());
    serviceIn.put("contentId", contentId);
    serviceIn.put("userLogin", session.getAttribute("userLogin"));
    serviceIn.put("direction", "From");
    serviceIn.put("thruDate", null);
    serviceIn.put("assocTypes", UtilMisc.toList("SUB_CONTENT"));
    try {
        results = dispatcher.runSync("getAssocAndContentAndDataResource", serviceIn);
        if (ServiceUtil.isError(results)) {
            String errorMessage = ServiceUtil.getErrorMessage(results);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            return "error";
        }
        entityList = UtilGenerics.checkList(results.get("entityList"));
        if (UtilValidate.isEmpty(entityList)) {
            String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.no_subcontent", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
        }
    } catch (GenericServiceException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }
    serviceIn = new HashMap<String, Object>();
    serviceIn.put("userLogin", session.getAttribute("userLogin"));
    // Can't count on records being unique
    Map<String, GenericValue> beenThere = new HashMap<String, GenericValue>();
    for (int i = 0; i < entityList.size(); i++) {
        GenericValue view = entityList.get(i);
        List<Object> errorMessages = new LinkedList<Object>();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        try {
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", view, serviceIn, errorMessages, locale);
        } catch (IllegalArgumentException e) {
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        } catch (MiniLangException e) {
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        String contentIdFrom = (String) view.get("contentId");
        String mapKey = (String) view.get("caMapKey");
        Timestamp fromDate = (Timestamp) view.get("caFromDate");
        Timestamp thruDate = (Timestamp) view.get("caThruDate");
        if (Debug.verboseOn())
            Debug.logVerbose("in cloneLayout, contentIdFrom:" + contentIdFrom + " fromDate:" + fromDate + " thruDate:" + thruDate + " mapKey:" + mapKey, "");
        if (beenThere.get(contentIdFrom) == null) {
            serviceIn.put("contentIdFrom", contentIdFrom);
            serviceIn.put("contentIdTo", newId);
            serviceIn.put("fromDate", UtilDateTime.nowTimestamp());
            serviceIn.put("thruDate", null);
            try {
                results = dispatcher.runSync("persistContentAndAssoc", serviceIn);
                if (ServiceUtil.isError(results)) {
                    String errorMessage = ServiceUtil.getErrorMessage(results);
                    request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                    Debug.logError(errorMessage, module);
                    return "error";
                }
            } catch (GenericServiceException e) {
                request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
                return "error";
            }
            beenThere.put(contentIdFrom, view);
        }
    }
    GenericValue view = delegator.makeValue("ContentDataResourceView");
    view.set("contentId", newId);
    view.set("drDataResourceId", newDataResourceId);
    if (Debug.verboseOn())
        Debug.logVerbose("in cloneLayout, view:" + view, "");
    ContentManagementWorker.setCurrentEntityMap(request, view);
    request.setAttribute("contentId", view.get("contentId"));
    request.setAttribute("drDataResourceId", view.get("drDataResourceId"));
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 14 with MiniLangException

use of org.apache.ofbiz.minilang.MiniLangException in project ofbiz-framework by apache.

the class LayoutEvents method updateLayoutSubContent.

public static String updateLayoutSubContent(HttpServletRequest request, HttpServletResponse response) {
    try {
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        HttpSession session = request.getSession();
        Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
        Map<String, Object> context = new HashMap<String, Object>();
        List<Object> errorMessages = new LinkedList<>();
        Locale loc = (Locale) request.getSession().getServletContext().getAttribute("locale");
        if (loc == null) {
            loc = Locale.getDefault();
        }
        context.put("locale", loc);
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        context.put("userLogin", userLogin);
        String rootDir = request.getSession().getServletContext().getRealPath("/");
        context.put("rootDir", rootDir);
        try {
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", paramMap, context, errorMessages, loc);
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", paramMap, context, errorMessages, loc);
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", paramMap, context, errorMessages, loc);
        } catch (MiniLangException e) {
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        context.put("dataResourceName", context.get("contentName"));
        String contentPurposeTypeId = (String) paramMap.get("contentPurposeTypeId");
        if (UtilValidate.isNotEmpty(contentPurposeTypeId)) {
            context.put("contentPurposeList", UtilMisc.toList(contentPurposeTypeId));
        }
        context.put("contentIdTo", paramMap.get("contentIdTo"));
        context.put("textData", paramMap.get("textData"));
        context.put("contentAssocTypeId", null);
        Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
        if (ServiceUtil.isError(result)) {
            String errorMessage = ServiceUtil.getErrorMessage(result);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            return "error";
        }
        String contentId = (String) result.get("contentId");
        String dataResourceId = (String) result.get("dataResourceId");
        request.setAttribute("contentId", contentId);
        request.setAttribute("drDataResourceId", dataResourceId);
        request.setAttribute("currentEntityName", "SubContentDataResourceId");
    } catch (GenericServiceException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) LinkedList(java.util.LinkedList)

Example 15 with MiniLangException

use of org.apache.ofbiz.minilang.MiniLangException in project ofbiz-framework by apache.

the class LayoutEvents method createLayoutImage.

public static String createLayoutImage(HttpServletRequest request, HttpServletResponse response) {
    Locale locale = UtilHttp.getLocale(request);
    try {
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        HttpSession session = request.getSession();
        Map<String, Object> uploadResults = LayoutWorker.uploadImageAndParameters(request, "imageData");
        Map<String, Object> formInput = UtilGenerics.checkMap(uploadResults.get("formInput"));
        Map<String, Object> context = new HashMap<String, Object>();
        ByteBuffer byteWrap = (ByteBuffer) uploadResults.get("imageData");
        if (byteWrap == null) {
            String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.image_data_null", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        String imageFileName = (String) uploadResults.get("imageFileName");
        String imageFileNameExt = null;
        if (UtilValidate.isNotEmpty(imageFileName)) {
            int pos = imageFileName.lastIndexOf('.');
            if (pos >= 0) {
                imageFileNameExt = imageFileName.substring(pos + 1);
            }
        }
        String mimeTypeId = "image/" + imageFileNameExt;
        List<Object> errorMessages = new LinkedList<Object>();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        context.put("locale", locale);
        try {
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", formInput, context, errorMessages, locale);
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", formInput, context, errorMessages, locale);
            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", formInput, context, errorMessages, locale);
        } catch (MiniLangException e) {
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        context.put("dataResourceName", context.get("contentName"));
        context.put("userLogin", session.getAttribute("userLogin"));
        context.put("dataResourceTypeId", "IMAGE_OBJECT");
        context.put("contentAssocTypeId", "SUB_CONTENT");
        context.put("contentTypeId", "DOCUMENT");
        context.put("contentIdTo", formInput.get("contentIdTo"));
        context.put("textData", formInput.get("textData"));
        String contentPurposeTypeId = (String) formInput.get("contentPurposeTypeId");
        if (UtilValidate.isNotEmpty(contentPurposeTypeId)) {
            context.put("contentPurposeList", UtilMisc.toList(contentPurposeTypeId));
        }
        Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
        if (ServiceUtil.isError(result)) {
            String errorMessage = ServiceUtil.getErrorMessage(result);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            return "error";
        }
        String dataResourceId = (String) result.get("dataResourceId");
        String activeContentId = (String) result.get("contentId");
        if (UtilValidate.isNotEmpty(activeContentId)) {
            Map<String, Object> context2 = new HashMap<String, Object>();
            context2.put("activeContentId", activeContentId);
            context2.put("contentAssocTypeId", result.get("contentAssocTypeId"));
            context2.put("fromDate", result.get("fromDate"));
            request.setAttribute("contentId", result.get("contentId"));
            request.setAttribute("drDataResourceId", dataResourceId);
            request.setAttribute("currentEntityName", "SubContentDataResourceId");
            context2.put("contentIdTo", formInput.get("contentIdTo"));
            context2.put("mapKey", formInput.get("mapKey"));
            Map<String, Object> serviceResult = new HashMap<String, Object>();
            serviceResult = dispatcher.runSync("deactivateAssocs", context2);
            if (ServiceUtil.isError(serviceResult)) {
                String errorMessage = ServiceUtil.getErrorMessage(serviceResult);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                return "error";
            }
        }
        GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
        // place in ImageDataResource for it.
        if (dataResource != null) {
            dataResource.set("objectInfo", imageFileName);
            dataResource.set("mimeTypeId", mimeTypeId);
            dataResource.store();
        }
        // See if this needs to be a create or an update procedure
        GenericValue imageDataResource = EntityQuery.use(delegator).from("ImageDataResource").where("dataResourceId", dataResourceId).queryOne();
        if (imageDataResource == null) {
            imageDataResource = delegator.makeValue("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
            imageDataResource.set("imageData", byteWrap.array());
            imageDataResource.create();
        } else {
            imageDataResource.set("imageData", byteWrap.array());
            imageDataResource.store();
        }
    } catch (GenericEntityException e3) {
        request.setAttribute("_ERROR_MESSAGE_", e3.getMessage());
        return "error";
    } catch (GenericServiceException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

MiniLangException (org.apache.ofbiz.minilang.MiniLangException)27 GenericValue (org.apache.ofbiz.entity.GenericValue)13 Locale (java.util.Locale)9 HashMap (java.util.HashMap)8 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)8 MiniLangRuntimeException (org.apache.ofbiz.minilang.MiniLangRuntimeException)8 LinkedList (java.util.LinkedList)7 Delegator (org.apache.ofbiz.entity.Delegator)7 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)6 HttpSession (javax.servlet.http.HttpSession)5 SimpleMethod (org.apache.ofbiz.minilang.SimpleMethod)5 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)5 Timestamp (java.sql.Timestamp)4 Map (java.util.Map)4 IOException (java.io.IOException)3 MethodOperation (org.apache.ofbiz.minilang.method.MethodOperation)3 BreakElementException (org.apache.ofbiz.minilang.method.envops.Break.BreakElementException)3 ContinueElementException (org.apache.ofbiz.minilang.method.envops.Continue.ContinueElementException)3 FileNotFoundException (java.io.FileNotFoundException)2 HashSet (java.util.HashSet)2