You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ofbiz.apache.org by jl...@apache.org on 2020/04/06 10:05:35 UTC
[ofbiz-framework] 02/02: Improved: follow checkstyle conventions in
files committed for CSRF token defense
This is an automated email from the ASF dual-hosted git repository.
jleroux pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/ofbiz-framework.git
commit b95fa36bf48e1e29a269a3a8e39757008801a367
Author: Jacques Le Roux <ja...@les7arts.com>
AuthorDate: Mon Apr 6 12:05:16 2020 +0200
Improved: follow checkstyle conventions in files committed for CSRF token defense
Mostly manually-automated, so some changes are not perfect. I have manually
changed back excessive ones
Comments out ArrayTypeStyle checkstyle
Updates checkstyleMain.maxErrors
---
.../category/ftl/CatalogAltUrlSeoTransform.java | 45 ++++---
.../category/ftl/CatalogUrlSeoTransform.java | 109 ++++++++++------
.../product/category/ftl/UrlRegexpTransform.java | 26 ++--
build.gradle | 8 +-
config/checkstyle/checkstyle.xml | 2 +-
.../java/org/apache/ofbiz/common/CommonEvents.java | 49 ++++---
.../apache/ofbiz/security/CsrfDefenseStrategy.java | 22 ++--
.../java/org/apache/ofbiz/security/CsrfUtil.java | 145 +++++++++++++--------
.../ofbiz/security/ICsrfDefenseStrategy.java | 5 +-
.../ofbiz/security/NoCsrfDefenseStrategy.java | 4 +-
.../org/apache/ofbiz/security/CsrfUtilTests.java | 8 +-
.../ofbiz/webapp/control/ConfigXMLReader.java | 102 +++++++++------
.../ofbiz/webapp/ftl/CsrfTokenAjaxTransform.java | 3 +-
.../webapp/ftl/CsrfTokenPairNonAjaxTransform.java | 4 +-
.../java/org/apache/ofbiz/widget/WidgetWorker.java | 4 +-
.../widget/renderer/macro/MacroFormRenderer.java | 2 +-
16 files changed, 327 insertions(+), 211 deletions(-)
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogAltUrlSeoTransform.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogAltUrlSeoTransform.java
index b98ad2a..dfe9e08 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogAltUrlSeoTransform.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogAltUrlSeoTransform.java
@@ -25,7 +25,6 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
-import org.apache.ofbiz.security.CsrfUtil;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.template.FreeMarkerWorker;
@@ -38,6 +37,7 @@ import org.apache.ofbiz.product.category.CatalogUrlFilter;
import org.apache.ofbiz.product.category.CategoryContentWrapper;
import org.apache.ofbiz.product.category.SeoConfigUtil;
import org.apache.ofbiz.product.product.ProductContentWrapper;
+import org.apache.ofbiz.security.CsrfUtil;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.webapp.OfbizUrlBuilder;
import org.apache.ofbiz.webapp.control.WebAppConfigurationException;
@@ -52,7 +52,7 @@ import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
public class CatalogAltUrlSeoTransform implements TemplateTransformModel {
- public final static String MODULE = CatalogUrlSeoTransform.class.getName();
+ public static final String MODULE = CatalogUrlSeoTransform.class.getName();
public String getStringArg(Map<?, ?> args, String key) {
Object o = args.get(key);
@@ -119,15 +119,19 @@ public class CatalogAltUrlSeoTransform implements TemplateTransformModel {
StringBuilder newURL = new StringBuilder();
if (UtilValidate.isNotEmpty(productId)) {
if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
- url = CatalogUrlSeoTransform.makeProductUrl(request, productId, productCategoryId, previousCategoryId);
+ url = CatalogUrlSeoTransform.makeProductUrl(request, productId, productCategoryId,
+ previousCategoryId);
} else {
- url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId, productId);
+ url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId,
+ productId);
}
} else {
if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
- url = CatalogUrlSeoTransform.makeCategoryUrl(request, productCategoryId, previousCategoryId, viewSize, viewIndex, viewSort, searchString);
+ url = CatalogUrlSeoTransform.makeCategoryUrl(request, productCategoryId,
+ previousCategoryId, viewSize, viewIndex, viewSort, searchString);
} else {
- url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
+ url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId,
+ productId, viewSize, viewIndex, viewSort, searchString);
}
}
@@ -158,21 +162,32 @@ public class CatalogAltUrlSeoTransform implements TemplateTransformModel {
contextPath = prefixString.substring(prefixString.lastIndexOf('/'));
}
if (UtilValidate.isNotEmpty(productId)) {
- GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
- ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
+ GenericValue product = EntityQuery.use(delegator).from("Product")
+ .where("productId", productId).queryOne();
+ ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale,
+ EntityUtilProperties.getPropertyValue("content", "defaultMimeType",
+ "text/html; charset=utf-8", delegator));
if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
- url = CatalogUrlSeoTransform.makeProductUrl(delegator, wrapper, prefixString, contextPath, productCategoryId, previousCategoryId, productId);
+ url = CatalogUrlSeoTransform.makeProductUrl(delegator, wrapper, prefixString,
+ contextPath, productCategoryId, previousCategoryId, productId);
} else {
- url = CatalogUrlFilter.makeProductUrl(wrapper, null, prefixString, previousCategoryId, productCategoryId, productId);
+ url = CatalogUrlFilter.makeProductUrl(wrapper, null, prefixString, previousCategoryId,
+ productCategoryId, productId);
}
} else {
- GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).queryOne();
- CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
+ GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory")
+ .where("productCategoryId", productCategoryId).queryOne();
+ CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory,
+ locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType",
+ "text/html; charset=utf-8", delegator));
if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
- url = CatalogUrlSeoTransform.makeCategoryUrl(delegator, wrapper, prefixString, productCategoryId, previousCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
+ url = CatalogUrlSeoTransform.makeCategoryUrl(delegator, wrapper, prefixString,
+ productCategoryId, previousCategoryId, productId, viewSize, viewIndex, viewSort,
+ searchString);
} else {
- url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, prefixString, previousCategoryId, productCategoryId,
- productId, viewSize, viewIndex, viewSort, searchString);
+ url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, prefixString,
+ previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort,
+ searchString);
}
}
out.write(url);
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java
index 3f19e13..5daf489 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java
@@ -44,6 +44,7 @@ import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityExpr;
import org.apache.ofbiz.entity.condition.EntityOperator;
+import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.product.category.CatalogUrlServlet;
import org.apache.ofbiz.product.category.CategoryContentWrapper;
import org.apache.ofbiz.product.category.CategoryWorker;
@@ -61,10 +62,9 @@ import freemarker.ext.beans.StringModel;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
-import org.apache.ofbiz.entity.util.EntityQuery;
public class CatalogUrlSeoTransform implements TemplateTransformModel {
- public final static String MODULE = CatalogUrlSeoTransform.class.getName();
+ public static final String MODULE = CatalogUrlSeoTransform.class.getName();
private static Map<String, String> categoryNameIdMap = null;
private static Map<String, String> categoryIdNameMap = null;
@@ -130,12 +130,14 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
String catalogUrl = "";
if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
if (UtilValidate.isEmpty(productId)) {
- catalogUrl = makeCategoryUrl(request, currentCategoryId, previousCategoryId, null, null, null, null);
+ catalogUrl = makeCategoryUrl(request, currentCategoryId, previousCategoryId, null, null,
+ null, null);
} else {
catalogUrl = makeProductUrl(request, productId, currentCategoryId, previousCategoryId);
}
} else {
- catalogUrl = CatalogUrlServlet.makeCatalogUrl(request, productId, currentCategoryId, previousCategoryId);
+ catalogUrl = CatalogUrlServlet.makeCatalogUrl(request, productId, currentCategoryId,
+ previousCategoryId);
}
out.write(catalogUrl);
}
@@ -174,11 +176,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
}
/**
- * Initial category-name/category-id map.
- * Note: as a key, the category-name should be:
- * 1. ascii
- * 2. lower cased and use hyphen between the words.
- * If not, the category id will be used.
+ * Initial category-name/category-id map. Note: as a key, the category-name should be: 1. ascii 2. lower cased and
+ * use hyphen between the words. If not, the category id will be used.
*
*/
public static synchronized void initCategoryMap(HttpServletRequest request) {
@@ -193,7 +192,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
Perl5Matcher matcher = new Perl5Matcher();
try {
- Collection<GenericValue> allCategories = delegator.findList("ProductCategory", null, UtilMisc.toSet("productCategoryId", "categoryName"), null, null, false);
+ Collection<GenericValue> allCategories = delegator.findList("ProductCategory", null,
+ UtilMisc.toSet("productCategoryId", "categoryName"), null, null, false);
for (GenericValue category : allCategories) {
String categoryName = category.getString("categoryName");
String categoryNameId = null;
@@ -203,18 +203,22 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
categoryName = SeoUrlUtil.replaceSpecialCharsUrl(categoryName.trim());
if (matcher.matches(categoryName, asciiPattern)) {
categoryIdName = categoryName.replaceAll(" ", URL_HYPHEN);
- categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN);
+ categoryNameId = categoryIdName + URL_HYPHEN
+ + categoryId.trim().replaceAll(" ", URL_HYPHEN);
} else {
categoryIdName = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryNameId = categoryIdName;
}
} else {
- GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", categoryId).cache().queryOne();
+ GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory")
+ .where("productCategoryId", categoryId).cache().queryOne();
CategoryContentWrapper wrapper = new CategoryContentWrapper(productCategory, request);
StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url");
- if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
+ if (UtilValidate.isNotEmpty(alternativeUrl)
+ && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
categoryIdName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString());
- categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN);
+ categoryNameId = categoryIdName + URL_HYPHEN
+ + categoryId.trim().replaceAll(" ", URL_HYPHEN);
} else {
categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryIdName = categoryNameId;
@@ -224,7 +228,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryIdName = categoryNameId;
}
- if (!matcher.matches(categoryNameId, asciiPattern) || categoryNameIdMap.containsKey(categoryNameId)) {
+ if (!matcher.matches(categoryNameId, asciiPattern)
+ || categoryNameIdMap.containsKey(categoryNameId)) {
continue;
}
categoryNameIdMap.put(categoryNameId, categoryId);
@@ -242,7 +247,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
*
* @return String a catalog url
*/
- public static String makeProductUrl(HttpServletRequest request, String productId, String currentCategoryId, String previousCategoryId) {
+ public static String makeProductUrl(HttpServletRequest request, String productId, String currentCategoryId,
+ String previousCategoryId) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
if (!isCategoryMapInitialed()) {
initCategoryMap(request);
@@ -259,7 +265,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
} catch (GenericEntityException e) {
- Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(), MODULE);
+ Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(),
+ MODULE);
}
}
if (product != null) {
@@ -270,7 +277,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
List<String> trail = CategoryWorker.getTrail(request);
trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId);
if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
- for (String trailCategoryId: trail) {
+ for (String trailCategoryId : trail) {
if ("TOP".equals(trailCategoryId)) {
continue;
}
@@ -331,7 +338,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
*
* @return String a category url
*/
- public static String makeCategoryUrl(HttpServletRequest request, String currentCategoryId, String previousCategoryId, String viewSize, String viewIndex, String viewSort, String searchString) {
+ public static String makeCategoryUrl(HttpServletRequest request, String currentCategoryId,
+ String previousCategoryId, String viewSize, String viewIndex, String viewSort, String searchString) {
if (!isCategoryMapInitialed()) {
initCategoryMap(request);
@@ -395,7 +403,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
urlBuilder.append("searchString=" + searchString + "&");
}
if (urlBuilder.toString().endsWith("&")) {
- return urlBuilder.toString().substring(0, urlBuilder.toString().length()-1);
+ return urlBuilder.toString().substring(0, urlBuilder.toString().length() - 1);
}
return urlBuilder.toString();
@@ -406,7 +414,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
*
* @return String a catalog url
*/
- public static String makeProductUrl(String contextPath, List<String> trail, String productId, String productName, String currentCategoryId, String previousCategoryId) {
+ public static String makeProductUrl(String contextPath, List<String> trail, String productId, String productName,
+ String currentCategoryId, String previousCategoryId) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(contextPath);
if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
@@ -421,7 +430,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
if (UtilValidate.isNotEmpty(currentCategoryId)) {
trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId);
if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
- for (String trailCategoryId: trail) {
+ for (String trailCategoryId : trail) {
if ("TOP".equals(trailCategoryId)) {
continue;
}
@@ -465,7 +474,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
/**
* Get a string lower cased and hyphen connected.
*
- * @param name a String to be transformed
+ * @param name
+ * a String to be transformed
* @return String nice name
*/
protected static String getNiceName(String name) {
@@ -480,16 +490,19 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
return niceName;
}
- public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator) throws ServletException, IOException {
+ public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response,
+ Delegator delegator) throws ServletException, IOException {
return forwardProductUri(request, response, delegator, null);
}
- public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException {
+ public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response,
+ Delegator delegator, String controlServlet) throws ServletException, IOException {
return forwardUri(request, response, delegator, controlServlet);
}
/**
* Forward a uri according to forward pattern regular expressions.
+ *
* @param request
* @param response
* @param delegator
@@ -498,7 +511,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
* @throws ServletException
* @throws IOException
*/
- public static boolean forwardUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException {
+ public static boolean forwardUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator,
+ String controlServlet) throws ServletException, IOException {
String pathInfo = request.getRequestURI();
String contextPath = request.getContextPath();
if (!isCategoryMapInitialed()) {
@@ -526,12 +540,14 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
if (UtilValidate.isNotEmpty(lastPathElement)) {
if (UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) {
if (lastPathElement.endsWith(SeoConfigUtil.getCategoryUrlSuffix())) {
- lastPathElement = lastPathElement.substring(0, lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length());
+ lastPathElement = lastPathElement.substring(0,
+ lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length());
} else {
return false;
}
}
- if (SeoConfigUtil.isCategoryNameEnabled() || pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) {
+ if (SeoConfigUtil.isCategoryNameEnabled()
+ || pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) {
for (Entry<String, String> entry : categoryNameIdMap.entrySet()) {
String categoryName = entry.getKey();
if (lastPathElement.startsWith(categoryName)) {
@@ -551,11 +567,13 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
List<String> urlElements = StringUtil.split(lastPathElement, URL_HYPHEN);
if (UtilValidate.isEmpty(urlElements)) {
try {
- if (EntityQuery.use(delegator).from("Product").where("productId", lastPathElement).cache().queryOne() != null) {
+ if (EntityQuery.use(delegator).from("Product").where("productId", lastPathElement).cache()
+ .queryOne() != null) {
productId = lastPathElement;
}
} catch (GenericEntityException e) {
- Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE);
+ Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo
+ + "]: " + e.toString(), MODULE);
}
} else {
int i = urlElements.size() - 1;
@@ -563,9 +581,12 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
while (i >= 0) {
try {
List<EntityExpr> exprs = new LinkedList<>();
- exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, lastPathElement));
+ exprs.add(
+ EntityCondition.makeCondition("productId", EntityOperator.EQUALS, lastPathElement));
exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, tempProductId));
- List<GenericValue> products = delegator.findList("Product", EntityCondition.makeCondition(exprs, EntityOperator.OR), UtilMisc.toSet("productId", "productName"), null, null, true);
+ List<GenericValue> products = delegator.findList("Product",
+ EntityCondition.makeCondition(exprs, EntityOperator.OR),
+ UtilMisc.toSet("productId", "productName"), null, null, true);
if (products != null && products.size() > 0) {
if (products.size() == 1) {
@@ -578,7 +599,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
tempProductId = urlElements.get(i - 1) + URL_HYPHEN + tempProductId;
}
} catch (GenericEntityException e) {
- Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE);
+ Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo
+ + "]: " + e.toString(), MODULE);
}
i--;
}
@@ -600,7 +622,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
if (UtilValidate.isNotEmpty(controlServlet)) {
urlBuilder.append("/" + controlServlet);
}
- urlBuilder.append("/" + (productId != null ? CatalogUrlServlet.PRODUCT_REQUEST : CatalogUrlServlet.CATEGORY_REQUEST));
+ urlBuilder.append(
+ "/" + (productId != null ? CatalogUrlServlet.PRODUCT_REQUEST : CatalogUrlServlet.CATEGORY_REQUEST));
UrlServletHelper.setViewQueryParameters(request, urlBuilder);
Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", MODULE);
RequestDispatcher rd = request.getRequestDispatcher(urlBuilder.toString());
@@ -612,6 +635,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
/**
* Forward a category uri according to forward pattern regular expressions.
+ *
* @param request
* @param response
* @param delegator
@@ -620,7 +644,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
* @throws ServletException
* @throws IOException
*/
- public static boolean forwardCategoryUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException {
+ public static boolean forwardCategoryUri(HttpServletRequest request, HttpServletResponse response,
+ Delegator delegator, String controlServlet) throws ServletException, IOException {
String pathInfo = request.getRequestURI();
String contextPath = request.getContextPath();
if (!isCategoryMapInitialed()) {
@@ -638,7 +663,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
if (UtilValidate.isNotEmpty(lastPathElement)) {
if (UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) {
if (lastPathElement.endsWith(SeoConfigUtil.getCategoryUrlSuffix())) {
- lastPathElement = lastPathElement.substring(0, lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length());
+ lastPathElement = lastPathElement.substring(0,
+ lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length());
} else {
return false;
}
@@ -682,8 +708,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
* @param productId
* @return
*/
- public static String makeProductUrl(Delegator delegator, ProductContentWrapper wrapper, String prefix, String contextPath, String currentCategoryId, String previousCategoryId,
- String productId) {
+ public static String makeProductUrl(Delegator delegator, ProductContentWrapper wrapper, String prefix,
+ String contextPath, String currentCategoryId, String previousCategoryId, String productId) {
StringBuilder urlBuilder = new StringBuilder();
GenericValue product = null;
urlBuilder.append(prefix);
@@ -694,7 +720,8 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
} catch (GenericEntityException e) {
- Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(), MODULE);
+ Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(),
+ MODULE);
}
}
if (product != null) {
@@ -705,7 +732,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
List<String> trail = null;
trail = CategoryWorker.adjustTrail(null, currentCategoryId, previousCategoryId);
if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
- for (String trailCategoryId: trail) {
+ for (String trailCategoryId : trail) {
if ("TOP".equals(trailCategoryId)) {
continue;
}
@@ -836,7 +863,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel {
urlBuilder.append("searchString=" + searchString + "&");
}
if (urlBuilder.toString().endsWith("&")) {
- return urlBuilder.toString().substring(0, urlBuilder.toString().length()-1);
+ return urlBuilder.toString().substring(0, urlBuilder.toString().length() - 1);
}
return urlBuilder.toString();
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/UrlRegexpTransform.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/UrlRegexpTransform.java
index a091263..5777adc 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/UrlRegexpTransform.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/UrlRegexpTransform.java
@@ -29,13 +29,13 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.ofbiz.base.component.ComponentConfig;
-import org.apache.ofbiz.security.CsrfUtil;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.template.FreeMarkerWorker;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.product.category.SeoConfigUtil;
+import org.apache.ofbiz.security.CsrfUtil;
import org.apache.ofbiz.webapp.OfbizUrlBuilder;
import org.apache.ofbiz.webapp.WebAppUtil;
import org.apache.ofbiz.webapp.control.RequestHandler;
@@ -59,12 +59,11 @@ public class UrlRegexpTransform implements TemplateTransformModel {
private static final String MODULE = UrlRegexpTransform.class.getName();
-
private static String convertToString(Object o) {
String result = "";
if (o != null) {
if (Debug.verboseOn()) {
- Debug.logVerbose("Arg Object : " + o.getClass().getName(), MODULE);
+ Debug.logVerbose("Arg Object : " + o.getClass().getName(), MODULE);
}
if (o instanceof TemplateScalarModel) {
TemplateScalarModel s = (TemplateScalarModel) o;
@@ -141,7 +140,7 @@ public class UrlRegexpTransform implements TemplateTransformModel {
// add / update csrf token to link when required
String tokenValue = CsrfUtil.generateTokenForNonAjax(request,
- controlPath + (requestURI.startsWith("/") ? requestURI : "/"+requestURI));
+ controlPath + (requestURI.startsWith("/") ? requestURI : "/" + requestURI));
seoUrl = CsrfUtil.addOrUpdateTokenInUrl(seoUrl, tokenValue);
out.write(seoUrl);
@@ -176,11 +175,8 @@ public class UrlRegexpTransform implements TemplateTransformModel {
} else {
out.write(buf.toString());
}
- } catch (IOException |
- SAXException |
- TemplateModelException |
- GenericEntityException |
- WebAppConfigurationException e) {
+ } catch (IOException | SAXException | TemplateModelException | GenericEntityException
+ | WebAppConfigurationException e) {
throw new IOException(e.getMessage());
}
}
@@ -190,8 +186,10 @@ public class UrlRegexpTransform implements TemplateTransformModel {
/**
* Transform a url according to seo pattern regular expressions.
*
- * @param url String to do the seo transform
- * @param isAnon boolean to indicate whether it's an anonymous visit.
+ * @param url
+ * String to do the seo transform
+ * @param isAnon
+ * boolean to indicate whether it's an anonymous visit.
*
* @return String the transformed url.
*/
@@ -251,14 +249,16 @@ public class UrlRegexpTransform implements TemplateTransformModel {
/**
* Forward a uri according to forward pattern regular expressions. Note: this is developed for Filter usage.
*
- * @param uri String to reverse transform
+ * @param uri
+ * String to reverse transform
* @return String
*/
public static boolean forwardUri(HttpServletResponse response, String uri) {
Perl5Matcher matcher = new Perl5Matcher();
boolean foundMatch = false;
Integer responseCodeInt = null;
- if (SeoConfigUtil.checkUseUrlRegexp() && SeoConfigUtil.getSeoPatterns() != null && SeoConfigUtil.getForwardReplacements() != null) {
+ if (SeoConfigUtil.checkUseUrlRegexp() && SeoConfigUtil.getSeoPatterns() != null
+ && SeoConfigUtil.getForwardReplacements() != null) {
Iterator<String> keys = SeoConfigUtil.getSeoPatterns().keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
diff --git a/build.gradle b/build.gradle
index 8bae19d..868caca 100644
--- a/build.gradle
+++ b/build.gradle
@@ -58,10 +58,10 @@ if (project.hasProperty('enableOwasp')) {
* Syntax: gradlew -PenableDependencyUpdates dependencyUpdates -Drevision=release
*
* You may want to use the use-latest-versions plugin to help you in your work
- * Syntax:
+ * Syntax:
* Check only: gradlew -PenableDependencyUpdates useLatestVersions && gradlew -PenableDependencyUpdates useLatestVersionsCheck
* Automated update: gradlew -PenableDependencyUpdates useLatestVersions
- * Beware that this is only a help.
+ * Beware that this is only a help.
* If you use it without check you will need to check things by yourself (can be as tedious as not using this plugin)
*/
if (project.hasProperty('enableDependencyUpdates')) {
@@ -283,10 +283,10 @@ jar.manifest.attributes(
checkstyle {
// Defining a maximum number of “tolerated” errors ensures that
// this number cannot increase in the future. It corresponds to
- // the sum of errors that were present before introducing the
+ // the sum of errors found last time it was changed after using the
// ‘checkstyle’ tool present in the framework and in the official
// plugins.
- tasks.checkstyleMain.maxErrors = 37713
+ tasks.checkstyleMain.maxErrors = 36923
// Currently there are a lot of errors so we need to temporarily
// hide them to avoid polluting the terminal output.
showViolations = false
diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
index 1cf0bf7..0788c24 100644
--- a/config/checkstyle/checkstyle.xml
+++ b/config/checkstyle/checkstyle.xml
@@ -121,7 +121,7 @@ under the License.
<module name="VisibilityModifier"/>
<!-- Miscellaneous other checks -->
- <module name="ArrayTypeStyle"/>
+ <!-- module name="ArrayTypeStyle"/-->
<module name="UpperEll"/>
<module name="Indentation">
<property name="caseIndent" value="0"/>
diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/CommonEvents.java b/framework/common/src/main/java/org/apache/ofbiz/common/CommonEvents.java
index eee5006..f03a87d 100644
--- a/framework/common/src/main/java/org/apache/ofbiz/common/CommonEvents.java
+++ b/framework/common/src/main/java/org/apache/ofbiz/common/CommonEvents.java
@@ -63,7 +63,8 @@ public class CommonEvents {
public static final String MODULE = CommonEvents.class.getName();
- private static final String[] ignoreAttrs = new String[] { // Attributes removed for security reason; _ERROR_MESSAGE_ and _ERROR_MESSAGE_LIST are kept
+ // Attributes removed for security reason; _ERROR_MESSAGE_ and _ERROR_MESSAGE_LIST are kept
+ private static final String[] IGNOREATTRS = new String[] {
"javax.servlet.request.key_size",
"_CONTEXT_ROOT_",
"_FORWARDED_FROM_SERVLET_",
@@ -81,8 +82,10 @@ public class CommonEvents {
"requestMapMap" // requestMapMap is used by CSRFUtil
};
- /** Simple event to set the users per-session locale setting. The user's locale
- * setting should be passed as a "newLocale" request parameter. */
+ /**
+ * Simple event to set the users per-session locale setting. The user's locale setting should be passed as a
+ * "newLocale" request parameter.
+ */
public static String setSessionLocale(HttpServletRequest request, HttpServletResponse response) {
String localeString = request.getParameter("newLocale");
if (UtilValidate.isNotEmpty(localeString)) {
@@ -178,7 +181,7 @@ public class CommonEvents {
Map<String, Object> attrMap = UtilHttp.getJSONAttributeMap(request);
- for (String ignoreAttr : ignoreAttrs) {
+ for (String ignoreAttr : IGNOREATTRS) {
if (attrMap.containsKey(ignoreAttr)) {
attrMap.remove(ignoreAttr);
}
@@ -192,11 +195,13 @@ public class CommonEvents {
return "success";
}
- private static void writeJSONtoResponse(JSON json, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
+ private static void writeJSONtoResponse(JSON json, HttpServletRequest request, HttpServletResponse response)
+ throws UnsupportedEncodingException {
String jsonStr = json.toString();
String httpMethod = request.getMethod();
- // This was added for security reason (OFBIZ-5409), you might need to remove the "//" prefix when handling the JSON response
+ // This was added for security reason (OFBIZ-5409), you might need to remove the "//" prefix when handling the
+ // JSON response
// Though normally you simply have to access the data you want, so should not be annoyed by the "//" prefix
if ("GET".equalsIgnoreCase(httpMethod)) {
Debug.logWarning("for security reason (OFBIZ-5409) the '//' prefix was added handling the JSON response. "
@@ -205,7 +210,7 @@ public class CommonEvents {
+ "In case, the util.js scrpt is there to help you."
+ "This can be customized in general.properties with the http.json.xssi.prefix property", MODULE);
Delegator delegator = (Delegator) request.getAttribute("delegator");
- String xssiPrefix =EntityUtilProperties.getPropertyValue("general", "http.json.xssi.prefix", delegator);
+ String xssiPrefix = EntityUtilProperties.getPropertyValue("general", "http.json.xssi.prefix", delegator);
jsonStr = xssiPrefix + jsonStr;
}
@@ -257,13 +262,14 @@ public class CommonEvents {
return "success";
}
- public static String getJSONuiLabel(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
+ public static String getJSONuiLabel(HttpServletRequest request, HttpServletResponse response)
+ throws UnsupportedEncodingException, IOException {
// Format - {resource : key}
String jsonString = request.getParameter("requiredLabel");
Map<String, String> uiLabelObject = null;
if (UtilValidate.isNotEmpty(jsonString)) {
JSON json = JSON.from(jsonString);
- uiLabelObject = UtilGenerics.<Map<String, String>>cast(json.toObject(Map.class));
+ uiLabelObject = UtilGenerics.<Map<String, String>> cast(json.toObject(Map.class));
}
if (UtilValidate.isEmpty(uiLabelObject)) {
Debug.logError("No resource and labels found in JSON string: " + jsonString, MODULE);
@@ -290,18 +296,23 @@ public class CommonEvents {
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
- final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default");
- final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator);
+ final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
+ "default");
+ final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha",
+ "captcha." + captchaSizeConfigName, delegator);
final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
- final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored
+ // this is used to uniquely identify in the user session the attribute where the captcha code
+ // for the last captcha for the form is stored
+ final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), "");
final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
final int height = Integer.parseInt(captchaSizeConfigs[1]);
final int width = Integer.parseInt(captchaSizeConfigs[2]);
final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
- final char[] availableChars = EntityUtilProperties.getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();
+ final char[] availableChars = EntityUtilProperties
+ .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();
- //It is possible to pass the font size, image width and height with the request as well
+ // It is possible to pass the font size, image width and height with the request as well
Color backgroundColor = Color.gray;
Color borderColor = Color.DARK_GRAY;
Color textColor = Color.ORANGE;
@@ -317,7 +328,7 @@ public class CommonEvents {
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
- //Generating some circles for background noise
+ // Generating some circles for background noise
g.setColor(circleColor);
for (int i = 0; i < circlesToDraw; i++) {
int circleRadius = (int) (Math.random() * height / 2.0);
@@ -384,13 +395,15 @@ public class CommonEvents {
return "success";
}
- public static String loadJWT(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
+ public static String loadJWT(HttpServletRequest request, HttpServletResponse response)
+ throws UnsupportedEncodingException {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Map<String, String> types = new HashMap<>();
String securedUserLoginId = LoginWorker.getSecuredUserLoginId(request);
if (securedUserLoginId != null) {
types.put("userLoginId", securedUserLoginId);
- int ttlSeconds = (int) Long.parseLong(EntityUtilProperties.getPropertyValue("security", "security.jwt.token.expireTime", "10", delegator));
+ int ttlSeconds = (int) Long.parseLong(EntityUtilProperties.getPropertyValue("security",
+ "security.jwt.token.expireTime", "10", delegator));
String token = JWTManager.createJwt(delegator, types, ttlSeconds);
writeJSONtoResponse(JSON.from(token), request, response);
} else {
@@ -398,5 +411,5 @@ public class CommonEvents {
}
return "success";
}
-
+
}
diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfDefenseStrategy.java b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfDefenseStrategy.java
index 5b72990..3262ac6 100644
--- a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfDefenseStrategy.java
+++ b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfDefenseStrategy.java
@@ -29,17 +29,18 @@ import org.apache.ofbiz.webapp.control.RequestHandlerExceptionAllowExternalReque
public class CsrfDefenseStrategy implements ICsrfDefenseStrategy {
- public static final String module = CsrfDefenseStrategy.class.getName();
+ public static final String MODULE = CsrfDefenseStrategy.class.getName();
private static SecureRandom secureRandom = null;
- private static final String prng = "SHA1PRNG";
+ private static final String PRNG = "SHA1PRNG";
private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- private static int csrfEntityErequestLimit = (int) Long.parseLong(UtilProperties.getPropertyValue("security", "csrf.entity.request.limit", "3"));
+ private static int requestlimit = (int) Long.parseLong(
+ UtilProperties.getPropertyValue("security", "csrf.entity.request.limit", "3"));
- static{
+ static {
try {
- secureRandom = SecureRandom.getInstance(prng);
+ secureRandom = SecureRandom.getInstance(PRNG);
} catch (NoSuchAlgorithmException e) {
- Debug.logError(e, module);
+ Debug.logError(e, MODULE);
}
}
@@ -55,9 +56,9 @@ public class CsrfDefenseStrategy implements ICsrfDefenseStrategy {
}
@Override
- public int maxSubFolderInRequestUrlForTokenMapLookup(String requestUri){
- if (requestUri.startsWith("entity/")){
- return csrfEntityErequestLimit;
+ public int maxSubFolderInRequestUrlForTokenMapLookup(String requestUri) {
+ if (requestUri.startsWith("entity/")) {
+ return requestlimit;
}
return 0;
}
@@ -84,7 +85,8 @@ public class CsrfDefenseStrategy implements ICsrfDefenseStrategy {
}
@Override
- public void invalidTokenResponse(String requestUri, HttpServletRequest request) throws RequestHandlerExceptionAllowExternalRequests {
+ public void invalidTokenResponse(String requestUri, HttpServletRequest request)
+ throws RequestHandlerExceptionAllowExternalRequests {
request.setAttribute("_ERROR_MESSAGE_",
"Invalid or missing CSRF token to path '" + request.getPathInfo() + "'. Click <a href='"
+ request.getContextPath() + "'>here</a> to continue.");
diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java
index ade9191..5309ac2 100644
--- a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java
+++ b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java
@@ -43,14 +43,18 @@ import org.apache.ofbiz.webapp.control.RequestHandlerException;
import org.apache.ofbiz.webapp.control.RequestHandlerExceptionAllowExternalRequests;
import org.apache.ofbiz.webapp.control.WebAppConfigurationException;
-public class CsrfUtil {
+public final class CsrfUtil {
public static final String MODULE = CsrfUtil.class.getName();
- public static String tokenNameNonAjax = UtilProperties.getPropertyValue("security", "csrf.tokenName.nonAjax", "csrf");
- public static ICsrfDefenseStrategy strategy;
- private static int cacheSize = (int) Long.parseLong(UtilProperties.getPropertyValue("security", "csrf.cache.size", "5000"));
- private static LinkedHashMap<String, Map<String, Map<String, String>>> csrfTokenCache = new LinkedHashMap<String, Map<String, Map<String, String>>>() {
+ private static String tokenNameNonAjax = UtilProperties.getPropertyValue("security", "csrf.tokenName.nonAjax",
+ "csrf");
+ private static ICsrfDefenseStrategy strategy;
+ private static int cacheSize = (int) Long
+ .parseLong(UtilProperties.getPropertyValue("security", "csrf.cache.size", "5000"));
+ private static LinkedHashMap<String, Map<String, Map<String, String>>> csrfTokenCache =
+ new LinkedHashMap<String, Map<String, Map<String, String>>>() {
private static final long serialVersionUID = 1L;
+
protected boolean removeEldestEntry(Map.Entry<String, Map<String, Map<String, String>>> eldest) {
return size() > cacheSize; // TODO use also csrf.cache.size here?
}
@@ -61,17 +65,18 @@ public class CsrfUtil {
static {
try {
- String className = UtilProperties.getPropertyValue("security", "csrf.defense.strategy", NoCsrfDefenseStrategy.class.getCanonicalName());
+ String className = UtilProperties.getPropertyValue("security", "csrf.defense.strategy",
+ NoCsrfDefenseStrategy.class.getCanonicalName());
Class<?> c = Class.forName(className);
- strategy = (ICsrfDefenseStrategy)c.newInstance();
- } catch (Exception e){
+ setStrategy((ICsrfDefenseStrategy) c.newInstance());
+ } catch (Exception e) {
Debug.logError(e, MODULE);
- strategy = new CsrfDefenseStrategy();
+ setStrategy(new CsrfDefenseStrategy());
}
}
public static Map<String, String> getTokenMap(HttpServletRequest request, String targetContextPath) {
-
+
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
String partyId = null;
@@ -91,6 +96,7 @@ public class CsrfUtil {
if (tokenMap == null) {
tokenMap = new LinkedHashMap<String, String>() {
private static final long serialVersionUID = 1L;
+
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > cacheSize;
}
@@ -102,6 +108,7 @@ public class CsrfUtil {
if (tokenMap == null) {
tokenMap = new LinkedHashMap<String, String>() {
private static final long serialVersionUID = 1L;
+
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > cacheSize;
}
@@ -113,26 +120,27 @@ public class CsrfUtil {
}
private static String generateToken() {
- return strategy.generateToken();
+ return getStrategy().generateToken();
}
/**
* Reduce number of subfolder from request uri, if needed, before using it to generate CSRF token.
+ *
* @param requestUri
* @return
*/
- static String getRequestUriWithSubFolderLimit(String requestUri){
- int limit = CsrfUtil.strategy.maxSubFolderInRequestUrlForTokenMapLookup(requestUri);
- if (limit<1){
+ static String getRequestUriWithSubFolderLimit(String requestUri) {
+ int limit = CsrfUtil.getStrategy().maxSubFolderInRequestUrlForTokenMapLookup(requestUri);
+ if (limit < 1) {
return requestUri;
}
- while(StringUtils.countMatches(requestUri, "/")+1>limit){
+ while (StringUtils.countMatches(requestUri, "/") + 1 > limit) {
requestUri = requestUri.substring(0, requestUri.lastIndexOf("/"));
}
return requestUri;
}
- static String getRequestUriFromPath(String pathOrRequestUri){
+ static String getRequestUriFromPath(String pathOrRequestUri) {
String requestUri = pathOrRequestUri;
// remove any query string
if (requestUri.contains("?")) {
@@ -148,7 +156,7 @@ public class CsrfUtil {
// e.g. "/viewprofile" to "viewprofile"
requestUri = requestUri.substring(1);
}
- if (requestUri.contains("#")){
+ if (requestUri.contains("#")) {
// e.g. "view/entityref_main#org.apache.ofbiz.accounting.budget" to "view/entityref_main"
requestUri = requestUri.substring(0, requestUri.indexOf("#"));
}
@@ -157,32 +165,31 @@ public class CsrfUtil {
/**
* Generate CSRF token for non-ajax request if required and add it as key to token map in session When token map
- * size limit is reached, the eldest entry will be deleted each time a new entry is added.
- * Token only generated for up to 3 subfolders in the path so 'entity/find/Budget/0001' and 'entity/find/Budget/0002'
- * should share the same CSRF token.
- *
+ * size limit is reached, the eldest entry will be deleted each time a new entry is added. Token only generated for
+ * up to 3 subfolders in the path so 'entity/find/Budget/0001' and 'entity/find/Budget/0002' should share the same
+ * CSRF token.
+ *
* @param request
* @param pathOrRequestUri
* @return csrf token
*/
public static String generateTokenForNonAjax(HttpServletRequest request, String pathOrRequestUri) {
- if (UtilValidate.isEmpty(pathOrRequestUri)
- || pathOrRequestUri.startsWith("javascript")
- || pathOrRequestUri.startsWith("#") ) {
+ if (UtilValidate.isEmpty(pathOrRequestUri) || pathOrRequestUri.startsWith("javascript")
+ || pathOrRequestUri.startsWith("#")) {
return "";
}
-
+
if (pathOrRequestUri.contains("/")) {
pathOrRequestUri = pathOrRequestUri.replaceAll("/", "/");
}
String requestUri = getRequestUriWithSubFolderLimit(getRequestUriFromPath(pathOrRequestUri));
-
+
Map<String, String> tokenMap = null;
ConfigXMLReader.RequestMap requestMap = null;
- // TODO when OFBIZ-11354 will be done this will need to be removed even if it should be OK as is
- if (pathOrRequestUri.contains("/control/")) {
+ // TODO when OFBIZ-11354 will be done this will need to be removed even if it should be OK as is
+ if (pathOrRequestUri.contains("/control/")) {
tokenMap = getTokenMap(request, "/" + RequestHandler.getRequestUri(pathOrRequestUri));
requestMap = findRequestMap(pathOrRequestUri);
} else {
@@ -206,18 +213,18 @@ public class CsrfUtil {
return tokenValue;
}
- static ConfigXMLReader.RequestMap findRequestMap(String _urlWithControlPath){
+ static ConfigXMLReader.RequestMap findRequestMap(String urlWithControlPath) {
- String requestUri = getRequestUriFromPath(_urlWithControlPath);
+ String requestUri = getRequestUriFromPath(urlWithControlPath);
List<ComponentConfig.WebappInfo> webappInfos = ComponentConfig.getAllWebappResourceInfos().stream()
- .filter(line -> line.contextRoot.contains(RequestHandler.getRequestUri(_urlWithControlPath)))
+ .filter(line -> line.contextRoot.contains(RequestHandler.getRequestUri(urlWithControlPath)))
.collect(Collectors.toList());
ConfigXMLReader.RequestMap requestMap = null;
if (UtilValidate.isNotEmpty(webappInfos)) {
try {
- if (StringUtils.countMatches(requestUri, "/")==1){
+ if (StringUtils.countMatches(requestUri, "/") == 1) {
requestMap = ConfigXMLReader.getControllerConfig(webappInfos.get(0)).getRequestMapMap()
.get(requestUri.substring(0, requestUri.indexOf("/")));
} else {
@@ -232,10 +239,10 @@ public class CsrfUtil {
}
static ConfigXMLReader.RequestMap findRequestMap(Map<String, ConfigXMLReader.RequestMap> requestMapMap,
- String _urlWithoutControlPath) {
- String path = _urlWithoutControlPath;
- if (_urlWithoutControlPath.startsWith("/")) {
- path = _urlWithoutControlPath.substring(1);
+ String urlWithoutControlPath) {
+ String path = urlWithoutControlPath;
+ if (urlWithoutControlPath.startsWith("/")) {
+ path = urlWithoutControlPath.substring(1);
}
int charPos = path.indexOf("?");
if (charPos != -1) {
@@ -258,7 +265,7 @@ public class CsrfUtil {
/**
* generate csrf token for AJAX and add it as value to token cache
- *
+ *
* @param request
* @return csrf token
*/
@@ -274,7 +281,7 @@ public class CsrfUtil {
/**
* get csrf token for AJAX
- *
+ *
* @param session
* @return csrf token
*/
@@ -283,13 +290,14 @@ public class CsrfUtil {
}
public static String addOrUpdateTokenInUrl(String link, String csrfToken) {
- if (link.contains(CsrfUtil.tokenNameNonAjax)) {
- return link.replaceFirst("\\b"+CsrfUtil.tokenNameNonAjax+"=.*?(&|$)", CsrfUtil.tokenNameNonAjax+"=" + csrfToken + "$1");
+ if (link.contains(CsrfUtil.getTokenNameNonAjax())) {
+ return link.replaceFirst("\\b" + CsrfUtil.getTokenNameNonAjax() + "=.*?(&|$)",
+ CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken + "$1");
} else if (!"".equals(csrfToken)) {
if (link.contains("?")) {
- return link + "&"+CsrfUtil.tokenNameNonAjax+"=" + csrfToken;
+ return link + "&" + CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken;
} else {
- return link + "?"+CsrfUtil.tokenNameNonAjax+"=" + csrfToken;
+ return link + "?" + CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken;
}
}
return link;
@@ -297,25 +305,26 @@ public class CsrfUtil {
public static String addOrUpdateTokenInQueryString(String link, String csrfToken) {
if (UtilValidate.isNotEmpty(link)) {
- if (link.contains(CsrfUtil.tokenNameNonAjax)) {
- return link.replaceFirst("\\b"+CsrfUtil.tokenNameNonAjax+"=.*?(&|$)", CsrfUtil.tokenNameNonAjax+"=" + csrfToken + "$1");
+ if (link.contains(CsrfUtil.getTokenNameNonAjax())) {
+ return link.replaceFirst("\\b" + CsrfUtil.getTokenNameNonAjax() + "=.*?(&|$)",
+ CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken + "$1");
} else {
if (UtilValidate.isNotEmpty(csrfToken)) {
- return link + "&"+CsrfUtil.tokenNameNonAjax+"=" + csrfToken;
+ return link + "&" + CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken;
} else {
return link;
}
}
} else {
- return CsrfUtil.tokenNameNonAjax+"=" + csrfToken;
+ return CsrfUtil.getTokenNameNonAjax() + "=" + csrfToken;
}
}
- public static void checkToken(HttpServletRequest request, String _path)
+ public static void checkToken(HttpServletRequest request, String path)
throws RequestHandlerException, RequestHandlerExceptionAllowExternalRequests {
- String path = _path;
- if (_path.startsWith("/")) {
- path = _path.substring(1);
+ String csrfUtilPath = path;
+ if (path.startsWith("/")) {
+ csrfUtilPath = path.substring(1);
}
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With")) && !"GET".equals(request.getMethod())) {
String csrfToken = request.getHeader("X-CSRF-Token");
@@ -327,15 +336,15 @@ public class CsrfUtil {
}
} else {
Map<String, String> tokenMap = CsrfUtil.getTokenMap(request, request.getContextPath());
- String csrfToken = request.getParameter(CsrfUtil.tokenNameNonAjax);
- String limitPath = getRequestUriWithSubFolderLimit(path);
+ String csrfToken = request.getParameter(CsrfUtil.getTokenNameNonAjax());
+ String limitPath = getRequestUriWithSubFolderLimit(csrfUtilPath);
if (UtilValidate.isNotEmpty(csrfToken) && tokenMap.containsKey(limitPath)
&& csrfToken.equals(tokenMap.get(limitPath))) {
- if (!CsrfUtil.strategy.keepTokenAfterUse(path,request.getMethod())) {
+ if (!CsrfUtil.getStrategy().keepTokenAfterUse(csrfUtilPath, request.getMethod())) {
tokenMap.remove(limitPath);
}
} else {
- CsrfUtil.strategy.invalidTokenResponse(path, request);
+ CsrfUtil.getStrategy().invalidTokenResponse(csrfUtilPath, request);
}
}
}
@@ -355,4 +364,32 @@ public class CsrfUtil {
}
}
}
+
+ /**
+ * @return the tokenNameNonAjax
+ */
+ public static String getTokenNameNonAjax() {
+ return tokenNameNonAjax;
+ }
+
+ /**
+ * @param tokenNameNonAjax the tokenNameNonAjax to set
+ */
+ public static void setTokenNameNonAjax(String tokenNameNonAjax) {
+ CsrfUtil.tokenNameNonAjax = tokenNameNonAjax;
+ }
+
+ /**
+ * @return the strategy
+ */
+ public static ICsrfDefenseStrategy getStrategy() {
+ return strategy;
+ }
+
+ /**
+ * @param strategy the strategy to set
+ */
+ public static void setStrategy(ICsrfDefenseStrategy strategy) {
+ CsrfUtil.strategy = strategy;
+ }
}
diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/ICsrfDefenseStrategy.java b/framework/security/src/main/java/org/apache/ofbiz/security/ICsrfDefenseStrategy.java
index 322afb5..fc2b227 100644
--- a/framework/security/src/main/java/org/apache/ofbiz/security/ICsrfDefenseStrategy.java
+++ b/framework/security/src/main/java/org/apache/ofbiz/security/ICsrfDefenseStrategy.java
@@ -50,6 +50,7 @@ public interface ICsrfDefenseStrategy {
*/
boolean keepTokenAfterUse(String requestUri, String requestMethod);
- void invalidTokenResponse(String requestUri, HttpServletRequest request) throws RequestHandlerExceptionAllowExternalRequests;
+ void invalidTokenResponse(String requestUri, HttpServletRequest request)
+ throws RequestHandlerExceptionAllowExternalRequests;
-}
\ No newline at end of file
+}
diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/NoCsrfDefenseStrategy.java b/framework/security/src/main/java/org/apache/ofbiz/security/NoCsrfDefenseStrategy.java
index 279310c..302ba3b 100644
--- a/framework/security/src/main/java/org/apache/ofbiz/security/NoCsrfDefenseStrategy.java
+++ b/framework/security/src/main/java/org/apache/ofbiz/security/NoCsrfDefenseStrategy.java
@@ -28,7 +28,7 @@ public class NoCsrfDefenseStrategy implements ICsrfDefenseStrategy {
}
@Override
- public int maxSubFolderInRequestUrlForTokenMapLookup(String requestUri){
+ public int maxSubFolderInRequestUrlForTokenMapLookup(String requestUri) {
return 0;
}
@@ -47,4 +47,4 @@ public class NoCsrfDefenseStrategy implements ICsrfDefenseStrategy {
public void invalidTokenResponse(String requestUri, HttpServletRequest request) {
}
-}
\ No newline at end of file
+}
diff --git a/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java b/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java
index 53d0096..7cd9a4c 100644
--- a/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java
+++ b/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java
@@ -71,7 +71,7 @@ public class CsrfUtilTests {
@Test
public void testGetRequestUriWithSubFolderLimit(){
- CsrfUtil.strategy = new CsrfDefenseStrategy();
+ CsrfUtil.setStrategy(new CsrfDefenseStrategy());
// limit only when request uri starts with 'entity'
String limitRequestUri = CsrfUtil.getRequestUriWithSubFolderLimit("entity/find/Budget/0002");
@@ -134,7 +134,7 @@ public class CsrfUtilTests {
token = CsrfUtil.generateTokenForNonAjax(request, "checkLogin");
assertNotEquals("", token);
- CsrfUtil.strategy = new CsrfDefenseStrategy();
+ CsrfUtil.setStrategy(new CsrfDefenseStrategy());
token = CsrfUtil.generateTokenForNonAjax(request, "entity/find/Budget/0001");
assertNotEquals("", token);
@@ -223,7 +223,7 @@ public class CsrfUtilTests {
@Test
public void testAddOrUpdateTokenInUrl(){
- CsrfUtil.tokenNameNonAjax = "csrfToken";
+ CsrfUtil.setTokenNameNonAjax("csrfToken");
// test link without csrfToken
String url = CsrfUtil.addOrUpdateTokenInUrl("https://localhost:8443/catalog/control/login", "abcd");
@@ -244,7 +244,7 @@ public class CsrfUtilTests {
@Test
public void testAddOrUpdateTokenInQueryString(){
- CsrfUtil.tokenNameNonAjax = "csrfToken";
+ CsrfUtil.setTokenNameNonAjax("csrfToken");
String queryString = CsrfUtil.addOrUpdateTokenInQueryString("", "abcd");
assertEquals(queryString, "csrfToken=abcd");
diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ConfigXMLReader.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ConfigXMLReader.java
index 1e7221d..6f53726 100644
--- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ConfigXMLReader.java
+++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ConfigXMLReader.java
@@ -64,22 +64,26 @@ import org.w3c.dom.Element;
public class ConfigXMLReader {
public static final String MODULE = ConfigXMLReader.class.getName();
- public static final Path controllerXmlFileName = Paths.get("WEB-INF", "controller.xml");
- private static final UtilCache<URL, ControllerConfig> controllerCache = UtilCache.createUtilCache("webapp.ControllerConfig");
- private static final UtilCache<String, List<ControllerConfig>> controllerSearchResultsCache = UtilCache.createUtilCache("webapp.ControllerSearchResults");
+ public static final Path CONTROLLERXMLFILENAME = Paths.get("WEB-INF", "controller.xml");
+ private static final UtilCache<URL, ControllerConfig> CONTROLLERCACHE = UtilCache
+ .createUtilCache("webapp.ControllerConfig");
+ private static final UtilCache<String, List<ControllerConfig>> CONTROLLERSEARCHRESULTSCACHE = UtilCache
+ .createUtilCache("webapp.ControllerSearchResults");
public static final RequestResponse emptyNoneRequestResponse = RequestResponse.createEmptyNoneRequestResponse();
- public static Set<String> findControllerFilesWithRequest(String requestUri, String controllerPartialPath) throws GeneralException {
+ public static Set<String> findControllerFilesWithRequest(String requestUri, String controllerPartialPath)
+ throws GeneralException {
Set<String> allControllerRequestSet = new HashSet<>();
if (UtilValidate.isEmpty(requestUri)) {
return allControllerRequestSet;
}
String cacheId = controllerPartialPath != null ? controllerPartialPath : "NOPARTIALPATH";
- List<ControllerConfig> controllerConfigs = controllerSearchResultsCache.get(cacheId);
+ List<ControllerConfig> controllerConfigs = CONTROLLERSEARCHRESULTSCACHE.get(cacheId);
if (controllerConfigs == null) {
try {
// find controller.xml file with webappMountPoint + "/WEB-INF" in the path
- List<File> controllerFiles = FileUtil.findXmlFiles(null, controllerPartialPath, "site-conf", "site-conf.xsd");
+ List<File> controllerFiles = FileUtil.findXmlFiles(null, controllerPartialPath, "site-conf",
+ "site-conf.xsd");
controllerConfigs = new LinkedList<>();
for (File controllerFile : controllerFiles) {
URL controllerUrl = null;
@@ -91,9 +95,10 @@ public class ConfigXMLReader {
ControllerConfig cc = ConfigXMLReader.getControllerConfig(controllerUrl);
controllerConfigs.add(cc);
}
- controllerConfigs = controllerSearchResultsCache.putIfAbsentAndGet(cacheId, controllerConfigs);
+ controllerConfigs = CONTROLLERSEARCHRESULTSCACHE.putIfAbsentAndGet(cacheId, controllerConfigs);
} catch (IOException e) {
- throw new GeneralException("Error finding controller XML files to lookup request references: " + e.toString(), e);
+ throw new GeneralException(
+ "Error finding controller XML files to lookup request references: " + e.toString(), e);
}
}
if (controllerConfigs != null) {
@@ -102,20 +107,23 @@ public class ConfigXMLReader {
if (cc.requestMapMap.get(requestUri) != null) {
String requestUniqueId = cc.url.toExternalForm() + "#" + requestUri;
allControllerRequestSet.add(requestUniqueId);
- // Debug.logInfo("========== In findControllerFilesWithRequest found controller with request here [" + requestUniqueId + "]", MODULE);
+ // Debug.logInfo("========== In findControllerFilesWithRequest found controller with request here ["
+ // + requestUniqueId + "]", MODULE);
}
}
}
return allControllerRequestSet;
}
- public static Set<String> findControllerRequestUniqueForTargetType(String target, String urlMode) throws GeneralException {
+ public static Set<String> findControllerRequestUniqueForTargetType(String target, String urlMode)
+ throws GeneralException {
if (UtilValidate.isEmpty(urlMode)) {
urlMode = "intra-app";
}
int indexOfDollarSignCurlyBrace = target.indexOf("${");
int indexOfQuestionMark = target.indexOf("?");
- if (indexOfDollarSignCurlyBrace >= 0 && (indexOfQuestionMark < 0 || indexOfQuestionMark > indexOfDollarSignCurlyBrace)) {
+ if (indexOfDollarSignCurlyBrace >= 0
+ && (indexOfQuestionMark < 0 || indexOfQuestionMark > indexOfDollarSignCurlyBrace)) {
// we have an expanded string in the requestUri part of the target, not much we can do about that...
return null;
}
@@ -123,16 +131,18 @@ public class ConfigXMLReader {
// look through all controller.xml files and find those with the request-uri referred to by the target
String requestUri = UtilHttp.getRequestUriFromTarget(target);
Set<String> controllerLocAndRequestSet = ConfigXMLReader.findControllerFilesWithRequest(requestUri, null);
- // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, MODULE);
+ // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In
+ // findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, MODULE);
return controllerLocAndRequestSet;
} else if ("inter-app".equals(urlMode)) {
String webappMountPoint = UtilHttp.getWebappMountPointFromTarget(target);
- if (webappMountPoint != null)
- webappMountPoint += "/WEB-INF";
+ if (webappMountPoint != null) webappMountPoint += "/WEB-INF";
String requestUri = UtilHttp.getRequestUriFromTarget(target);
- Set<String> controllerLocAndRequestSet = ConfigXMLReader.findControllerFilesWithRequest(requestUri, webappMountPoint);
- // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, MODULE);
+ Set<String> controllerLocAndRequestSet = ConfigXMLReader.findControllerFilesWithRequest(requestUri,
+ webappMountPoint);
+ // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In
+ // findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, MODULE);
return controllerLocAndRequestSet;
} else {
return new HashSet<>();
@@ -142,29 +152,32 @@ public class ConfigXMLReader {
public static ControllerConfig getControllerConfig(WebappInfo webAppInfo)
throws WebAppConfigurationException, MalformedURLException {
Assert.notNull("webAppInfo", webAppInfo);
- Path filePath = webAppInfo.location().resolve(controllerXmlFileName);
+ Path filePath = webAppInfo.location().resolve(CONTROLLERXMLFILENAME);
return getControllerConfig(filePath.toUri().toURL());
}
public static ControllerConfig getControllerConfig(URL url) throws WebAppConfigurationException {
- ControllerConfig controllerConfig = controllerCache.get(url);
+ ControllerConfig controllerConfig = CONTROLLERCACHE.get(url);
if (controllerConfig == null) {
- controllerConfig = controllerCache.putIfAbsentAndGet(url, new ControllerConfig(url));
+ controllerConfig = CONTROLLERCACHE.putIfAbsentAndGet(url, new ControllerConfig(url));
}
return controllerConfig;
}
public static URL getControllerConfigURL(ServletContext context) {
try {
- return context.getResource("/" + controllerXmlFileName);
+ return context.getResource("/" + CONTROLLERXMLFILENAME);
} catch (MalformedURLException e) {
- Debug.logError(e, "Error Finding XML Config File: " + controllerXmlFileName, MODULE);
+ Debug.logError(e, "Error Finding XML Config File: " + CONTROLLERXMLFILENAME, MODULE);
return null;
}
}
- /** Loads the XML file and returns the root element
- * @throws WebAppConfigurationException */
+ /**
+ * Loads the XML file and returns the root element
+ *
+ * @throws WebAppConfigurationException
+ */
private static Element loadDocument(URL location) throws WebAppConfigurationException {
try {
Document document = UtilXml.readXmlDocument(location, true);
@@ -173,18 +186,19 @@ public class ConfigXMLReader {
rootElement = UtilXml.firstChildElement(rootElement, "site-conf");
}
if (Debug.verboseOn()) {
- Debug.logVerbose("Loaded XML Config - " + location, MODULE);
+ Debug.logVerbose("Loaded XML Config - " + location, MODULE);
}
return rootElement;
} catch (Exception e) {
- Debug.logError("When read " + (location != null? location.toString(): "empty location (!)") + " threw " + e.toString(), MODULE);
+ Debug.logError("When read " + (location != null ? location.toString() : "empty location (!)") + " threw "
+ + e.toString(), MODULE);
throw new WebAppConfigurationException(e);
}
}
public static class ControllerConfig {
- private static final String DEFAULT_REDIRECT_STATUS_CODE =
- UtilProperties.getPropertyValue("requestHandler", "status-code", "302");
+ private static final String DEFAULT_REDIRECT_STATUS_CODE = UtilProperties.getPropertyValue("requestHandler",
+ "status-code", "302");
public URL url;
private String errorpage;
@@ -217,7 +231,8 @@ public class ConfigXMLReader {
if (Debug.infoOn()) {
double totalSeconds = (System.currentTimeMillis() - startTime) / 1000.0;
String locString = this.url.toExternalForm();
- Debug.logInfo("controller loaded: " + totalSeconds + "s, " + this.requestMapMap.size() + " requests, " + this.viewMapMap.size() + " views in " + locString, MODULE);
+ Debug.logInfo("controller loaded: " + totalSeconds + "s, " + this.requestMapMap.size()
+ + " requests, " + this.viewMapMap.size() + " views in " + locString, MODULE);
}
}
}
@@ -324,9 +339,11 @@ public class ConfigXMLReader {
/**
* Computes the name of an XML element.
*
- * @param el the element containing "type" and/or "name" attributes
+ * @param el
+ * the element containing "type" and/or "name" attributes
* @return the derived name.
- * @throws NullPointerException when {@code el} is {@code null}
+ * @throws NullPointerException
+ * when {@code el} is {@code null}
*/
private static String elementToName(Element el) {
String eventName = el.getAttribute("name");
@@ -338,15 +355,18 @@ public class ConfigXMLReader {
/**
* Collects some events defined in an XML tree.
*
- * @param root the root of the XML tree
- * @param childName the name of the element inside {@code root} containing the events
- * @param coll the map associating element derived names to an event objects to populate.
+ * @param root
+ * the root of the XML tree
+ * @param childName
+ * the name of the element inside {@code root} containing the events
+ * @param coll
+ * the map associating element derived names to an event objects to populate.
*/
private static void collectEvents(Element root, String childName, Map<String, Event> coll) {
Element child = UtilXml.firstChildElement(root, childName);
if (child != null) {
UtilXml.childElementList(child, "event").stream()
- .forEachOrdered(ev -> coll.put(elementToName(ev), new Event(ev)));
+ .forEachOrdered(ev -> coll.put(elementToName(ev), new Event(ev)));
}
}
@@ -387,7 +407,8 @@ public class ConfigXMLReader {
ControllerConfig includedController = getControllerConfig(urlLocation);
includes.add(includedController);
} catch (MalformedURLException mue) {
- Debug.logError(mue, "Error processing include at [" + includeLocation + "]:" + mue.toString(), MODULE);
+ Debug.logError(mue, "Error processing include at [" + includeLocation + "]:" + mue.toString(),
+ MODULE);
}
}
}
@@ -423,7 +444,7 @@ public class ConfigXMLReader {
this.invoke = eventElement.getAttribute("invoke");
this.globalTransaction = !"false".equals(eventElement.getAttribute("global-transaction"));
String tt = eventElement.getAttribute("transaction-timeout");
- if(!tt.isEmpty()) {
+ if (!tt.isEmpty()) {
this.transactionTimeout = Integer.valueOf(tt);
}
// Get metrics.
@@ -483,7 +504,8 @@ public class ConfigXMLReader {
this.securityCert = "true".equals(securityElement.getAttribute("cert"));
this.securityExternalView = !"false".equals(securityElement.getAttribute("external-view"));
this.securityDirectRequest = !"false".equals(securityElement.getAttribute("direct-request"));
- this.securityCsrfToken = CsrfUtil.strategy.modifySecurityCsrfToken(this.uri, this.method, securityElement.getAttribute("csrf-token"));
+ this.securityCsrfToken = CsrfUtil.getStrategy().modifySecurityCsrfToken(this.uri, this.method,
+ securityElement.getAttribute("csrf-token"));
}
// Check for event
Element eventElement = UtilXml.firstChildElement(requestMapElement, "event");
@@ -538,11 +560,11 @@ public class ConfigXMLReader {
this.saveHomeView = "true".equals(responseElement.getAttribute("save-home-view"));
for (Element redirectParameterElement : UtilXml.childElementList(responseElement, "redirect-parameter")) {
if (UtilValidate.isNotEmpty(redirectParameterElement.getAttribute("value"))) {
- this.redirectParameterValueMap.put(redirectParameterElement.getAttribute("name"), redirectParameterElement.getAttribute("value"));
+ this.redirectParameterValueMap.put(redirectParameterElement.getAttribute("name"),
+ redirectParameterElement.getAttribute("value"));
} else {
String from = redirectParameterElement.getAttribute("from");
- if (from.isEmpty())
- from = redirectParameterElement.getAttribute("name");
+ if (from.isEmpty()) from = redirectParameterElement.getAttribute("name");
this.redirectParameterMap.put(redirectParameterElement.getAttribute("name"), from);
}
}
diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenAjaxTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenAjaxTransform.java
index b5fdbeb..3b92e92 100644
--- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenAjaxTransform.java
+++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenAjaxTransform.java
@@ -36,7 +36,7 @@ import freemarker.template.TemplateTransformModel;
*/
public class CsrfTokenAjaxTransform implements TemplateTransformModel {
- public final static String MODULE = CsrfTokenAjaxTransform.class.getName();
+ public static final String MODULE = CsrfTokenAjaxTransform.class.getName();
@Override
public Writer getWriter(Writer out, @SuppressWarnings("rawtypes") Map args)
@@ -67,7 +67,6 @@ public class CsrfTokenAjaxTransform implements TemplateTransformModel {
@Override
public void write(char cbuf[], int off, int len) {
-
}
};
diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenPairNonAjaxTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenPairNonAjaxTransform.java
index 02d7a30..12fc1a6 100644
--- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenPairNonAjaxTransform.java
+++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/CsrfTokenPairNonAjaxTransform.java
@@ -36,7 +36,7 @@ import freemarker.template.TemplateTransformModel;
*/
public class CsrfTokenPairNonAjaxTransform implements TemplateTransformModel {
- public final static String MODULE = CsrfTokenPairNonAjaxTransform.class.getName();
+ public static final String MODULE = CsrfTokenPairNonAjaxTransform.class.getName();
@Override
public Writer getWriter(Writer out, @SuppressWarnings("rawtypes") Map args)
@@ -54,7 +54,7 @@ public class CsrfTokenPairNonAjaxTransform implements TemplateTransformModel {
if (req != null) {
HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
String tokenValue = CsrfUtil.generateTokenForNonAjax(request, buf.toString());
- out.write(CsrfUtil.tokenNameNonAjax +"="+tokenValue);
+ out.write(CsrfUtil.getTokenNameNonAjax() + "=" + tokenValue);
}
return;
} catch (Exception e) {
diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetWorker.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetWorker.java
index 08609c7..1bd7088 100644
--- a/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetWorker.java
+++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetWorker.java
@@ -124,9 +124,9 @@ public final class WidgetWorker {
currentString = currentString.substring(currentString.lastIndexOf("\"")+1);
}
if (currentString.indexOf('?') == -1) {
- externalWriter.append("?" + CsrfUtil.tokenNameNonAjax + "=" + tokenValue);
+ externalWriter.append("?" + CsrfUtil.getTokenNameNonAjax() + "=" + tokenValue);
} else {
- externalWriter.append("&" + CsrfUtil.tokenNameNonAjax + "=" + tokenValue);
+ externalWriter.append("&" + CsrfUtil.getTokenNameNonAjax() + "=" + tokenValue);
}
}
}
diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java
index 8561b2e..cbf06a8 100644
--- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java
+++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java
@@ -1428,7 +1428,7 @@ public final class MacroFormRenderer implements FormStringRenderer {
String focusFieldName = modelForm.getFocusFieldName();
// Generate CSRF name & value for form
- String csrfNameValue = CsrfUtil.tokenNameNonAjax + " " +CsrfUtil.generateTokenForNonAjax(request, targ);
+ String csrfNameValue = CsrfUtil.getTokenNameNonAjax() + " " +CsrfUtil.generateTokenForNonAjax(request, targ);
StringWriter sr = new StringWriter();
sr.append("<@renderFormOpen ");