You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ofbiz.apache.org by ad...@apache.org on 2013/10/24 02:45:51 UTC
svn commit: r1535246 -
/ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java
Author: adrianc
Date: Thu Oct 24 00:45:51 2013
New Revision: 1535246
URL: http://svn.apache.org/r1535246
Log:
Code cleanup and JavaDocs in OfbizUrlTransform.java.
If a web site ID is specified, the transform does not require a HttpServletRequest object - so the transform will work in scheduled services.
Modified:
ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java
Modified: ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java?rev=1535246&r1=1535245&r2=1535246&view=diff
==============================================================================
--- ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java (original)
+++ ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/OfbizUrlTransform.java Thu Oct 24 00:45:51 2013
@@ -18,67 +18,62 @@
*******************************************************************************/
package org.ofbiz.webapp.ftl;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.Writer;
+import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.xml.parsers.ParserConfigurationException;
import org.ofbiz.base.component.ComponentConfig;
import org.ofbiz.base.component.ComponentConfig.WebappInfo;
import org.ofbiz.base.util.Debug;
-import org.ofbiz.base.util.UtilMisc;
-import org.ofbiz.base.util.UtilProperties;
-import org.ofbiz.base.util.UtilValidate;
-import org.ofbiz.base.util.UtilXml;
+import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.entity.Delegator;
-import org.ofbiz.entity.GenericEntityException;
-import org.ofbiz.entity.GenericValue;
+import org.ofbiz.webapp.OfbizUrlBuilder;
+import org.ofbiz.webapp.WebAppUtil;
import org.ofbiz.webapp.control.RequestHandler;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
import freemarker.core.Environment;
-import freemarker.ext.beans.BeanModel;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateTransformModel;
/**
- * OfbizUrlTransform - Freemarker Transform for URLs (links)
+ * Freemarker Transform for creating OFBiz URLs (links).
+ * <p>This transform accepts several arguments:<br>
+ * <ul>
+ * <li><b>fullPath</b> (true/false) - generate a full URL including scheme and host, defaults to false.</li>
+ * <li><b>secure</b> (true/false) - generate a secure (https) URL, defaults to false. Server settings will
+ * override this argument.</li>
+ * <li><b>encode</b> (true/false) - encode the URL, defaults to true. Encoding is UTF-8.</li>
+ * <li><b>webSiteId</b> - generate a full URL using the web site settings found in the WebSite entity.</li>
+ * </ul></p>
+ * <p>In addition, this transform accepts an environment variable - <b>urlPrefix</b>. If the variable
+ * exists, it is prepended to the contents of the transform (the part between
+ * <code><@ofbizUrl></code> and <code></@ofbizUrl></code>), and all transform arguments are
+ * ignored.</p>
+ *
*/
public class OfbizUrlTransform implements TemplateTransformModel {
public final static String module = OfbizUrlTransform.class.getName();
@SuppressWarnings("rawtypes")
- private static boolean checkArg(Map args, String key, boolean defaultValue) {
- if (!args.containsKey(key)) {
- return defaultValue;
- } else {
- Object o = args.get(key);
- if (o instanceof SimpleScalar) {
- SimpleScalar s = (SimpleScalar) o;
- return "true".equalsIgnoreCase(s.getAsString());
- }
- return defaultValue;
+ private static boolean checkBooleanArg(Map args, String key, boolean defaultValue) {
+ Object o = args.get(key);
+ if (o instanceof SimpleScalar) {
+ SimpleScalar s = (SimpleScalar) o;
+ return "true".equalsIgnoreCase(s.getAsString());
}
+ return defaultValue;
}
- @SuppressWarnings("rawtypes")
- private static String getArg(Map args, String key) {
+ private static String convertToString(Object o) {
String result = "";
- Object o = args.get(key);
if (o != null) {
if (Debug.verboseOn())
Debug.logVerbose("Arg Object : " + o.getClass().getName(), module);
@@ -96,168 +91,72 @@ public class OfbizUrlTransform implement
return result;
}
- private static String getTagValue(String sTag, Element eElement) {
- String value = "";
- try {
- NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
- Node nValue = nlList.item(0);
- return value = nValue.getNodeValue();
- } catch (Exception e) {
- return value;
- }
- }
-
+ @Override
@SuppressWarnings("rawtypes")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
- final boolean fullPath = checkArg(args, "fullPath", false);
- final boolean secure = checkArg(args, "secure", false);
- final boolean encode = checkArg(args, "encode", true);
- final String webSiteId = getArg(args, "webSiteId");
+ final boolean fullPath = checkBooleanArg(args, "fullPath", false);
+ final boolean secure = checkBooleanArg(args, "secure", false);
+ final boolean encode = checkBooleanArg(args, "encode", true);
+ final String webSiteId = convertToString(args.get("webSiteId"));
return new Writer(out) {
+
@Override
public void close() throws IOException {
try {
Environment env = Environment.getCurrentEnvironment();
- BeanModel req = (BeanModel) env.getVariable("request");
- BeanModel res = (BeanModel) env.getVariable("response");
- Object prefix = env.getVariable("urlPrefix");
- if (UtilValidate.isNotEmpty(webSiteId)) {
- HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
- Delegator delegator = (Delegator) request.getAttribute("delegator");
- String httpsPort = null;
- String httpsServer = null;
- String httpPort = null;
- String httpServer = null;
- Boolean enableHttps = null;
- StringBuilder newURL = new StringBuilder();
- // make prefix url
- try {
- GenericValue webSite = delegator.findOne("WebSite", UtilMisc.toMap("webSiteId", webSiteId), true);
- if (webSite != null) {
- httpsPort = webSite.getString("httpsPort");
- httpsServer = webSite.getString("httpsHost");
- httpPort = webSite.getString("httpPort");
- httpServer = webSite.getString("httpHost");
- enableHttps = webSite.getBoolean("enableHttps");
- }
- } catch (GenericEntityException e) {
- Debug.logWarning(e, "Problems with WebSite entity; using global defaults", module);
- }
- // fill in any missing properties with fields from the global file
- if (UtilValidate.isEmpty(httpsPort)) {
- httpsPort = UtilProperties.getPropertyValue("url.properties", "port.https", "443");
- }
- if (UtilValidate.isEmpty(httpsServer)) {
- httpsServer = UtilProperties.getPropertyValue("url.properties", "force.https.host");
- }
- if (UtilValidate.isEmpty(httpPort)) {
- httpPort = UtilProperties.getPropertyValue("url.properties", "port.http", "80");
+ // Handle prefix.
+ String prefixString = convertToString(env.getVariable("urlPrefix"));
+ if (!prefixString.isEmpty()) {
+ String bufString = buf.toString();
+ boolean prefixSlash = prefixString.endsWith("/");
+ boolean bufSlash = bufString.startsWith("/");
+ if (prefixSlash && bufSlash) {
+ bufString = bufString.substring(1);
+ } else if (!prefixSlash && !bufSlash) {
+ bufString = "/" + bufString;
}
- if (UtilValidate.isEmpty(httpServer)) {
- httpServer = UtilProperties.getPropertyValue("url.properties", "force.http.host");
- }
- if (enableHttps == null) {
- enableHttps = UtilProperties.propertyValueEqualsIgnoreCase("url.properties", "port.https.enabled", "Y");
- }
- if (secure && enableHttps) {
- String server = httpsServer;
- if (UtilValidate.isEmpty(server)) {
- server = request.getServerName();
- }
- newURL.append("https://");
- newURL.append(httpsServer);
- newURL.append(":").append(httpsPort);
- } else {
- newURL.append("http://");
- newURL.append(httpServer);
- if (!"80".equals(httpPort)) {
- newURL.append(":").append(httpPort);
- }
+ out.write(prefixString + bufString);
+ return;
+ }
+ HttpServletRequest request = FreeMarkerWorker.unwrap(env.getVariable("request"));
+ Delegator delegator = FreeMarkerWorker.unwrap(env.getVariable("delegator"));
+ if (request != null && delegator == null) {
+ delegator = (Delegator) request.getAttribute("delegator");
+ }
+ // Handle web site ID.
+ if (!webSiteId.isEmpty()) {
+ if (delegator == null) {
+ throw new IllegalStateException("Delegator not found");
}
- // make mount point
- String mountPoint = null;
for (WebappInfo webAppInfo : ComponentConfig.getAllWebappResourceInfos()) {
- File file = new File(webAppInfo.getLocation() + "/WEB-INF/web.xml");
- if (!file.exists()) {
- continue;
- }
- InputStream is = new FileInputStream(file);
- try {
- Document doc = UtilXml.readXmlDocument(is, true, null);
- NodeList nList = doc.getElementsByTagName("context-param");
- for (int temp = 0; temp < nList.getLength(); temp++) {
- Node nNode = nList.item(temp);
- if (nNode.getNodeType() == Node.ELEMENT_NODE) {
- Element eElement = (Element) nNode;
- String paramName = getTagValue("param-name", eElement);
- String paramValue = getTagValue("param-value", eElement);
- if ("webSiteId".equals(paramName) && webSiteId.equals(paramValue)) {
- mountPoint = webAppInfo.getContextRoot();
- break;
- }
- }
+ if (webSiteId.equals(WebAppUtil.getWebSiteId(webAppInfo))) {
+ StringBuilder newUrlBuff = new StringBuilder(250);
+ OfbizUrlBuilder builder = OfbizUrlBuilder.from(webAppInfo, delegator);
+ builder.buildFullUrl(newUrlBuff, buf.toString(), secure);
+ String newUrl = newUrlBuff.toString();
+ if (encode) {
+ newUrl = URLEncoder.encode(newUrl, "UTF-8");
}
- } catch (SAXException e) {
- Debug.logWarning(e, e.getMessage(), module);
- } catch (ParserConfigurationException e) {
- Debug.logWarning(e, e.getMessage(), module);
+ out.write(newUrl);
+ return;
}
- if (UtilValidate.isNotEmpty(mountPoint)) {
- if (mountPoint.length() > 1)
- newURL.append(mountPoint);
- break;
- }
- }
- // make the path the the control servlet
- String controlPath = (String) request.getAttribute("_CONTROL_PATH_");
- String[] patch = controlPath.split("/");
- String patchStr = null;
- if (patch.length > 0) {
- patchStr = patch[patch.length - 1];
}
- if (UtilValidate.isNotEmpty(patchStr)) {
- newURL.append("/");
- newURL.append(patchStr);
- }
- newURL.append("/");
- // make requestUrl
- String requestUrl = buf.toString();
- newURL.append(requestUrl);
- out.write(newURL.toString());
- } else if (req != null) {
- HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
+ throw new IllegalArgumentException("Web site ID '" + webSiteId + "' not found.");
+ }
+ if (request != null) {
ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
- HttpServletResponse response = null;
- if (res != null) {
- response = (HttpServletResponse) res.getWrappedObject();
- }
-
+ HttpServletResponse response = FreeMarkerWorker.unwrap(env.getVariable("response"));
String requestUrl = buf.toString();
-
- // make the link
RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
out.write(rh.makeLink(request, response, requestUrl, fullPath, secure, encode));
- } else if (prefix != null) {
- if (prefix instanceof TemplateScalarModel) {
- TemplateScalarModel s = (TemplateScalarModel) prefix;
- String prefixString = s.getAsString();
- String bufString = buf.toString();
- boolean prefixSlash = prefixString.endsWith("/");
- boolean bufSlash = bufString.startsWith("/");
- if (prefixSlash && bufSlash) {
- bufString = bufString.substring(1);
- } else if (!prefixSlash && !bufSlash) {
- bufString = "/" + bufString;
- }
- out.write(prefixString + bufString);
- }
} else {
out.write(buf.toString());
}
- } catch (TemplateModelException e) {
- throw new IOException(e.getMessage());
+ } catch (Exception e) {
+ Debug.logWarning(e, "Exception thrown while running ofbizUrl transform", module);
+ throw new IOException(e);
}
}