Search in sources :

Example 1 with LoopWriter

use of org.apache.ofbiz.webapp.ftl.LoopWriter 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 2 with LoopWriter

use of org.apache.ofbiz.webapp.ftl.LoopWriter in project ofbiz-framework by apache.

the class InjectNodeTrailCsvTransform 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> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    FreeMarkerWorker.getSiteParameters(request, templateCtx);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    return new LoopWriter(out) {

        final String passedCsv = (String) templateCtx.get("nodeTrailCsv");

        @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 {
            String csvTrail = null;
            List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
            if (Debug.infoOn()) {
                Debug.logInfo("in InjectNodeTrailCsv(0), trail:" + trail, module);
            }
            // This will build a nodeTrail if none exists
            // Maybe only contentId or subContentId are passed in
            String redo = (String) templateCtx.get("redo");
            if (UtilValidate.isEmpty(trail) || (redo != null && "true".equalsIgnoreCase(redo))) {
                String subContentId = (String) templateCtx.get("subContentId");
                if (Debug.infoOn()) {
                    Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:" + subContentId, module);
                }
                String contentId = (String) templateCtx.get("contentId");
                if (Debug.infoOn()) {
                    Debug.logInfo("in InjectNodeTrailCsv(0), contentId:" + contentId, module);
                }
                String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
                if (Debug.infoOn()) {
                    Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:" + contentAssocTypeId, module);
                }
                try {
                    if (UtilValidate.isNotEmpty(subContentId)) {
                        csvTrail = ContentWorker.getContentAncestryNodeTrailCsv(delegator, subContentId, contentAssocTypeId, "to");
                        if (UtilValidate.isNotEmpty(csvTrail)) {
                            csvTrail += ",";
                        }
                        csvTrail += subContentId;
                    } else if (UtilValidate.isNotEmpty(contentId)) {
                        csvTrail = ContentWorker.getContentAncestryNodeTrailCsv(delegator, contentId, contentAssocTypeId, "to");
                        if (UtilValidate.isNotEmpty(csvTrail)) {
                            csvTrail += ",";
                        }
                        csvTrail += contentId;
                    }
                } catch (GenericEntityException e) {
                    throw new RuntimeException("Error getting current content. " + e.toString());
                }
                if (Debug.infoOn()) {
                    Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:" + csvTrail, module);
                }
            } else {
                // Build nodeTrail if one does not exist
                if (UtilValidate.isNotEmpty(passedCsv)) {
                    csvTrail = passedCsv;
                    int lastComma = passedCsv.lastIndexOf(',');
                    String lastPassedContentId = null;
                    if (lastComma >= 0) {
                        lastPassedContentId = passedCsv.substring(lastComma + 1);
                    } else {
                        lastPassedContentId = passedCsv;
                    }
                    if (UtilValidate.isNotEmpty(lastPassedContentId)) {
                        if (UtilValidate.isNotEmpty(trail)) {
                            Map<String, ? extends Object> nd = trail.get(0);
                            String firstTrailContentId = (String) nd.get("contentId");
                            if (UtilValidate.isNotEmpty(firstTrailContentId) && UtilValidate.isNotEmpty(lastPassedContentId) && firstTrailContentId.equals(lastPassedContentId)) {
                                csvTrail += "," + ContentWorker.nodeTrailToCsv(trail.subList(1, trail.size()));
                            } else {
                                csvTrail += "," + ContentWorker.nodeTrailToCsv(trail);
                            }
                        }
                    }
                } else {
                    csvTrail = ContentWorker.nodeTrailToCsv(trail);
                }
            }
            templateCtx.put("nodeTrailCsv", csvTrail);
            return TransformControl.EVALUATE_BODY;
        }

        @Override
        public void close() throws IOException {
            templateCtx.put("nodeTrailCsv", passedCsv);
            String wrappedContent = buf.toString();
            out.write(wrappedContent);
        }
    };
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) Map(java.util.Map)

