Search in sources :

Example 6 with LoopWriter

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

the class TraverseSubContentTransform 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> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    GenericValue view = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
    final Integer indent = (templateCtx.get("indent") == null) ? Integer.valueOf(0) : (Integer) templateCtx.get("indent");
    String contentId = (String) templateCtx.get("contentId");
    String subContentId = (String) templateCtx.get("subContentId");
    if (view == null) {
        String thisContentId = subContentId;
        if (UtilValidate.isEmpty(thisContentId)) {
            thisContentId = contentId;
        }
        if (UtilValidate.isNotEmpty(thisContentId)) {
            try {
                view = EntityQuery.use(delegator).from("Content").where("contentId", thisContentId).queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, "Error getting sub-content", module);
                throw new RuntimeException(e.getMessage());
            }
        }
    }
    final GenericValue subContentDataResourceView = view;
    final Map<String, Object> traverseContext = new HashMap<String, Object>();
    traverseContext.put("delegator", delegator);
    Map<String, Object> whenMap = new HashMap<String, Object>();
    whenMap.put("followWhen", templateCtx.get("followWhen"));
    whenMap.put("pickWhen", templateCtx.get("pickWhen"));
    whenMap.put("returnBeforePickWhen", templateCtx.get("returnBeforePickWhen"));
    whenMap.put("returnAfterPickWhen", templateCtx.get("returnAfterPickWhen"));
    traverseContext.put("whenMap", whenMap);
    String fromDateStr = (String) templateCtx.get("fromDateStr");
    String thruDateStr = (String) templateCtx.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);
    String startContentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
    if (startContentAssocTypeId != null)
        startContentAssocTypeId = "SUB_CONTENT";
    traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
    String direction = (String) templateCtx.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, Object>> nodeTrail = new LinkedList<Map<String, Object>>();
            traverseContext.put("nodeTrail", nodeTrail);
            Map<String, Object> rootNode = ContentWorker.makeNode(subContentDataResourceView);
            ContentWorker.traceNodeTrail("1", nodeTrail);
            ContentWorker.selectKids(rootNode, traverseContext);
            ContentWorker.traceNodeTrail("2", nodeTrail);
            nodeTrail.add(rootNode);
            boolean isPick = checkWhen(subContentDataResourceView, (String) traverseContext.get("contentAssocTypeId"));
            rootNode.put("isPick", Boolean.valueOf(isPick));
            if (!isPick) {
                ContentWorker.traceNodeTrail("3", nodeTrail);
                isPick = ContentWorker.traverseSubContent(traverseContext);
                ContentWorker.traceNodeTrail("4", nodeTrail);
            }
            if (isPick) {
                populateContext(traverseContext, templateCtx);
                ContentWorker.traceNodeTrail("5", nodeTrail);
                return TransformControl.EVALUATE_BODY;
            } else {
                return TransformControl.SKIP_BODY;
            }
        }

        @Override
        public int afterBody() throws TemplateModelException, IOException {
            List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
            ContentWorker.traceNodeTrail("6", nodeTrail);
            boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
            ContentWorker.traceNodeTrail("7", nodeTrail);
            if (inProgress) {
                populateContext(traverseContext, templateCtx);
                ContentWorker.traceNodeTrail("8", nodeTrail);
                return TransformControl.REPEAT_EVALUATION;
            } else
                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 = null;
            }
            String wrapTemplateId = (String) templateCtx.get("wrapTemplateId");
            if (UtilValidate.isNotEmpty(wrapTemplateId)) {
                templateCtx.put("wrappedFTL", wrappedFTL);
                Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
                templateRoot.put("context", templateCtx);
                String mimeTypeId = (String) templateCtx.get("mimeTypeId");
                Locale locale = (Locale) templateCtx.get("locale");
                if (locale == null)
                    locale = Locale.getDefault();
                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);
        }

        private boolean checkWhen(GenericValue thisContent, String contentAssocTypeId) {
            boolean isPick = false;
            Map<String, Object> assocContext = new HashMap<String, Object>();
            if (UtilValidate.isEmpty(contentAssocTypeId)) {
                contentAssocTypeId = "";
            }
            assocContext.put("contentAssocTypeId", contentAssocTypeId);
            String thisDirection = (String) templateCtx.get("direction");
            String thisContentId = (String) templateCtx.get("thisContentId");
            if (thisDirection != null && "From".equalsIgnoreCase(thisDirection)) {
                assocContext.put("contentIdFrom", thisContentId);
            } else {
                assocContext.put("contentIdTo", thisContentId);
            }
            assocContext.put("content", thisContent);
            List<Object> purposes = ContentWorker.getPurposes(thisContent);
            assocContext.put("purposes", purposes);
            List<String> contentTypeAncestry = new LinkedList<String>();
            String contentTypeId = (String) thisContent.get("contentTypeId");
            try {
                ContentWorker.getContentTypeAncestry(delegator, contentTypeId, contentTypeAncestry);
            } catch (GenericEntityException e) {
                return false;
            }
            assocContext.put("typeAncestry", contentTypeAncestry);
            Map<String, Object> whenMap = UtilGenerics.checkMap(traverseContext.get("whenMap"));
            List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
            int indentSz = indent.intValue() + nodeTrail.size();
            assocContext.put("indentObj", Integer.valueOf(indentSz));
            isPick = ContentWorker.checkWhen(assocContext, (String) whenMap.get("pickWhen"), true);
            return isPick;
        }

        public void populateContext(Map<String, Object> traverseContext, Map<String, Object> templateContext) {
            List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
            int sz = nodeTrail.size();
            Map<String, Object> node = nodeTrail.get(sz - 1);
            String contentId = (String) node.get("contentId");
            templateContext.put("subContentId", contentId);
            templateContext.put("subContentDataResourceView", null);
            int indentSz = indent.intValue() + nodeTrail.size();
            templateContext.put("indent", Integer.valueOf(indentSz));
            if (sz >= 2) {
                Map<String, Object> parentNode = nodeTrail.get(sz - 2);
                GenericValue parentContent = (GenericValue) parentNode.get("value");
                String parentContentId = (String) parentNode.get("contentId");
                templateContext.put("parentContentId", parentContentId);
                templateContext.put("parentContent", parentContent);
                templateContext.put("nodeTrail", nodeTrail);
            }
        }
    };
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with LoopWriter

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

