Search in sources :

Example 11 with RequestHandler

use of org.apache.ofbiz.webapp.control.RequestHandler in project ofbiz-framework by apache.

the class SurveyEvents method createSurveyResponseAndRestoreParameters.

public static String createSurveyResponseAndRestoreParameters(HttpServletRequest request, HttpServletResponse response) {
    // Call createSurveyResponse as an event, easier to setup and ensures parameter security
    ConfigXMLReader.Event createSurveyResponseEvent = new ConfigXMLReader.Event("service", null, "createSurveyResponse", true);
    RequestHandler rh = (RequestHandler) request.getAttribute("_REQUEST_HANDLER_");
    ConfigXMLReader.ControllerConfig controllerConfig = rh.getControllerConfig();
    String requestUri = (String) request.getAttribute("thisRequestUri");
    RequestMap requestMap = null;
    try {
        requestMap = controllerConfig.getRequestMapMap().get(requestUri);
    } catch (WebAppConfigurationException e) {
        Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
    }
    String eventResponse = null;
    try {
        eventResponse = rh.runEvent(request, response, createSurveyResponseEvent, requestMap, null);
    } catch (EventHandlerException e) {
        Debug.logError(e, module);
        return "error";
    }
    if (!"success".equals(eventResponse)) {
        return eventResponse;
    }
    // Check for an incoming _ORIG_PARAM_MAP_ID_, if present get the session stored parameter map and insert it's entries as request attributes
    Map<String, Object> combinedMap = UtilHttp.getCombinedMap(request);
    if (combinedMap.containsKey("_ORIG_PARAM_MAP_ID_")) {
        String origParamMapId = (String) combinedMap.get("_ORIG_PARAM_MAP_ID_");
        UtilHttp.restoreStashedParameterMap(request, origParamMapId);
    }
    return "success";
}
Also used : ConfigXMLReader(org.apache.ofbiz.webapp.control.ConfigXMLReader) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) EventHandlerException(org.apache.ofbiz.webapp.event.EventHandlerException) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException)

Example 12 with RequestHandler

use of org.apache.ofbiz.webapp.control.RequestHandler in project ofbiz-framework by apache.

the class CmsEvents method cms.