Example 3 with LoopWriter

use of org.apache.ofbiz.webapp.ftl.LoopWriter in project ofbiz-framework by apache.

the class LoopSubContentTransform 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> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
    if (UtilValidate.isEmpty(contentAssocTypeId)) {
        contentAssocTypeId = "SUB_CONTENT";
        templateCtx.put("contentAssocTypeId ", contentAssocTypeId);
    }
    List<String> assocTypes = UtilMisc.toList(contentAssocTypeId);
    templateCtx.put("assocTypes", assocTypes);
    Locale locale = (Locale) templateCtx.get("locale");
    if (locale == null) {
        locale = Locale.getDefault();
        templateCtx.put("locale", locale);
    }
    String fromDateStr = (String) templateCtx.get("fromDateStr");
    Timestamp fromDate = null;
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        fromDate = UtilDateTime.toTimestamp(fromDateStr);
    }
    if (fromDate == null) {
        fromDate = UtilDateTime.nowTimestamp();
    }
    String thisContentId = (String) templateCtx.get("contentId");
    // DEJ20080730 Should always use contentId, not subContentId since we're searching for that and it is confusing
    String thisMapKey = (String) templateCtx.get("mapKey");
    Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceMethod(delegator, thisContentId, thisMapKey, null, fromDate, null, null, null, assocTypes, null);
    List<GenericValue> entityList = UtilGenerics.checkList(results.get("entityList"));
    templateCtx.put("entityList", entityList);
    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 {
            templateCtx.put("entityIndex", Integer.valueOf(0));
            boolean inProgress = prepCtx(delegator, templateCtx);
            if (inProgress) {
                return TransformControl.EVALUATE_BODY;
            }
            return TransformControl.SKIP_BODY;
        }

        @Override
        public int afterBody() throws TemplateModelException, IOException {
            boolean inProgress = prepCtx(delegator, templateCtx);
            if (inProgress) {
                return TransformControl.REPEAT_EVALUATION;
            }
            return TransformControl.END_EVALUATION;
        }

        @Override
        public void close() throws IOException {
            String wrappedFTL = buf.toString();
            String encloseWrappedText = (String) templateCtx.get("encloseWrappedText");
            if (UtilValidate.isEmpty(encloseWrappedText) || "false".equalsIgnoreCase(encloseWrappedText)) {
                out.write(wrappedFTL);
                // So it won't get written again below.
                wrappedFTL = "";
            }
            String wrapTemplateId = (String) templateCtx.get("wrapTemplateId");
            if (UtilValidate.isNotEmpty(wrapTemplateId)) {
                templateCtx.put("wrappedFTL", wrappedFTL);
                Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
                templateRoot.put("wrapDataResourceTypeId", templateCtx.get("subDataResourceTypeId"));
                templateRoot.put("wrapContentIdTo", templateCtx.get("contentId"));
                templateRoot.put("wrapMimeTypeId", templateCtx.get("mimeTypeId"));
                templateRoot.put("context", templateCtx);
                Locale locale = (Locale) templateCtx.get("locale");
                if (locale == null) {
                    locale = Locale.getDefault();
                }
                String mimeTypeId = (String) templateCtx.get("mimeTypeId");
                try {
                    ContentWorker.renderContentAsText(dispatcher, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true);
                } catch (GeneralException e) {
                    Debug.logError(e, "Error rendering content", module);
                    throw new IOException("Error rendering content" + e.toString());
                }
            } else {
                if (UtilValidate.isNotEmpty(wrappedFTL)) {
                    out.write(wrappedFTL);
                }
            }
            FreeMarkerWorker.removeValues(templateCtx, removeKeyNames);
            FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
        }
    };
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) Delegator(org.apache.ofbiz.entity.Delegator) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) Environment(freemarker.core.Environment)

Example 4 with LoopWriter

use of org.apache.ofbiz.webapp.ftl.LoopWriter in project ofbiz-framework by apache.

