diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentUrlFilter.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentUrlFilter.java index 4824cfe54e..67a882fa1e 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentUrlFilter.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentUrlFilter.java @@ -38,6 +38,7 @@ import org.apache.ofbiz.common.UrlServletHelper; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.ofbiz.webapp.control.ContextFilter; public class ContentUrlFilter extends ContextFilter { @@ -57,7 +58,7 @@ public class ContentUrlFilter extends ContextFilter { //Get ServletContext ServletContext servletContext = config.getServletContext(); - ContextFilter.setCharacterEncoding(request); + WebAppUtil.setCharacterEncoding(request); //Set request attribute and session UrlServletHelper.setRequestAttributes(request, delegator, servletContext); @@ -88,7 +89,7 @@ public class ContentUrlFilter extends ContextFilter { urlBuilder.append("/" + CONTROL_MOUNT_POINT); urlBuilder.append("/" + config.getInitParameter("viewRequest") + "?contentId=" + urlContentId); - ContextFilter.setAttributesFromRequestBody(request); + WebAppUtil.setAttributesFromRequestBody(request); //Set view query parameters UrlServletHelper.setViewQueryParameters(request, urlBuilder); Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java index 93a92b2490..5a62992797 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java @@ -44,6 +44,7 @@ import org.apache.ofbiz.entity.condition.EntityCondition; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.entity.util.EntityUtil; import org.apache.ofbiz.product.product.ProductContentWrapper; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.ofbiz.webapp.control.ContextFilter; public class CatalogUrlFilter extends ContextFilter { @@ -66,7 +67,7 @@ public class CatalogUrlFilter extends ContextFilter { //Get ServletContext ServletContext servletContext = config.getServletContext(); - ContextFilter.setCharacterEncoding(request); + WebAppUtil.setCharacterEncoding(request); //Set request attribute and session UrlServletHelper.setRequestAttributes(request, delegator, servletContext); @@ -324,7 +325,7 @@ public class CatalogUrlFilter extends ContextFilter { UrlServletHelper.setViewQueryParameters(request, urlBuilder); if (UtilValidate.isNotEmpty(productId) || UtilValidate.isNotEmpty(productCategoryId) || UtilValidate.isNotEmpty(urlContentId)) { Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); - ContextFilter.setAttributesFromRequestBody(request); + WebAppUtil.setAttributesFromRequestBody(request); RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString()); dispatch.forward(request, response); return; diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContextFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContextFilter.java index f3601259e9..d8700d89ca 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContextFilter.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContextFilter.java @@ -39,6 +39,7 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.ofbiz.base.util.Debug; @@ -296,7 +297,7 @@ public class SeoContextFilter extends ContextFilter { String serverName = httpRequest.getServerName(); try { // if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute - Delegator delegator = getDelegator(config.getServletContext()); + Delegator delegator = WebAppUtil.getDelegator(config.getServletContext()); // to access entity "tenant" we need the default delegator Delegator defaultdelegator = DelegatorFactory.getDelegator("default"); @@ -330,9 +331,9 @@ public class SeoContextFilter extends ContextFilter { config.getServletContext().setAttribute("dispatcher", null); // initialize security - Security security = getSecurity(); + Security security = WebAppUtil.getSecurity(config.getServletContext()); // initialize the services dispatcher - LocalDispatcher dispatcher = getDispatcher(config.getServletContext()); + LocalDispatcher dispatcher = WebAppUtil.getDispatcher(config.getServletContext()); // set web context objects request.setAttribute("dispatcher", dispatcher); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/UrlRegexpContextFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/UrlRegexpContextFilter.java deleted file mode 100644 index a488854b93..0000000000 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/UrlRegexpContextFilter.java +++ /dev/null @@ -1,321 +0,0 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.apache.ofbiz.product.category; - -import static org.apache.ofbiz.base.util.UtilGenerics.checkMap; - -import java.io.IOException; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.FilterChain; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.ofbiz.base.util.Debug; -import org.apache.ofbiz.base.util.GeneralException; -import org.apache.ofbiz.base.util.StringUtil; -import org.apache.ofbiz.base.util.UtilHttp; -import org.apache.ofbiz.base.util.UtilMisc; -import org.apache.ofbiz.base.util.UtilObject; -import org.apache.ofbiz.base.util.UtilValidate; -import org.apache.ofbiz.entity.Delegator; -import org.apache.ofbiz.entity.DelegatorFactory; -import org.apache.ofbiz.entity.GenericEntityException; -import org.apache.ofbiz.entity.GenericValue; -import org.apache.ofbiz.entity.condition.EntityCondition; -import org.apache.ofbiz.entity.util.EntityUtil; -import org.apache.ofbiz.product.category.ftl.UrlRegexpTransform; -import org.apache.ofbiz.security.Security; -import org.apache.ofbiz.service.LocalDispatcher; -import org.apache.ofbiz.webapp.control.ConfigXMLReader; -import org.apache.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig; -import org.apache.ofbiz.webapp.control.ContextFilter; -import org.apache.ofbiz.webapp.control.WebAppConfigurationException; - -/** - * UrlRegexpContextFilter - Restricts access to raw files and configures servlet objects. - */ -public class UrlRegexpContextFilter extends ContextFilter { - - public static final String module = UrlRegexpContextFilter.class.getName(); - - /** - * @throws GeneralException - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - - String uri = httpRequest.getRequestURI(); - boolean forwarded = UrlRegexpTransform.forwardUri(httpResponse, uri); - if (forwarded) { - return; - } - - URL controllerConfigURL = ConfigXMLReader.getControllerConfigURL(config.getServletContext()); - ControllerConfig controllerConfig = null; - Map requestMaps = null; - try { - controllerConfig = ConfigXMLReader.getControllerConfig(controllerConfigURL); - requestMaps = controllerConfig.getRequestMapMap(); - } catch (WebAppConfigurationException e) { - Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module); - throw new ServletException(e); - } - Set uris = requestMaps.keySet(); - - // NOTE: the following part is copied from org.apache.ofbiz.webapp.control.ContextFilter.doFilter method, please update this if framework is updated. - // Debug.logInfo("Running ContextFilter.doFilter", module); - - // ----- Servlet Object Setup ----- - // set the cached class loader for more speedy running in this thread - - - // set the ServletContext in the request for future use - httpRequest.setAttribute("servletContext", config.getServletContext()); - - // set the webSiteId in the session - if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))) { - httpRequest.getSession().setAttribute("webSiteId", config.getServletContext().getAttribute("webSiteId")); - } - - // set the filesystem path of context root. - httpRequest.setAttribute("_CONTEXT_ROOT_", config.getServletContext().getRealPath("/")); - - // set the server root url - String serverRootUrl = UtilHttp.getServerRootUrl(httpRequest); - httpRequest.setAttribute("_SERVER_ROOT_URL_", serverRootUrl); - - // request attributes from redirect call - String reqAttrMapHex = (String) httpRequest.getSession().getAttribute("_REQ_ATTR_MAP_"); - if (UtilValidate.isNotEmpty(reqAttrMapHex)) { - byte[] reqAttrMapBytes = StringUtil.fromHexString(reqAttrMapHex); - Map reqAttrMap = checkMap(UtilObject.getObject(reqAttrMapBytes), String.class, Object.class); - if (reqAttrMap != null) { - for (Map.Entry entry : reqAttrMap.entrySet()) { - httpRequest.setAttribute(entry.getKey(), entry.getValue()); - } - } - httpRequest.getSession().removeAttribute("_REQ_ATTR_MAP_"); - } - - // ----- Context Security ----- - // check if we are disabled - String disableSecurity = config.getInitParameter("disableContextSecurity"); - if (disableSecurity != null && "Y".equalsIgnoreCase(disableSecurity)) { - chain.doFilter(httpRequest, httpResponse); - return; - } - - // check if we are told to redirect everthing - String redirectAllTo = config.getInitParameter("forceRedirectAll"); - if (UtilValidate.isNotEmpty(redirectAllTo)) { - // little trick here so we don't loop on ourself - if (httpRequest.getSession().getAttribute("_FORCE_REDIRECT_") == null) { - httpRequest.getSession().setAttribute("_FORCE_REDIRECT_", "true"); - Debug.logWarning("Redirecting user to: " + redirectAllTo, module); - - if (!redirectAllTo.toLowerCase().startsWith("http")) { - redirectAllTo = httpRequest.getContextPath() + redirectAllTo; - } - httpResponse.sendRedirect(redirectAllTo); - return; - } else { - httpRequest.getSession().removeAttribute("_FORCE_REDIRECT_"); - chain.doFilter(httpRequest, httpResponse); - return; - } - } - - // test to see if we have come through the control servlet already, if not do the processing - String requestPath = null; - String contextUri = null; - if (httpRequest.getAttribute(ContextFilter.FORWARDED_FROM_SERVLET) == null) { - if (debug) Debug.log("[Domain]: " + httpRequest.getServerName() + " [Request]: " + httpRequest.getRequestURI(), module); - - requestPath = httpRequest.getServletPath(); - if (requestPath == null) requestPath = ""; - if (requestPath.lastIndexOf("/") > 0) { - if (requestPath.indexOf("/") == 0) { - requestPath = "/" + requestPath.substring(1, requestPath.indexOf("/", 1)); - } else { - requestPath = requestPath.substring(1, requestPath.indexOf("/")); - } - } - - String requestInfo = httpRequest.getServletPath(); - if (requestInfo == null) requestInfo = ""; - if (requestInfo.lastIndexOf("/") >= 0) { - requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf("/")) + "/*"; - } - - StringBuilder contextUriBuffer = new StringBuilder(); - if (httpRequest.getContextPath() != null) { - contextUriBuffer.append(httpRequest.getContextPath()); - } - if (httpRequest.getServletPath() != null) { - contextUriBuffer.append(httpRequest.getServletPath()); - } - if (httpRequest.getPathInfo() != null) { - contextUriBuffer.append(httpRequest.getPathInfo()); - } - contextUri = contextUriBuffer.toString(); - - List pathItemList = StringUtil.split(httpRequest.getPathInfo(), "/"); - String viewName = ""; - if (pathItemList != null) { - viewName = pathItemList.get(0); - } - - // Debug.logInfo("In ContextFilter.doFilter, FORWARDED_FROM_SERVLET is NOT set", module); - String allowedPath = config.getInitParameter("allowedPaths"); - String redirectPath = config.getInitParameter("redirectPath"); - String errorCode = config.getInitParameter("errorCode"); - - List allowList = StringUtil.split(allowedPath, ":"); - allowList.add("/"); // No path is allowed. - if (UtilValidate.isNotEmpty(httpRequest.getServletPath())) { - allowList.add(""); // No path is allowed if servlet path is not empty. - } - - // Verbose Debugging - if (Debug.verboseOn()) { - for (String allow : allowList) { - Debug.logVerbose("[Allow]: " + allow, module); - } - Debug.logVerbose("[Request path]: " + requestPath, module); - Debug.logVerbose("[Request info]: " + requestInfo, module); - Debug.logVerbose("[Servlet path]: " + httpRequest.getServletPath(), module); - Debug.logVerbose("[View name]: " + viewName, module); - Debug.logVerbose("[Not In AllowList]: " + (!allowList.contains(requestPath) && !allowList.contains(requestInfo) && !allowList.contains(httpRequest.getServletPath())), module); - Debug.logVerbose("[Not In controller]: " + (UtilValidate.isEmpty(requestPath) && UtilValidate.isEmpty(httpRequest.getServletPath()) && !uris.contains(viewName)), module); - } - - // check to make sure the requested url is allowed - if (!allowList.contains(requestPath) && !allowList.contains(requestInfo) && !allowList.contains(httpRequest.getServletPath()) - && (UtilValidate.isEmpty(requestPath) && UtilValidate.isEmpty(httpRequest.getServletPath()) && !uris.contains(viewName))) { - String filterMessage = "[Filtered request]: " + contextUri; - - if (redirectPath == null) { - int error = 404; - if (UtilValidate.isNotEmpty(errorCode)) { - try { - error = Integer.parseInt(errorCode); - } catch (NumberFormatException nfe) { - Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module); - } - } - filterMessage = filterMessage + " (" + error + ")"; - httpResponse.sendError(error, contextUri); - } else { - filterMessage = filterMessage + " (" + redirectPath + ")"; - if (!redirectPath.toLowerCase().startsWith("http")) { - redirectPath = httpRequest.getContextPath() + redirectPath; - } - // httpResponse.sendRedirect(redirectPath); - if (uri.equals("") || uri.equals("/")) { - // redirect without any url change in browser - RequestDispatcher rd = request.getRequestDispatcher(redirectPath); - rd.forward(request, response); - } else { - // redirect with url change in browser - httpResponse.setStatus(SeoConfigUtil.getDefaultResponseCode()); - httpResponse.setHeader("Location", redirectPath); - } - } - Debug.logWarning(filterMessage, module); - return; - } - } - - // check if multi tenant is enabled - boolean useMultitenant = EntityUtil.isMultiTenantEnabled(); - if (useMultitenant) { - // get tenant delegator by domain name - String serverName = httpRequest.getServerName(); - try { - // if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute - Delegator delegator = getDelegator(config.getServletContext()); - List tenants = delegator.findList("Tenant", EntityCondition.makeCondition("domainName", serverName), null, UtilMisc.toList("-createdStamp"), null, false); - if (UtilValidate.isNotEmpty(tenants)) { - GenericValue tenant = EntityUtil.getFirst(tenants); - String tenantId = tenant.getString("tenantId"); - - // if the request path is a root mount then redirect to the initial path - if (UtilValidate.isNotEmpty(requestPath) && requestPath.equals(contextUri)) { - String initialPath = tenant.getString("initialPath"); - if (UtilValidate.isNotEmpty(initialPath) && !"/".equals(initialPath)) { - ((HttpServletResponse) response).sendRedirect(initialPath); - return; - } - } - - // make that tenant active, setup a new delegator and a new dispatcher - String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId; - httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName); - - // after this line the delegator is replaced with the new per-tenant delegator - delegator = DelegatorFactory.getDelegator(tenantDelegatorName); - config.getServletContext().setAttribute("delegator", delegator); - - // clear web context objects - // config.getServletContext().setAttribute("authorization", null); - config.getServletContext().setAttribute("security", null); - config.getServletContext().setAttribute("dispatcher", null); - - // initialize authorizer - // getAuthz(); - // initialize security - Security security = getSecurity(); - // initialize the services dispatcher - LocalDispatcher dispatcher = getDispatcher(config.getServletContext()); - - // set web context objects - httpRequest.getSession().setAttribute("dispatcher", dispatcher); - httpRequest.getSession().setAttribute("security", security); - - httpRequest.setAttribute("userTenantId", tenantId); - } - - // NOTE DEJ20101130: do NOT always put the delegator name in the user's session because the user may - // have logged in and specified a tenant, and even if no Tenant record with a matching domainName field - // is found this will change the user's delegator back to the base one instead of the one for the - // tenant specified on login - // httpRequest.getSession().setAttribute("delegatorName", delegator.getDelegatorName()); - } catch (GenericEntityException e) { - Debug.logWarning(e, "Unable to get Tenant", module); - } - } - - // we're done checking; continue on - chain.doFilter(httpRequest, httpResponse); - - // reset thread local security - // AbstractAuthorization.clearThreadLocal(); - } - -} diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java b/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java index 8357553595..3dface749c 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java @@ -38,6 +38,7 @@ import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.entity.util.EntityUtil; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.ofbiz.webapp.control.ContextFilter; import org.apache.ofbiz.webapp.website.WebSiteWorker; @@ -56,7 +57,7 @@ public final class UrlServletHelper extends ContextFilter { String serverName = request.getServerName(); try { // if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute - delegator = getDelegator(servletContext); + delegator = WebAppUtil.getDelegator(servletContext); //Use base delegator for fetching data from entity of entityGroup org.apache.ofbiz.tenant Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName()); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/WebAppUtil.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/WebAppUtil.java index 88bf977b42..3b7bae8239 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/WebAppUtil.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/WebAppUtil.java @@ -22,13 +22,22 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import javax.servlet.ServletContext; +import javax.servlet.ServletRequest; -import org.apache.tomcat.util.digester.Digester; -import org.apache.tomcat.util.descriptor.DigesterFactory; -import org.apache.tomcat.util.descriptor.web.ServletDef; -import org.apache.tomcat.util.descriptor.web.WebRuleSet; -import org.apache.tomcat.util.descriptor.web.WebXml; +import org.apache.ofbiz.base.util.UtilValidate; +import org.apache.ofbiz.entity.Delegator; +import org.apache.ofbiz.entity.DelegatorFactory; +import org.apache.ofbiz.security.Security; +import org.apache.ofbiz.security.SecurityConfigurationException; +import org.apache.ofbiz.security.SecurityFactory; +import org.apache.ofbiz.service.LocalDispatcher; +import org.apache.ofbiz.service.ServiceContainer; +import org.apache.ofbiz.webapp.event.RequestBodyMapHandlerFactory; import org.apache.ofbiz.base.component.ComponentConfig; import org.apache.ofbiz.base.component.ComponentConfig.WebappInfo; import org.apache.ofbiz.base.util.Assert; @@ -36,6 +45,12 @@ import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.UtilXml.LocalErrorHandler; import org.apache.ofbiz.base.util.UtilXml.LocalResolver; import org.apache.ofbiz.base.util.cache.UtilCache; + +import org.apache.tomcat.util.digester.Digester; +import org.apache.tomcat.util.descriptor.DigesterFactory; +import org.apache.tomcat.util.descriptor.web.ServletDef; +import org.apache.tomcat.util.descriptor.web.WebRuleSet; +import org.apache.tomcat.util.descriptor.web.WebXml; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -118,6 +133,103 @@ public final class WebAppUtil { return webXml.getContextParams().get("webSiteId"); } + public static LocalDispatcher getDispatcher(ServletContext servletContext) { + LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher"); + if (dispatcher == null) { + Delegator delegator = getDelegator(servletContext); + dispatcher = makeWebappDispatcher(servletContext, delegator); + servletContext.setAttribute("dispatcher", dispatcher); + } + return dispatcher; + } + + public static void setCharacterEncoding(ServletRequest request) throws UnsupportedEncodingException { + String charset = request.getServletContext().getInitParameter("charset"); + if (UtilValidate.isEmpty(charset)) charset = request.getCharacterEncoding(); + if (UtilValidate.isEmpty(charset)) charset = "UTF-8"; + if (Debug.verboseOn()) Debug.logVerbose("The character encoding of the request is: [" + request.getCharacterEncoding() + "]. The character encoding we will use for the request is: [" + charset + "]", module); + + if (!"none".equals(charset)) { + request.setCharacterEncoding(charset); + } + } + + public static void setAttributesFromRequestBody(ServletRequest request) { + // read the body (for JSON requests) and set the parameters as attributes: + Map requestBodyMap = null; + try { + requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request); + } catch (IOException ioe) { + Debug.logWarning(ioe, module); + } + if (requestBodyMap != null) { + Set parameterNames = requestBodyMap.keySet(); + for (String parameterName: parameterNames) { + request.setAttribute(parameterName, requestBodyMap.get(parameterName)); + } + } + } + + /** This method only sets up a dispatcher for the current webapp and passed in delegator, it does not save it to the ServletContext or anywhere else, just returns it */ + public static LocalDispatcher makeWebappDispatcher(ServletContext servletContext, Delegator delegator) { + if (delegator == null) { + Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module); + return null; + } + // get the unique name of this dispatcher + String dispatcherName = servletContext.getInitParameter("localDispatcherName"); + + if (dispatcherName == null) { + Debug.logError("No localDispatcherName specified in the web.xml file", module); + dispatcherName = delegator.getDelegatorName(); + } + + LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, delegator); + if (dispatcher == null) { + Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module); + } + + return dispatcher; + } + + public static Delegator getDelegator(ServletContext servletContext) { + Delegator delegator = (Delegator) servletContext.getAttribute("delegator"); + if (delegator == null) { + String delegatorName = servletContext.getInitParameter("entityDelegatorName"); + + if (UtilValidate.isEmpty(delegatorName)) { + delegatorName = "default"; + } + if (Debug.verboseOn()) Debug.logVerbose("Setup Entity Engine Delegator with name " + delegatorName, module); + delegator = DelegatorFactory.getDelegator(delegatorName); + servletContext.setAttribute("delegator", delegator); + if (delegator == null) { + Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module); + } + } + return delegator; + } + + public static Security getSecurity(ServletContext servletContext) { + Security security = (Security) servletContext.getAttribute("security"); + if (security == null) { + Delegator delegator = (Delegator) servletContext.getAttribute("delegator"); + + if (delegator != null) { + try { + security = SecurityFactory.getInstance(delegator); + } catch (SecurityConfigurationException e) { + Debug.logError(e, "Unable to obtain an instance of the security object.", module); + } + } + servletContext.setAttribute("security", security); + if (security == null) { + Debug.logError("An invalid (null) Security object has been set in the servlet context.", module); + } + } + return security; + } + /** * Returns a WebXml instance that models the web application's web.xml file. * @@ -125,7 +237,7 @@ public final class WebAppUtil { * @throws IOException * @throws SAXException */ - public static WebXml getWebXml(WebappInfo webAppInfo) throws IOException, SAXException { + private static WebXml getWebXml(WebappInfo webAppInfo) throws IOException, SAXException { Assert.notNull("webAppInfo", webAppInfo); String webXmlFileLocation = webAppInfo.getLocation().concat(webAppFileName); return parseWebXmlFile(webXmlFileLocation, true); @@ -139,7 +251,7 @@ public final class WebAppUtil { * @throws IOException * @throws SAXException */ - public static WebXml parseWebXmlFile(String webXmlFileLocation, boolean validate) throws IOException, SAXException { + private static WebXml parseWebXmlFile(String webXmlFileLocation, boolean validate) throws IOException, SAXException { Assert.notEmpty("webXmlFileLocation", webXmlFileLocation); WebXml result = webXmlCache.get(webXmlFileLocation); if (result == null) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java index 4cc3f72649..528bc0fc65 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java @@ -54,6 +54,7 @@ import org.apache.ofbiz.security.SecurityConfigurationException; import org.apache.ofbiz.security.SecurityFactory; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ServiceContainer; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.ofbiz.webapp.event.RequestBodyMapHandlerFactory; import org.apache.ofbiz.webapp.website.WebSiteWorker; @@ -74,7 +75,7 @@ public class ContextFilter implements Filter { public void init(FilterConfig config) throws ServletException { this.config = config; - // puts all init-parameters in ServletContext attributes for easier parameterization without code changes + // puts all init-parameters in ServletContext attributes for easier parametrization without code changes this.putAllInitParametersInAttributes(); // set debug @@ -86,11 +87,11 @@ public class ContextFilter implements Filter { // check the serverId getServerId(); // initialize the delegator - getDelegator(config.getServletContext()); + WebAppUtil.getDelegator(config.getServletContext()); // initialize security - getSecurity(); + WebAppUtil.getSecurity(config.getServletContext()); // initialize the services dispatcher - getDispatcher(config.getServletContext()); + WebAppUtil.getDispatcher(config.getServletContext()); // this will speed up the initial sessionId generation new java.security.SecureRandom().nextLong(); @@ -251,14 +252,14 @@ public class ContextFilter implements Filter { // check if multi tenant is enabled boolean useMultitenant = EntityUtil.isMultiTenantEnabled(); - setCharacterEncoding(request); - setAttributesFromRequestBody(request); + WebAppUtil.setCharacterEncoding(request); + WebAppUtil.setAttributesFromRequestBody(request); if (useMultitenant) { // get tenant delegator by domain name String serverName = httpRequest.getServerName(); try { // if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute - Delegator delegator = getDelegator(config.getServletContext()); + Delegator delegator = WebAppUtil.getDelegator(config.getServletContext()); //Use base delegator for fetching data from entity of entityGroup org.apache.ofbiz.tenant Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName()); @@ -298,9 +299,9 @@ public class ContextFilter implements Filter { config.getServletContext().setAttribute("dispatcher", null); // initialize security - Security security = getSecurity(); + Security security = WebAppUtil.getSecurity(config.getServletContext()); // initialize the services dispatcher - LocalDispatcher dispatcher = getDispatcher(config.getServletContext()); + LocalDispatcher dispatcher = WebAppUtil.getDispatcher(config.getServletContext()); // set web context objects request.setAttribute("dispatcher", dispatcher); @@ -327,108 +328,11 @@ public class ContextFilter implements Filter { * @see javax.servlet.Filter#destroy() */ public void destroy() { - getDispatcher(config.getServletContext()).deregister(); + WebAppUtil.getDispatcher(config.getServletContext()).deregister(); config = null; } - protected static LocalDispatcher getDispatcher(ServletContext servletContext) { - LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher"); - if (dispatcher == null) { - Delegator delegator = getDelegator(servletContext); - dispatcher = makeWebappDispatcher(servletContext, delegator); - servletContext.setAttribute("dispatcher", dispatcher); - } - return dispatcher; - } - - public static void setCharacterEncoding(ServletRequest request) throws UnsupportedEncodingException { - String charset = request.getServletContext().getInitParameter("charset"); - if (UtilValidate.isEmpty(charset)) charset = request.getCharacterEncoding(); - if (UtilValidate.isEmpty(charset)) charset = "UTF-8"; - if (Debug.verboseOn()) Debug.logVerbose("The character encoding of the request is: [" + request.getCharacterEncoding() + "]. The character encoding we will use for the request is: [" + charset + "]", module); - - if (!"none".equals(charset)) { - request.setCharacterEncoding(charset); - } - } - - public static void setAttributesFromRequestBody(ServletRequest request) { - // read the body (for JSON requests) and set the parameters as attributes: - Map requestBodyMap = null; - try { - requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request); - } catch (IOException ioe) { - Debug.logWarning(ioe, module); - } - if (requestBodyMap != null) { - Set parameterNames = requestBodyMap.keySet(); - for (String parameterName: parameterNames) { - request.setAttribute(parameterName, requestBodyMap.get(parameterName)); - } - } - } - - /** This method only sets up a dispatcher for the current webapp and passed in delegator, it does not save it to the ServletContext or anywhere else, just returns it */ - public static LocalDispatcher makeWebappDispatcher(ServletContext servletContext, Delegator delegator) { - if (delegator == null) { - Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module); - return null; - } - // get the unique name of this dispatcher - String dispatcherName = servletContext.getInitParameter("localDispatcherName"); - - if (dispatcherName == null) { - Debug.logError("No localDispatcherName specified in the web.xml file", module); - dispatcherName = delegator.getDelegatorName(); - } - - LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, delegator); - if (dispatcher == null) { - Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module); - } - - return dispatcher; - } - - protected static Delegator getDelegator(ServletContext servletContext) { - Delegator delegator = (Delegator) servletContext.getAttribute("delegator"); - if (delegator == null) { - String delegatorName = servletContext.getInitParameter("entityDelegatorName"); - - if (UtilValidate.isEmpty(delegatorName)) { - delegatorName = "default"; - } - if (Debug.verboseOn()) Debug.logVerbose("Setup Entity Engine Delegator with name " + delegatorName, module); - delegator = DelegatorFactory.getDelegator(delegatorName); - servletContext.setAttribute("delegator", delegator); - if (delegator == null) { - Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module); - } - } - return delegator; - } - - protected Security getSecurity() { - Security security = (Security) config.getServletContext().getAttribute("security"); - if (security == null) { - Delegator delegator = (Delegator) config.getServletContext().getAttribute("delegator"); - - if (delegator != null) { - try { - security = SecurityFactory.getInstance(delegator); - } catch (SecurityConfigurationException e) { - Debug.logError(e, "Unable to obtain an instance of the security object.", module); - } - } - config.getServletContext().setAttribute("security", security); - if (security == null) { - Debug.logError("An invalid (null) Security object has been set in the servlet context.", module); - } - } - return security; - } - - protected void putAllInitParametersInAttributes() { + private void putAllInitParametersInAttributes() { Enumeration initParamEnum = UtilGenerics.cast(config.getServletContext().getInitParameterNames()); while (initParamEnum.hasMoreElements()) { String initParamName = initParamEnum.nextElement(); @@ -438,7 +342,7 @@ public class ContextFilter implements Filter { } } - protected String getServerId() { + private String getServerId() { String serverId = (String) config.getServletContext().getAttribute("_serverId"); if (serverId == null) { serverId = config.getServletContext().getInitParameter("ofbizServerName"); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/LoginWorker.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/LoginWorker.java index 5c586ddbe1..c30373d0c8 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/LoginWorker.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/LoginWorker.java @@ -79,6 +79,7 @@ import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; +import org.apache.ofbiz.webapp.WebAppUtil; import org.apache.ofbiz.webapp.stats.VisitHandler; /** @@ -475,7 +476,7 @@ public class LoginWorker { try { // after this line the delegator is replaced with the new per-tenant delegator delegator = DelegatorFactory.getDelegator(delegatorName); - dispatcher = ContextFilter.makeWebappDispatcher(servletContext, delegator); + dispatcher = WebAppUtil.makeWebappDispatcher(servletContext, delegator); } catch (NullPointerException e) { Debug.logError(e, "Error getting tenant delegator", module); Map messageMap = UtilMisc.toMap("errorMessage", "Tenant [" + tenantId + "] not found..."); @@ -494,7 +495,7 @@ public class LoginWorker { try { // after this line the delegator is replaced with default delegator delegator = DelegatorFactory.getDelegator(delegatorName); - dispatcher = ContextFilter.makeWebappDispatcher(servletContext, delegator); + dispatcher = WebAppUtil.makeWebappDispatcher(servletContext, delegator); } catch (NullPointerException e) { Debug.logError(e, "Error getting default delegator", module); Map messageMap = UtilMisc.toMap("errorMessage", "Error getting default delegator"); @@ -748,7 +749,7 @@ public class LoginWorker { session.setAttribute("delegatorName", delegatorName); delegator = DelegatorFactory.getDelegator(delegatorName); - LocalDispatcher dispatcher = ContextFilter.makeWebappDispatcher(session.getServletContext(), delegator); + LocalDispatcher dispatcher = WebAppUtil.makeWebappDispatcher(session.getServletContext(), delegator); setWebContextObjects(request, response, delegator, dispatcher); } @@ -1064,7 +1065,7 @@ public class LoginWorker { ServletContext servletContext = session.getServletContext(); if (!oldDelegatorName.equals(userLogin.getDelegator().getDelegatorName())) { delegator = DelegatorFactory.getDelegator(userLogin.getDelegator().getDelegatorName()); - dispatcher = ContextFilter.makeWebappDispatcher(servletContext, delegator); + dispatcher = WebAppUtil.makeWebappDispatcher(servletContext, delegator); setWebContextObjects(request, response, delegator, dispatcher); } // found userLogin, do the external login...