public static String cms(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ServletContext servletContext = request.getSession().getServletContext();
    HttpSession session = request.getSession();
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    Writer writer = null;
    Locale locale = UtilHttp.getLocale(request);
    String webSiteId = (String) session.getAttribute("webSiteId");
    if (webSiteId == null) {
        webSiteId = WebSiteWorker.getWebSiteId(request);
        if (webSiteId == null) {
            request.setAttribute("_ERROR_MESSAGE_", "Not able to run CMS application; no webSiteId defined for WebApp!");
            return "error";
        }
    }
    // is this a default request or called from a defined request mapping
    String targetRequest = (String) request.getAttribute("targetRequestUri");
    String actualRequest = (String) request.getAttribute("thisRequestUri");
    if (targetRequest != null) {
        targetRequest = targetRequest.replaceAll("\\W", "");
    } else {
        targetRequest = "";
    }
    if (actualRequest != null) {
        actualRequest = actualRequest.replaceAll("\\W", "");
    } else {
        actualRequest = "";
    }
    // place holder for the content id
    String contentId = null;
    String mapKey = null;
    String pathInfo = null;
    String displayMaintenancePage = (String) session.getAttribute("displayMaintenancePage");
    if (UtilValidate.isNotEmpty(displayMaintenancePage) && "Y".equalsIgnoreCase(displayMaintenancePage)) {
        try {
            writer = response.getWriter();
            GenericValue webSiteContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "MAINTENANCE_PAGE").filterByDate().queryFirst();
            if (webSiteContent != null) {
                ContentWorker.renderContentAsText(dispatcher, webSiteContent.getString("contentId"), writer, null, locale, "text/html", null, null, true);
                return "success";
            } else {
                request.setAttribute("_ERROR_MESSAGE_", "Not able to display maintenance page for [" + webSiteId + "]");
                return "error";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        } catch (IOException e) {
            throw new GeneralRuntimeException("Error in the response writer/output stream while rendering content.", e);
        } catch (GeneralException e) {
            throw new GeneralRuntimeException("Error rendering content", e);
        }
    } else {
        // If an override view is present then use that in place of request.getPathInfo()
        String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
        if (UtilValidate.isNotEmpty(overrideViewUri)) {
            pathInfo = overrideViewUri;
        } else {
            pathInfo = request.getPathInfo();
            if (targetRequest.equals(actualRequest) && pathInfo != null) {
                // was called directly -- path info is everything after the request
                String[] pathParsed = pathInfo.split("/", 3);
                if (pathParsed.length > 2) {
                    pathInfo = pathParsed[2];
                } else {
                    pathInfo = null;
                }
            }
        // if called through the default request, there is no request in pathinfo
        }
        // if path info is null or path info is / (i.e application mounted on root); check for a default content
        if (pathInfo == null || "/".equals(pathInfo)) {
            GenericValue defaultContent = null;
            try {
                defaultContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE").orderBy("-fromDate").filterByDate().cache().queryFirst();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (defaultContent != null) {
                pathInfo = defaultContent.getString("contentId");
            }
        }
        // check for path alias first
        if (pathInfo != null) {
            // clean up the pathinfo for parsing
            pathInfo = pathInfo.trim();
            if (pathInfo.startsWith("/")) {
                pathInfo = pathInfo.substring(1);
            }
            if (pathInfo.endsWith("/")) {
                pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
            }
            GenericValue pathAlias = null;
            try {
                pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (pathAlias != null) {
                String alias = pathAlias.getString("aliasTo");
                contentId = pathAlias.getString("contentId");
                mapKey = pathAlias.getString("mapKey");
                if (contentId == null && UtilValidate.isNotEmpty(alias)) {
                    if (!alias.startsWith("/")) {
                        alias = "/" + alias;
                    }
                    RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath() + alias);
                    try {
                        rd.forward(request, response);
                    } catch (ServletException e) {
                        Debug.logError(e, module);
                        return "error";
                    } catch (IOException e) {
                        Debug.logError(e, module);
                        return "error";
                    }
                    // null to not process any views
                    return null;
                }
            }
            // get the contentId/mapKey from URL
            if (contentId == null) {
                if (Debug.verboseOn())
                    Debug.logVerbose("Current PathInfo: " + pathInfo, module);
                String[] pathSplit = pathInfo.split("/");
                if (Debug.verboseOn())
                    Debug.logVerbose("Split pathinfo: " + pathSplit.length, module);
                contentId = pathSplit[0];
                if (pathSplit.length > 1) {
                    mapKey = pathSplit[1];
                }
            }
            // verify the request content is associated with the current website
            int statusCode = -1;
            boolean hasErrorPage = false;
            if (contentId != null) {
                try {
                    statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
                } catch (GeneralException e) {
                    Debug.logError(e, module);
                    throw new GeneralRuntimeException(e.getMessage(), e);
                }
            } else {
                statusCode = HttpServletResponse.SC_NOT_FOUND;
            }
            // We try to find a specific Error page for this website concerning the status code
            if (statusCode != HttpServletResponse.SC_OK) {
                GenericValue errorContainer = null;
                try {
                    errorContainer = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT").orderBy("fromDate").filterByDate().cache().queryFirst();
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                if (errorContainer != null) {
                    if (Debug.verboseOn())
                        Debug.logVerbose("Found error containers: " + errorContainer, module);
                    GenericValue errorPage = null;
                    try {
                        errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo").where("contentIdStart", errorContainer.getString("contentId"), "caContentAssocTypeId", "TREE_CHILD", "contentTypeId", "DOCUMENT", "caMapKey", String.valueOf(statusCode)).filterByDate().queryFirst();
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                    if (errorPage != null) {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, module);
                        }
                        contentId = errorPage.getString("contentId");
                    } else {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, module);
                        }
                        contentId = errorContainer.getString("contentId");
                    }
                    mapKey = null;
                    hasErrorPage = true;
                }
                // We try to find a generic content Error page concerning the status code
                if (!hasErrorPage) {
                    try {
                        GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
                        if (errorPage != null) {
                            if (Debug.verboseOn())
                                Debug.logVerbose("Found generic page " + statusCode, module);
                            contentId = errorPage.getString("contentId");
                            mapKey = null;
                            hasErrorPage = true;
                        }
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                }
            }
            if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
                // create the template map
                MapStack<String> templateMap = MapStack.create();
                ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
                templateMap.put("statusCode", statusCode);
                // make the link prefix
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                templateMap.put("_REQUEST_HANDLER_", rh);
                response.setStatus(statusCode);
                try {
                    writer = response.getWriter();
                    // TODO: replace "screen" to support dynamic rendering of different output
                    if (visualTheme == null) {
                        String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
                        visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
                    }
                    FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response);
                    templateMap.put("formStringRenderer", formStringRenderer);
                    // if use web analytics
                    List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
                    // render
                    if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
                    } else if (UtilValidate.isEmpty(mapKey)) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true);
                    } else {
                        ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true);
                    }
                } catch (TemplateException e) {
                    throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (IOException e) {
                    throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (GeneralException e) {
                    throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                }
                return "success";
            } else {
                String contentName = null;
                String siteName = null;
                try {
                    GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
                    if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) {
                        contentName = content.getString("contentName");
                    } else {
                        request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
                        return "error";
                    }
                    siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
                return "error";
            }
        }
    }
    String siteName = null;
    GenericValue webSite = null;
    try {
        webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne();
        if (webSite != null) {
            siteName = webSite.getString("siteName");
        }
        if (siteName == null) {
            siteName = "Not specified";
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (webSite != null) {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display for website: " + siteName + " [" + webSiteId + "] not even a default page!");
    } else {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display, not even a default page AND the website entity record for WebSiteId:" + webSiteId + " could not be found");
    }
    return "error";
}
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) TemplateException(freemarker.template.TemplateException) HttpSession(javax.servlet.http.HttpSession) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) ServletException(javax.servlet.ServletException) Delegator(org.apache.ofbiz.entity.Delegator) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) ServletContext(javax.servlet.ServletContext) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) Writer(java.io.Writer)