the class TraverseSubContentCacheTransform method getWriter.

@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 Map<String, Object> savedValuesUp = new HashMap<String, Object>();
    FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
    final Map<String, Object> savedValues = new HashMap<String, Object>();
    FreeMarkerWorker.overrideWithArgs(templateRoot, args);
    String startContentAssocTypeId = (String) templateRoot.get("contentAssocTypeId");
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    FreeMarkerWorker.getSiteParameters(request, templateRoot);
    final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
    String strNullThruDatesOnly = (String) templateRoot.get("nullThruDatesOnly");
    String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId");
    Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE;
    try {
        // getCurrentContent puts the "current" node on the end of globalNodeTrail.
        // It may have already been there, but getCurrentContent will compare its contentId
        // to values in templateRoot.
        ContentWorker.getCurrentContent(delegator, globalNodeTrail, userLogin, templateRoot, nullThruDatesOnly, contentAssocPredicateId);
    } catch (GeneralException e) {
        throw new RuntimeException("Error getting current content. " + e.toString());
    }
    final Map<String, Object> traverseContext = new HashMap<String, Object>();
    traverseContext.put("delegator", delegator);
    Map<String, Object> whenMap = new HashMap<String, Object>();
    whenMap.put("followWhen", templateRoot.get("followWhen"));
    whenMap.put("pickWhen", templateRoot.get("pickWhen"));
    whenMap.put("returnBeforePickWhen", templateRoot.get("returnBeforePickWhen"));
    whenMap.put("returnAfterPickWhen", templateRoot.get("returnAfterPickWhen"));
    traverseContext.put("whenMap", whenMap);
    env.setVariable("whenMap", FreeMarkerWorker.autoWrap(whenMap, env));
    String fromDateStr = (String) templateRoot.get("fromDateStr");
    String thruDateStr = (String) templateRoot.get("thruDateStr");
    Timestamp fromDate = null;
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        fromDate = UtilDateTime.toTimestamp(fromDateStr);
    }
    traverseContext.put("fromDate", fromDate);
    Timestamp thruDate = null;
    if (UtilValidate.isNotEmpty(thruDateStr)) {
        thruDate = UtilDateTime.toTimestamp(thruDateStr);
    }
    traverseContext.put("thruDate", thruDate);
    traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
    String direction = (String) templateRoot.get("direction");
    if (UtilValidate.isEmpty(direction)) {
        direction = "From";
    }
    traverseContext.put("direction", direction);
    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 {
            List<Map<String, ? extends Object>> nodeTrail = null;
            Map<String, Object> node = null;
            List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
            if (globalNodeTrail.size() > 0) {
                int sz = globalNodeTrail.size();
                nodeTrail = new LinkedList<Map<String, ? extends Object>>();
                node = UtilGenerics.checkMap(globalNodeTrail.get(sz - 1));
                Boolean checkedObj = (Boolean) node.get("checked");
                Map<String, Object> whenMap = UtilGenerics.checkMap(templateRoot.get("whenMap"));
                if (checkedObj == null || !checkedObj.booleanValue()) {
                    ContentWorker.checkConditions(delegator, node, null, whenMap);
                }
            } else {
                throw new IOException("Empty node trail entries");
            }
            Boolean isReturnBeforePickBool = (Boolean) node.get("isReturnBeforePick");
            if (isReturnBeforePickBool != null && isReturnBeforePickBool.booleanValue()) {
                return TransformControl.SKIP_BODY;
            }
            ContentWorker.selectKids(node, traverseContext);
            nodeTrail.add(node);
            traverseContext.put("nodeTrail", nodeTrail);
            Boolean isPickBool = (Boolean) node.get("isPick");
            Boolean isFollowBool = (Boolean) node.get("isFollow");
            boolean isPick = true;
            if ((isPickBool == null || !isPickBool.booleanValue()) && (isFollowBool != null && isFollowBool.booleanValue())) {
                isPick = ContentWorker.traverseSubContent(traverseContext);
            }
            if (isPick) {
                populateContext(traverseContext, templateRoot);
                FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
                return TransformControl.EVALUATE_BODY;
            } else {
                return TransformControl.SKIP_BODY;
            }
        }

        @Override
        public int afterBody() throws TemplateModelException, IOException {
            FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
            boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
            if (inProgress) {
                populateContext(traverseContext, templateRoot);
                FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
                return TransformControl.REPEAT_EVALUATION;
            } else {
                return TransformControl.END_EVALUATION;
            }
        }

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

        public void populateContext(Map<String, Object> traverseContext, Map<String, Object> templateContext) {
            List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
            int sz = nodeTrail.size();
            Map<String, ? extends Object> node = nodeTrail.get(sz - 1);
            GenericValue content = (GenericValue) node.get("value");
            String contentId = (String) node.get("contentId");
            String contentAssocTypeId = (String) node.get("contentAssocTypeId");
            envWrap("contentAssocTypeId", contentAssocTypeId);
            envWrap("contentId", contentId);
            envWrap("content", content);
            String mapKey = (String) node.get("mapKey");
            envWrap("mapKey", mapKey);
            envWrap("subContentDataResourceView", null);
            List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateContext.get("nodeTrail"));
            String contentIdEnd = null;
            String contentIdStart = null;
            if (globalNodeTrail != null) {
                Map<String, ? extends Object> ndEnd = globalNodeTrail.get(globalNodeTrail.size() - 1);
                contentIdEnd = (String) ndEnd.get("contentId");
                Map<String, ? extends Object> ndStart = nodeTrail.get(0);
                contentIdStart = (String) ndStart.get("contentId");
            } else {
                globalNodeTrail = new LinkedList<Map<String, ? extends Object>>();
                contentIdStart = "";
            }
            boolean bIdEnd = UtilValidate.isNotEmpty(contentIdEnd);
            boolean bIdStart = UtilValidate.isNotEmpty(contentIdStart);
            boolean bEquals = contentIdStart.equals(contentIdEnd);
            if (bIdEnd && bIdStart && bEquals) {
                List<Map<String, ? extends Object>> subList = nodeTrail.subList(1, sz);
                globalNodeTrail.addAll(subList);
            } else {
                globalNodeTrail.addAll(nodeTrail);
            }
            int indentSz = globalNodeTrail.size();
            envWrap("indent", Integer.valueOf(indentSz));
            String trailCsv = ContentWorker.nodeTrailToCsv(globalNodeTrail);
            envWrap("nodeTrailCsv", trailCsv);
            envWrap("globalNodeTrail", globalNodeTrail);
        }

        public void envWrap(String varName, Object obj) {
            templateRoot.put(varName, obj);
            env.setVariable(varName, FreeMarkerWorker.autoWrap(obj, env));
        }
    };
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) Environment(freemarker.core.Environment) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with LoopWriter