the class MenuWrapTransform method getWriter.

@SuppressWarnings("rawtypes")
public Writer getWriter(final Writer out, Map args) {
    final Environment env = Environment.getCurrentEnvironment();
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
    final HttpSession session = FreeMarkerWorker.getWrappedObject("session", env);
    final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    FreeMarkerWorker.getSiteParameters(request, templateCtx);
    final Map<String, Object> savedValuesUp = new HashMap<>();
    FreeMarkerWorker.saveContextValues(templateCtx, upSaveKeyNames, savedValuesUp);
    Map<String, Object> checkedArgs = UtilGenerics.checkMap(args);
    FreeMarkerWorker.overrideWithArgs(templateCtx, checkedArgs);
    List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
    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 {
        if (WidgetContentWorker.getContentWorker() != null) {
            val = WidgetContentWorker.getContentWorker().getCurrentContentExt(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
        } else {
            Debug.logError("Not rendering content, not ContentWorker found.", module);
        }
    } catch (GeneralException e) {
        throw new RuntimeException("Error getting current content. " + e.toString());
    }
    final GenericValue view = val;
    String dataResourceId = null;
    try {
        dataResourceId = (String) view.get("drDataResourceId");
    } catch (IllegalArgumentException e) {
        dataResourceId = (String) view.get("dataResourceId");
    }
    String subContentIdSub = (String) view.get("contentId");
    // This order is taken so that the dataResourceType can be overridden in the transform arguments.
    String subDataResourceTypeId = (String) templateCtx.get("subDataResourceTypeId");
    if (UtilValidate.isEmpty(subDataResourceTypeId)) {
        try {
            subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
        } catch (IllegalArgumentException e) {
        // view may be "Content"
        }
    // 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.
    }
    // This order is taken so that the mimeType can be overridden in the transform arguments.
    String mimeTypeId = null;
    if (WidgetContentWorker.getContentWorker() != null) {
        mimeTypeId = WidgetContentWorker.getContentWorker().getMimeTypeIdExt(delegator, view, templateCtx);
    } else {
        Debug.logError("Not rendering content, not ContentWorker found.", module);
    }
    templateCtx.put("drDataResourceId", dataResourceId);
    templateCtx.put("mimeTypeId", mimeTypeId);
    templateCtx.put("dataResourceId", dataResourceId);
    templateCtx.put("subContentIdSub", subContentIdSub);
    templateCtx.put("subDataResourceTypeId", subDataResourceTypeId);
    final Map<String, Object> savedValues = new HashMap<>();
    FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
    final StringBuilder buf = new StringBuilder();
    return new LoopWriter(out) {

        @Override
        public int onStart() throws TemplateModelException, IOException {
            String renderOnStart = (String) templateCtx.get("renderOnStart");
            if (renderOnStart != null && "true".equalsIgnoreCase(renderOnStart)) {
                renderMenu();
            }
            return TransformControl.EVALUATE_BODY;
        }

        @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 void close() throws IOException {
            FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
            String wrappedContent = buf.toString();
            out.write(wrappedContent);
            String renderOnClose = (String) templateCtx.get("renderOnClose");
            if (renderOnClose == null || !"false".equalsIgnoreCase(renderOnClose)) {
                renderMenu();
            }
            FreeMarkerWorker.reloadValues(templateCtx, savedValuesUp, env);
        }

        public void renderMenu() throws IOException {
            String menuDefFile = (String) templateCtx.get("menuDefFile");
            String menuName = (String) templateCtx.get("menuName");
            String menuWrapperClassName = (String) templateCtx.get("menuWrapperClassName");
            HtmlMenuWrapper menuWrapper = HtmlMenuWrapper.getMenuWrapper(request, response, session, menuDefFile, menuName, menuWrapperClassName);
            if (menuWrapper == null) {
                throw new IOException("HtmlMenuWrapper with def file:" + menuDefFile + " menuName:" + menuName + " and HtmlMenuWrapper class:" + menuWrapperClassName + " could not be instantiated.");
            }
            String associatedContentId = (String) templateCtx.get("associatedContentId");
            menuWrapper.putInContext("defaultAssociatedContentId", associatedContentId);
            menuWrapper.putInContext("currentValue", view);
            String menuStr = menuWrapper.renderMenuString();
            out.write(menuStr);
        }
    };
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) 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) HtmlMenuWrapper(org.apache.ofbiz.widget.renderer.html.HtmlMenuWrapper)

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