Example 13 with RequestHandler

use of org.apache.ofbiz.webapp.control.RequestHandler in project ofbiz-framework by apache.

the class ContentMapFacade method get.

// implemented get method
public Object get(Object obj) {
    if (!(obj instanceof String)) {
        Debug.logWarning("Key parameters must be a string", module);
        return null;
    }
    String name = (String) obj;
    if ("fields".equalsIgnoreCase(name)) {
        // fields key, returns value object
        if (this.fields != null) {
            return fields;
        }
        try {
            EntityQuery contentQuery = EntityQuery.use(delegator).from("Content").where("contentId", contentId);
            if (cache) {
                contentQuery.cache();
            }
            this.fields = contentQuery.queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        return this.fields;
    } else if ("link".equalsIgnoreCase(name)) {
        // link to this content
        RequestHandler rh = (RequestHandler) this.context.get("_REQUEST_HANDLER_");
        HttpServletRequest request = (HttpServletRequest) this.context.get("request");
        HttpServletResponse response = (HttpServletResponse) this.context.get("response");
        if (rh != null && request != null && response != null) {
            String webSiteId = WebSiteWorker.getWebSiteId(request);
            Delegator delegator = (Delegator) request.getAttribute("delegator");
            String contentUri = this.contentId;
            // so we're only looking for a direct alias using contentId
            if (webSiteId != null && delegator != null) {
                try {
                    GenericValue webSitePathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("mapKey", null, "webSiteId", webSiteId, "contentId", this.contentId).orderBy("-fromDate").cache().filterByDate().queryFirst();
                    if (webSitePathAlias != null) {
                        contentUri = webSitePathAlias.getString("pathAlias");
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
            String contextLink = rh.makeLink(request, response, contentUri, true, false, true);
            return contextLink;
        } else {
            return this.contentId;
        }
    } else if ("data".equalsIgnoreCase(name) || "dataresource".equalsIgnoreCase(name)) {
        // data (resource) object
        return dataResource;
    } else if ("subcontent_all".equalsIgnoreCase(name)) {
        // subcontent list of ordered subcontent
        List<ContentMapFacade> subContent = new LinkedList<ContentMapFacade>();
        List<GenericValue> subs = null;
        try {
            Map<String, Object> expressions = new HashMap<String, Object>();
            expressions.put("contentIdStart", contentId);
            if (!this.mapKeyFilter.equals("")) {
                expressions.put("caMapKey", this.mapKeyFilter);
            }
            if (!this.statusFilter.equals("")) {
                expressions.put("statusId", this.statusFilter);
            }
            subs = EntityQuery.use(delegator).from("ContentAssocViewTo").where(expressions).orderBy(this.sortOrder).filterByDate().cache(cache).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (subs != null) {
            for (GenericValue v : subs) {
                subContent.add(new ContentMapFacade(dispatcher, v.getString("contentId"), context, locale, mimeType, cache));
            }
        }
        return subContent;
    } else if ("subcontent".equalsIgnoreCase(name)) {
        // return the subcontent object
        return this.subContent;
    } else if ("metadata".equalsIgnoreCase(name)) {
        // return list of metaData by predicate ID
        return this.metaData;
    } else if ("content".equalsIgnoreCase(name)) {
        // content; returns object from contentId
        return content;
    } else if ("render".equalsIgnoreCase(name)) {
        // render this content
        return this.renderThis();
    }
    return null;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HttpServletResponse(javax.servlet.http.HttpServletResponse) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 14 with RequestHandler

use of org.apache.ofbiz.webapp.control.RequestHandler in project ofbiz-framework by apache.

the class RenderContentAsText method getWriter.

@Override
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
    final Environment env = Environment.getCurrentEnvironment();
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
    final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
    if (Debug.verboseOn()) {
        Debug.logVerbose("in RenderSubContent, contentId(0):" + templateRoot.get("contentId"), module);
    }
    FreeMarkerWorker.getSiteParameters(request, templateRoot);
    final Map<String, Object> savedValuesUp = new HashMap<>();
    FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
    FreeMarkerWorker.overrideWithArgs(templateRoot, args);
    if (Debug.verboseOn()) {
        Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
    }
    final String thisContentId = (String) templateRoot.get("contentId");
    final String xmlEscape = (String) templateRoot.get("xmlEscape");
    final boolean directAssocMode = UtilValidate.isNotEmpty(thisContentId) ? true : false;
    if (Debug.verboseOn()) {
        Debug.logVerbose("in Render(0), directAssocMode ." + directAssocMode, module);
    }
    final Map<String, Object> savedValues = new HashMap<>();
    return new Writer(out) {

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

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

        @Override
        public void close() throws IOException {
            List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
            if (Debug.verboseOn()) {
                Debug.logVerbose("Render close, globalNodeTrail(2a):" + ContentWorker.nodeTrailToCsv(globalNodeTrail), "");
            }
            renderSubContent();
        }

        public void renderSubContent() throws IOException {
            String mimeTypeId = (String) templateRoot.get("mimeTypeId");
            Object localeObject = templateRoot.get("locale");
            Locale locale = null;
            if (localeObject == null) {
                locale = UtilHttp.getLocale(request);
            } else {
                locale = UtilMisc.ensureLocale(localeObject);
            }
            String editRequestName = (String) templateRoot.get("editRequestName");
            if (Debug.verboseOn()) {
                Debug.logVerbose("in Render(3), editRequestName ." + editRequestName, module);
            }
            if (UtilValidate.isNotEmpty(editRequestName)) {
                String editStyle = getEditStyle();
                openEditWrap(out, editStyle);
            }
            if (Debug.verboseOn()) {
                Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
                Debug.logVerbose("in RenderSubContent, subContentId(2):" + templateRoot.get("subContentId"), module);
            }
            FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
            try {
                String txt = ContentWorker.renderContentAsText(dispatcher, thisContentId, templateRoot, locale, mimeTypeId, true);
                if ("true".equals(xmlEscape)) {
                    txt = UtilFormatOut.encodeXmlValue(txt);
                }
                out.write(txt);
            } catch (GeneralException e) {
                String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString();
                Debug.logError(e, errMsg, module);
            // just log a message and don't return anything: throw new IOException();
            }
            // }
            FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
            FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
            if (UtilValidate.isNotEmpty(editRequestName)) {
                closeEditWrap(out, editRequestName);
            }
        }

        public void openEditWrap(Writer out, String editStyle) throws IOException {
            String divStr = "<div class=\"" + editStyle + "\">";
            out.write(divStr);
        }

        public void closeEditWrap(Writer out, String editRequestName) throws IOException {
            if (Debug.infoOn()) {
                Debug.logInfo("in RenderSubContent, contentId(3):" + templateRoot.get("contentId"), module);
                Debug.logInfo("in RenderSubContent, subContentId(3):" + templateRoot.get("subContentId"), module);
            }
            String fullRequest = editRequestName;
            String contentId = null;
            contentId = (String) templateRoot.get("subContentId");
            String delim = "?";
            if (UtilValidate.isNotEmpty(contentId)) {
                fullRequest += delim + "contentId=" + contentId;
                delim = "&";
            }
            out.write("<a href=\"");
            ServletContext servletContext = request.getSession().getServletContext();
            RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
            out.append(rh.makeLink(request, response, "/" + fullRequest, false, false, true));
            out.write("\">Edit</a>");
            out.write("</div>");
        }

        public String getEditStyle() {
            String editStyle = (String) templateRoot.get("editStyle");
            if (UtilValidate.isEmpty(editStyle)) {
                editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
            }
            if (UtilValidate.isEmpty(editStyle)) {
                editStyle = "buttontext";
            }
            return editStyle;
        }
    };
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) Environment(freemarker.core.Environment) ServletContext(javax.servlet.ServletContext) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 15 with RequestHandler

use of org.apache.ofbiz.webapp.control.RequestHandler in project ofbiz-framework by apache.

the class RenderContentTransform method getWriter.

@Override
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
    final Environment env = Environment.getCurrentEnvironment();
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
    final Map<String, Object> templateRoot = MapStack.create(FreeMarkerWorker.createEnvironmentMap(env));
    ((MapStack) templateRoot).push(args);
    final String xmlEscape = (String) templateRoot.get("xmlEscape");
    final String thisContentId = (String) templateRoot.get("contentId");
    return new Writer(out) {

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

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

        @Override
        public void close() throws IOException {
            renderSubContent();
        }

        public void renderSubContent() throws IOException {
            String mimeTypeId = (String) templateRoot.get("mimeTypeId");
            Object localeObject = templateRoot.get("locale");
            Locale locale = null;
            if (localeObject == null) {
                locale = UtilHttp.getLocale(request);
            } else {
                locale = UtilMisc.ensureLocale(localeObject);
            }
            String editRequestName = (String) templateRoot.get("editRequestName");
            if (UtilValidate.isNotEmpty(editRequestName)) {
                String editStyle = getEditStyle();
                openEditWrap(out, editStyle);
            }
            try {
                String txt = null;
                String mapKey = (String) templateRoot.get("mapKey");
                if (UtilValidate.isEmpty(mapKey)) {
                    txt = ContentWorker.renderContentAsText(dispatcher, thisContentId, templateRoot, locale, mimeTypeId, true);
                } else {
                    txt = ContentWorker.renderSubContentAsText(dispatcher, thisContentId, mapKey, templateRoot, locale, mimeTypeId, true);
                }
                if ("true".equals(xmlEscape)) {
                    txt = UtilFormatOut.encodeXmlValue(txt);
                }
                out.write(txt);
            } catch (GeneralException e) {
                String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString();
                Debug.logError(e, errMsg, module);
            // just log a message and don't return anything: throw new IOException();
            }
            if (UtilValidate.isNotEmpty(editRequestName)) {
                closeEditWrap(out, editRequestName);
            }
        }

        public void openEditWrap(Writer out, String editStyle) throws IOException {
            String divStr = "<div class=\"" + editStyle + "\">";
            out.write(divStr);
        }

        public void closeEditWrap(Writer out, String editRequestName) throws IOException {
            String fullRequest = editRequestName;
            String delim = "?";
            if (UtilValidate.isNotEmpty(thisContentId)) {
                fullRequest += delim + "contentId=" + thisContentId;
                delim = "&";
            }
            out.write("<a href=\"");
            ServletContext servletContext = request.getSession().getServletContext();
            RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
            out.append(rh.makeLink(request, response, "/" + fullRequest, false, false, true));
            out.write("\">Edit</a>");
            out.write("</div>");
        }

        public String getEditStyle() {
            String editStyle = (String) templateRoot.get("editStyle");
            if (UtilValidate.isEmpty(editStyle)) {
                editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
            }
            if (UtilValidate.isEmpty(editStyle)) {
                editStyle = "buttontext";
            }
            return editStyle;
        }
    };
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) MapStack(org.apache.ofbiz.base.util.collections.MapStack) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) Environment(freemarker.core.Environment) ServletContext(javax.servlet.ServletContext) Writer(java.io.Writer)

Aggregations

RequestHandler (org.apache.ofbiz.webapp.control.RequestHandler)27 ServletContext (javax.servlet.ServletContext)24 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 HashMap (java.util.HashMap)10 IOException (java.io.IOException)9 Writer (java.io.Writer)7 Environment (freemarker.core.Environment)6 Locale (java.util.Locale)6 WeakHashMap (java.util.WeakHashMap)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)6 GenericValue (org.apache.ofbiz.entity.GenericValue)6 HttpSession (javax.servlet.http.HttpSession)5 Delegator (org.apache.ofbiz.entity.Delegator)5 Map (java.util.Map)4 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)4 TemplateModelException (freemarker.template.TemplateModelException)3 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)3 EventHandlerException (org.apache.ofbiz.webapp.event.EventHandlerException)3 BeanModel (freemarker.ext.beans.BeanModel)2