use of org.apache.ofbiz.webapp.ftl.LoopWriter in project ofbiz-framework by apache.

the class CheckPermissionTransform 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> templateCtx = FreeMarkerWorker.createEnvironmentMap(env);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    FreeMarkerWorker.getSiteParameters(request, templateCtx);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    final String mode = (String) templateCtx.get("mode");
    final String quickCheckContentId = (String) templateCtx.get("quickCheckContentId");
    final Map<String, Object> savedValues = new HashMap<>();
    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 {
            List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
            GenericValue currentContent = null;
            String contentAssocPredicateId = (String) templateCtx.get("contentAssocPredicateId");
            String strNullThruDatesOnly = (String) templateCtx.get("nullThruDatesOnly");
            Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE;
            GenericValue val = null;
            try {
                val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
            } catch (GeneralException e) {
                throw new RuntimeException("Error getting current content. " + e.toString());
            }
            currentContent = val;
            if (currentContent == null) {
                currentContent = delegator.makeValue("Content");
                currentContent.put("ownerContentId", templateCtx.get("ownerContentId"));
            }
            Security security = null;
            if (request != null) {
                security = (Security) request.getAttribute("security");
            }
            String statusId = (String) currentContent.get("statusId");
            String passedStatusId = (String) templateCtx.get("statusId");
            List<String> statusList = StringUtil.split(passedStatusId, "|");
            if (statusList == null) {
                statusList = new LinkedList<>();
            }
            if (UtilValidate.isNotEmpty(statusId) && !statusList.contains(statusId)) {
                statusList.add(statusId);
            }
            String targetPurpose = (String) templateCtx.get("contentPurposeList");
            List<String> purposeList = StringUtil.split(targetPurpose, "|");
            String entityOperation = (String) templateCtx.get("entityOperation");
            String targetOperation = (String) templateCtx.get("targetOperation");
            if (UtilValidate.isEmpty(targetOperation)) {
                if (UtilValidate.isNotEmpty(entityOperation)) {
                    targetOperation = "CONTENT" + entityOperation;
                }
            }
            List<String> targetOperationList = StringUtil.split(targetOperation, "|");
            if (targetOperationList.size() == 0) {
                throw new IOException("targetOperationList has zero size.");
            }
            List<String> roleList = new LinkedList<>();
            String privilegeEnumId = (String) currentContent.get("privilegeEnumId");
            Map<String, Object> results = EntityPermissionChecker.checkPermission(currentContent, statusList, userLogin, purposeList, targetOperationList, roleList, delegator, security, entityOperation, privilegeEnumId, quickCheckContentId);
            boolean isError = ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                throw new IOException(ModelService.RESPONSE_MESSAGE);
            }
            String permissionStatus = (String) results.get("permissionStatus");
            if (UtilValidate.isEmpty(permissionStatus) || !"granted".equals(permissionStatus)) {
                String errorMessage = "Permission to add response is denied (2)";
                PermissionRecorder recorder = (PermissionRecorder) results.get("permissionRecorder");
                if (recorder != null) {
                    String permissionMessage = recorder.toHtml();
                    errorMessage += " \n " + permissionMessage;
                }
                templateCtx.put("permissionErrorMsg", errorMessage);
            }
            if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) {
                FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
                if (mode == null || !"not-equals".equalsIgnoreCase(mode)) {
                    return TransformControl.EVALUATE_BODY;
                }
                return TransformControl.SKIP_BODY;
            }
            if (mode == null || !"not-equals".equalsIgnoreCase(mode)) {
                return TransformControl.SKIP_BODY;
            }
            return TransformControl.EVALUATE_BODY;
        }

        @Override
        public void close() throws IOException {
            FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
            String wrappedContent = buf.toString();
            out.write(wrappedContent);
        }
    };
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) IOException(java.io.IOException) Security(org.apache.ofbiz.security.Security) PermissionRecorder(org.apache.ofbiz.content.content.PermissionRecorder) LinkedList(java.util.LinkedList) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) Environment(freemarker.core.Environment) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Environment (freemarker.core.Environment)7 Delegator (org.apache.ofbiz.entity.Delegator)7 LoopWriter (org.apache.ofbiz.webapp.ftl.LoopWriter)7 IOException (java.io.IOException)6 Map (java.util.Map)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)6 GenericValue (org.apache.ofbiz.entity.GenericValue)6 HashMap (java.util.HashMap)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 Timestamp (java.sql.Timestamp)4 Locale (java.util.Locale)3 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)3 LinkedList (java.util.LinkedList)2 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 PermissionRecorder (org.apache.ofbiz.content.content.PermissionRecorder)1 MiniLangException (org.apache.ofbiz.minilang.MiniLangException)1 Security (org.apache.ofbiz.security.Security)1 HtmlMenuWrapper (org.apache.ofbiz.widget.renderer.html.HtmlMenuWrapper)1