This is an automated email from the ASF dual-hosted git repository.
surajk pushed a commit to branch trunk in repository https://gitbox.apache.org/repos/asf/ofbiz-framework.git The following commit(s) were added to refs/heads/trunk by this push: new f357b99 Improved: Corrected class names, method names, data members of class and variables names in framework component. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. f357b99 is described below commit f357b997c0ba2d1459055088d962a5168eee5c4d Author: Suraj Khurana <[hidden email]> AuthorDate: Wed Aug 26 21:40:40 2020 +0530 Improved: Corrected class names, method names, data members of class and variables names in framework component. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. --- .../apache/ofbiz/base/config/ResourceLoader.java | 15 +- .../java/org/apache/ofbiz/base/util/UtilPlist.java | 40 +-- .../java/org/apache/ofbiz/base/util/UtilURL.java | 14 +- .../ofbiz/base/util/collections/GenericMap.java | 42 ++- .../collections/test/FlexibleMapAccessorTests.java | 17 +- .../ofbiz/base/util/string/JuelConnector.java | 6 +- .../org/apache/ofbiz/base/util/string/UelUtil.java | 22 +- .../string/test/FlexibleStringExpanderTests.java | 74 +++-- .../ofbiz/base/util/template/XslTransform.java | 13 +- .../ofbiz/catalina/container/OFBizRealm.java | 8 +- .../org/apache/ofbiz/common/CdyneServices.java | 16 +- .../org/apache/ofbiz/common/CommonServices.java | 13 +- .../java/org/apache/ofbiz/common/FindServices.java | 30 +- .../ofbiz/common/JsLanguageFilesMapping.java | 40 +-- .../ofbiz/common/authentication/AuthHelper.java | 4 +- .../apache/ofbiz/common/test/PerformFindTests.java | 20 +- .../org/apache/ofbiz/entity/DelegatorFactory.java | 11 +- .../entity/condition/EntityConditionValue.java | 16 +- .../ofbiz/entity/config/model/EntityConfig.java | 12 +- .../entity/connection/DBCPConnectionFactory.java | 21 +- .../apache/ofbiz/entity/datasource/GenericDAO.java | 190 +++++++++++- .../entity/datasource/GenericHelperFactory.java | 11 +- .../ofbiz/entity/jdbc/ConnectionFactoryLoader.java | 7 +- .../apache/ofbiz/entity/jdbc/JdbcValueHandler.java | 13 +- .../org/apache/ofbiz/entity/jdbc/SQLProcessor.java | 322 +++++++++++---------- .../ofbiz/entity/model/ModelEntityChecker.java | 92 +++--- .../ofbiz/entity/model/ModelFieldTypeReader.java | 14 +- .../org/apache/ofbiz/entity/model/ModelUtil.java | 10 +- .../apache/ofbiz/entity/model/ModelViewEntity.java | 51 ++-- .../apache/ofbiz/entity/test/EntityTestSuite.java | 144 ++++++--- .../ofbiz/entity/transaction/DebugXaResource.java | 11 +- .../entity/transaction/JNDITransactionFactory.java | 14 +- .../transaction/TransactionFactoryLoader.java | 6 +- .../ofbiz/entity/transaction/TransactionUtil.java | 10 +- .../org/apache/ofbiz/entity/util/EntityCrypto.java | 8 +- .../apache/ofbiz/minilang/SimpleMapProcessor.java | 29 +- .../org/apache/ofbiz/minilang/SimpleMethod.java | 31 +- .../method/conditional/ConditionalFactory.java | 6 +- .../conditional/ValidateMethodCondition.java | 4 +- .../apache/ofbiz/minilang/test/MiniLangTests.java | 21 +- .../org/apache/ofbiz/security/SecurityFactory.java | 24 +- .../org/apache/ofbiz/security/SecurityUtil.java | 8 +- .../org/apache/ofbiz/service/DispatchContext.java | 30 +- .../org/apache/ofbiz/service/LocalDispatcher.java | 77 +++-- .../org/apache/ofbiz/service/ServiceContainer.java | 14 +- .../apache/ofbiz/service/ServiceDispatcher.java | 2 +- .../java/org/apache/ofbiz/service/ServiceUtil.java | 34 ++- .../ofbiz/service/config/ServiceConfigUtil.java | 23 +- .../ofbiz/service/engine/EntityAutoEngine.java | 4 +- .../ofbiz/service/jms/JmsListenerFactory.java | 48 +-- .../org/apache/ofbiz/service/job/JobManager.java | 206 ++++++------- .../ofbiz/service/job/PersistedServiceJob.java | 12 +- .../apache/ofbiz/service/mail/ServiceMcaUtil.java | 10 +- .../ofbiz/service/semaphore/ServiceSemaphore.java | 2 +- .../ofbiz/service/test/ServiceEngineTests.java | 6 +- .../ofbiz/service/test/ServiceEntityAutoTests.java | 30 ++ .../ofbiz/service/test/ServicePermissionTests.java | 46 ++- .../ofbiz/service/test/ServiceSOAPTests.java | 12 +- .../ofbiz/service/testtools/OFBizTestCase.java | 57 +++- .../org/apache/ofbiz/testtools/ServiceTest.java | 4 +- .../apache/ofbiz/testtools/SimpleMethodTest.java | 4 +- .../apache/ofbiz/testtools/TestRunContainer.java | 10 +- .../webapp/control/ExternalLoginKeysManager.java | 12 +- .../apache/ofbiz/webapp/control/LoginWorker.java | 84 ++++-- .../ofbiz/webapp/control/SameSiteFilter.java | 7 +- .../webapp/event/RequestBodyMapHandlerFactory.java | 6 +- .../ofbiz/webapp/event/RomeEventHandler.java | 12 +- .../ofbiz/webapp/event/ScriptEventHandler.java | 7 +- .../ofbiz/webapp/ftl/FreeMarkerViewHandler.java | 9 +- .../ftl/JsLanguageFilesMappingTransform.java | 10 +- .../apache/ofbiz/webapp/stats/ServerHitBin.java | 12 +- .../apache/ofbiz/webapp/stats/VisitHandler.java | 37 ++- .../org/apache/ofbiz/widget/WidgetFactory.java | 9 +- .../org/apache/ofbiz/widget/model/FormFactory.java | 24 +- .../org/apache/ofbiz/widget/model/GridFactory.java | 21 +- .../org/apache/ofbiz/widget/model/HtmlWidget.java | 39 ++- .../org/apache/ofbiz/widget/model/MenuFactory.java | 31 +- .../org/apache/ofbiz/widget/model/ModelForm.java | 26 +- .../ofbiz/widget/model/ModelFormFieldBuilder.java | 35 ++- .../org/apache/ofbiz/widget/model/ModelWidget.java | 6 +- .../apache/ofbiz/widget/model/ScreenFactory.java | 42 ++- .../apache/ofbiz/widget/model/ThemeFactory.java | 31 +- .../org/apache/ofbiz/widget/model/TreeFactory.java | 10 +- .../ofbiz/widget/renderer/ScreenRenderer.java | 40 ++- .../ofbiz/widget/renderer/fo/FoFormRenderer.java | 39 ++- .../widget/renderer/html/HtmlMenuRenderer.java | 30 +- .../widget/renderer/html/HtmlTreeRenderer.java | 6 +- .../widget/renderer/html/HtmlWidgetRenderer.java | 26 +- 88 files changed, 1714 insertions(+), 988 deletions(-) diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceLoader.java b/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceLoader.java index 455ebfe..07c6397 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceLoader.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceLoader.java @@ -34,9 +34,9 @@ import org.w3c.dom.Element; public abstract class ResourceLoader { private static final String MODULE = ResourceLoader.class.getName(); - private static final UtilCache<String, ResourceLoader> loaderCache = UtilCache.createUtilCache("resource.ResourceLoaders", 0, 0); + private static final UtilCache<String, ResourceLoader> LOADER_CACHE = UtilCache.createUtilCache("resource.ResourceLoaders", 0, 0); // This cache is temporary - we will use it until the framework has been refactored to eliminate DOM tree caching, then it can be removed. - private static final UtilCache<String, Document> domCache = UtilCache.createUtilCache("resource.DomTrees", 0, 0); + private static final UtilCache<String, Document> DOM_CACHE = UtilCache.createUtilCache("resource.DomTrees", 0, 0); public static InputStream loadResource(String xmlFilename, String location, String loaderName) throws GenericConfigException { ResourceLoader loader = getLoader(xmlFilename, loaderName); @@ -56,7 +56,7 @@ public abstract class ResourceLoader { public static ResourceLoader getLoader(String xmlFilename, String loaderName) throws GenericConfigException { String cacheKey = xmlFilename.concat("#").concat(loaderName); - ResourceLoader loader = loaderCache.get(cacheKey); + ResourceLoader loader = LOADER_CACHE.get(cacheKey); if (loader == null) { loader = getLoader(xmlFilename, loaderName, cacheKey); } @@ -81,9 +81,10 @@ public abstract class ResourceLoader { throw new GenericConfigException("The " + xmlFilename + " file is missing the <resource-loader> element with the name " + loaderName); } if (loaderElement.getAttribute("class").isEmpty()) { - throw new GenericConfigException("The " + xmlFilename + " file <resource-loader> element with the name " + loaderName + " is missing the class attribute"); + throw new GenericConfigException("The " + xmlFilename + " file <resource-loader> element with the name " + loaderName + + " is missing the class attribute"); } - loader = loaderCache.putIfAbsentAndGet(cacheKey, makeLoader(loaderElement)); + loader = LOADER_CACHE.putIfAbsentAndGet(cacheKey, makeLoader(loaderElement)); return loader; } @@ -120,13 +121,13 @@ public abstract class ResourceLoader { */ @Deprecated public static Document getXmlDocument(String xmlFilename) throws GenericConfigException { - Document document = domCache.get(xmlFilename); + Document document = DOM_CACHE.get(xmlFilename); if (document == null) { document = readXmlDocument(xmlFilename); if (document != null) { - document = domCache.putIfAbsentAndGet(xmlFilename, document); + document = DOM_CACHE.putIfAbsentAndGet(xmlFilename, document); } } return document; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java index 9a59bef..0e2cfc8 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java @@ -40,11 +40,11 @@ public final class UtilPlist { private UtilPlist() { } /** simple 4 char indentation */ - private static final String indentFourString = " "; + private static final String INDENT_FOUR_STRING = " "; public static void writePlistProperty(String name, Object value, int indentLevel, PrintWriter writer) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.print(name); writer.print(" = "); @@ -62,14 +62,14 @@ public final class UtilPlist { } public static void writePlistPropertyMap(Map<String, Object> propertyMap, int indentLevel, PrintWriter writer, boolean appendComma) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println("{"); for (Map.Entry<String, Object> property: propertyMap.entrySet()) { writePlistProperty(property.getKey(), property.getValue(), indentLevel + 1, writer); } for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } if (appendComma) { writer.println("},"); @@ -79,7 +79,7 @@ public final class UtilPlist { } public static void writePlistPropertyValueList(List<Object> propertyValueList, int indentLevel, PrintWriter writer) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.print("("); @@ -98,14 +98,14 @@ public final class UtilPlist { } for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println(");"); } public static void writePlistPropertyXml(String name, Object value, int indentLevel, PrintWriter writer) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.print("<key>"); writer.print(name); @@ -118,7 +118,7 @@ public final class UtilPlist { writePlistPropertyValueListXml(list, indentLevel, writer); } else { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.print("<string>"); writer.print(value); @@ -127,20 +127,20 @@ public final class UtilPlist { } public static void writePlistPropertyMapXml(Map<String, Object> propertyMap, int indentLevel, PrintWriter writer) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println("<dict>"); for (Map.Entry<String, Object> property: propertyMap.entrySet()) { writePlistPropertyXml(property.getKey(), property.getValue(), indentLevel + 1, writer); } for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println("</dict>"); } public static void writePlistPropertyValueListXml(List<Object> propertyValueList, int indentLevel, PrintWriter writer) { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println("<array>"); @@ -153,7 +153,7 @@ public final class UtilPlist { writePlistPropertyMapXml(propertyMap, indentLevel, writer); } else { for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.print("<string>"); writer.print(propertyValue); @@ -163,25 +163,29 @@ public final class UtilPlist { indentLevel--; for (int i = 0; i < indentLevel; i++) { - writer.print(indentFourString); + writer.print(INDENT_FOUR_STRING); } writer.println("</array>"); } /** * Writes model information in the Apple EOModelBundle format. - * For document structure and definition see: http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html + * For document structure and definition see: + * http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html * @param eoModelMap * @param eomodeldFullPath * @param filename * @throws FileNotFoundException * @throws UnsupportedEncodingException */ - public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) throws FileNotFoundException, UnsupportedEncodingException { - try (PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(eomodeldFullPath, filename)), "UTF-8")))) { + public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) + throws FileNotFoundException, UnsupportedEncodingException { + try (PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( + new File(eomodeldFullPath, filename)), "UTF-8")))) { if (useXml) { plistWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - plistWriter.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); + plistWriter.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/" + + "PropertyList-1.0.dtd\">"); plistWriter.println("<plist version=\"1.0\">"); writePlistPropertyMapXml(eoModelMap, 0, plistWriter); plistWriter.println("</plist>"); @@ -190,4 +194,4 @@ public final class UtilPlist { } } } -} \ No newline at end of file +} diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java index 907344d..4d45255 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java @@ -31,7 +31,7 @@ import java.util.concurrent.ConcurrentHashMap; public final class UtilURL { private static final String MODULE = UtilURL.class.getName(); - private static final Map<String, URL> urlMap = new ConcurrentHashMap<>(); + private static final Map<String, URL> URL_MAP = new ConcurrentHashMap<>(); private UtilURL() { } @@ -78,7 +78,7 @@ public final class UtilURL { * @return */ public static URL fromResource(String resourceName, ClassLoader loader) { - URL url = urlMap.get(resourceName); + URL url = URL_MAP.get(resourceName); if (url != null) { try { return new URL(url.toString()); @@ -96,27 +96,27 @@ public final class UtilURL { } url = loader.getResource(resourceName); if (url != null) { - urlMap.put(resourceName, url); + URL_MAP.put(resourceName, url); return url; } url = ClassLoader.getSystemResource(resourceName); if (url != null) { - urlMap.put(resourceName, url); + URL_MAP.put(resourceName, url); return url; } url = fromFilename(resourceName); if (url != null) { - urlMap.put(resourceName, url); + URL_MAP.put(resourceName, url); return url; } url = fromOfbizHomePath(resourceName); if (url != null) { - urlMap.put(resourceName, url); + URL_MAP.put(resourceName, url); return url; } url = fromUrlString(resourceName); if (url != null) { - urlMap.put(resourceName, url); + URL_MAP.put(resourceName, url); } return url; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMap.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMap.java index 3b3d276..48b2a4e 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMap.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMap.java @@ -33,22 +33,33 @@ import org.apache.ofbiz.base.util.UtilGenerics; @SuppressWarnings("serial") public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K, V>, Serializable { - private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Set<?>> keySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "keySet")); - private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Set<?>> entrySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "entrySet")); - private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Collection<?>> valuesUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Collection.class, "values")); - private static final AtomicIntegerFieldUpdater<GenericMap<?, ?>> modCountUpdater = UtilGenerics.cast(AtomicIntegerFieldUpdater.newUpdater(GenericMap.class, "modCount")); + private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Set<?>> KEY_SET_UPDATER = + UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "keySet")); + private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Set<?>> ENTRY_SET_UPDATER = + UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "entrySet")); + private static final AtomicReferenceFieldUpdater<GenericMap<?, ?>, Collection<?>> VALUES_UPDATER = + UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Collection.class, "values")); + private static final AtomicIntegerFieldUpdater<GenericMap<?, ?>> MOD_COUNT_UPDATER = + UtilGenerics.cast(AtomicIntegerFieldUpdater.newUpdater(GenericMap.class, "modCount")); private volatile Set<K> keySet; private volatile Set<Map.Entry<K, V>> entrySet; private volatile Collection<V> values; private volatile int modCount; + /** + * Gets mod count. + * @return the mod count + */ public int getModCount() { return modCount; } + /** + * Increment mod count. + */ protected void incrementModCount() { - modCountUpdater.getAndIncrement(this); + MOD_COUNT_UPDATER.getAndIncrement(this); } @Override @@ -90,6 +101,11 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K return equalsMap(map); } + /** + * Equals generic map boolean. + * @param map the map + * @return the boolean + */ protected boolean equalsGenericMap(GenericMap<?, ?> map) { Iterator<Map.Entry<K, V>> it = iterator(false); while (it.hasNext()) { @@ -113,6 +129,11 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K return true; } + /** + * Equals map boolean. + * @param map the map + * @return the boolean + */ protected boolean equalsMap(Map<?, ?> map) { Iterator<Map.Entry<K, V>> it = iterator(false); while (it.hasNext()) { @@ -150,6 +171,11 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K super(iterator(noteAccess)); } + /** + * Is valid boolean. + * @param src the src + * @return the boolean + */ protected boolean isValid(Map.Entry<K, V> src) { if (currentModCount != getModCount()) { throw new ConcurrentModificationException(); @@ -161,7 +187,7 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K @Override public final Set<Map.Entry<K, V>> entrySet() { if (entrySet == null) { - entrySetUpdater.compareAndSet(this, null, new GenericMapEntrySet<K, V, GenericMap<K, V>>(this) { + ENTRY_SET_UPDATER.compareAndSet(this, null, new GenericMapEntrySet<K, V, GenericMap<K, V>>(this) { @Override protected boolean contains(Object key, Object value) { return Objects.equals(get(key, false), value); @@ -191,7 +217,7 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K @Override public final Set<K> keySet() { if (keySet == null) { - keySetUpdater.compareAndSet(this, null, new GenericMapKeySet<K, V, GenericMap<K, V>>(this) { + KEY_SET_UPDATER.compareAndSet(this, null, new GenericMapKeySet<K, V, GenericMap<K, V>>(this) { @Override public boolean contains(Object key) { return containsKey(key); @@ -219,7 +245,7 @@ public abstract class GenericMap<K, V> implements Appender<StringBuilder>, Map<K @Override public final Collection<V> values() { if (values == null) { - valuesUpdater.compareAndSet(this, null, new GenericMapValues<K, V, GenericMap<K, V>>(this) { + VALUES_UPDATER.compareAndSet(this, null, new GenericMapValues<K, V, GenericMap<K, V>>(this) { @Override public Iterator<V> iterator(boolean noteAccess) { return new GenericMapIterator<V>(noteAccess) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java index 11e7d17..53f78eb 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java @@ -33,7 +33,7 @@ import org.apache.ofbiz.base.util.string.FlexibleStringExpander; @SourceMonitored public class FlexibleMapAccessorTests extends GenericTestCaseBase { - private static final Locale localeToTest = new Locale("en", "US"); + private static final Locale LOCALE_TO_TEST = new Locale("en", "US"); private static FlexibleMapAccessor<?> fmaEmpty = FlexibleMapAccessor.getInstance(""); private static FlexibleMapAccessor<?> fmaNull = FlexibleMapAccessor.getInstance(null); @@ -138,16 +138,26 @@ public class FlexibleMapAccessorTests extends GenericTestCaseBase { fmaTest("UEL auto-vivify Map", "parameters.var", "Hello ${parameters.var}!", "World", "Hello World!"); fmaTest("UEL auto-vivify List", "parameters.someList[0]", "parameters.someList[+0]", "Hello ${parameters.someList[0]}!", null, "World", "Hello World!"); fmaTest("fse", "para${'meter'}s.var", "Hello ${parameters.var}!", "World", "Hello World!"); - fmaTest("foo", "'The total is ${total?currency(USD)}.'", "total", "The total is ${total?currency(USD)}.", localeToTest, new BigDecimal("12345678.90"), "The total is $12,345,678.90."); + fmaTest("foo", "'The total is ${total?currency(USD)}.'", "total", "The total is ${total?currency(USD)}.", LOCALE_TO_TEST, new BigDecimal("12345678.90"), "The total is $12,345,678.90."); assertTrue("containsNestedExpression method returns true", FlexibleMapAccessor.getInstance("Hello ${parameters.var}!").containsNestedExpression()); assertFalse("containsNestedExpression method returns false", FlexibleMapAccessor.getInstance("Hello World!").containsNestedExpression()); } public static class ThrowException { + /** + * Gets value. + * @return the value + * @throws Exception the exception + */ public Object getValue() throws Exception { throw new Exception(); } + /** + * Sets value. + * @param value the value + * @throws Exception the exception + */ public void setValue(Object value) throws Exception { throw new Exception(); } @@ -169,6 +179,9 @@ public class FlexibleMapAccessorTests extends GenericTestCaseBase { } } + /** + * Test verbosity and errors. + */ public void testVerbosityAndErrors() { boolean isVerbose = Debug.isOn(Debug.VERBOSE); try { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/JuelConnector.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/JuelConnector.java index 521cc0a..eeb70e7 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/JuelConnector.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/JuelConnector.java @@ -147,8 +147,8 @@ public class JuelConnector { @Override protected AstEval eval(boolean required, boolean deferred) throws ScanException, ParseException { AstEval v = null; - Symbol start_eval = deferred ? START_EVAL_DEFERRED : START_EVAL_DYNAMIC; - if (this.getToken().getSymbol() == start_eval) { + Symbol startEval = deferred ? START_EVAL_DEFERRED : START_EVAL_DYNAMIC; + if (this.getToken().getSymbol() == startEval) { consumeToken(); AstNode node = expr(true); try { @@ -166,7 +166,7 @@ public class JuelConnector { } v = new AstEval(node, deferred); } else if (required) { - fail(start_eval); + fail(startEval); } return v; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelUtil.java index 13e7955..428b648 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelUtil.java @@ -49,9 +49,9 @@ import org.apache.ofbiz.base.util.collections.LocalizedMap; /** Implements the Unified Expression Language (JSR-245). */ public final class UelUtil { private static final String MODULE = UelUtil.class.getName(); - private static final String localizedMapLocaleKey = LocalizedMap.class.getName() + "_locale".replace(".", "_"); - private static final ExpressionFactory exprFactory = JuelConnector.newExpressionFactory(); - private static final ELResolver defaultResolver = new ExtendedCompositeResolver() { + private static final String LOCALIZED_MAP_LOCALE_KEY = LocalizedMap.class.getName() + "_locale".replace(".", "_"); + private static final ExpressionFactory EXPR_FACTORY = JuelConnector.newExpressionFactory(); + private static final ELResolver DEFAULT_RESOLVER = new ExtendedCompositeResolver() { { add(new ExtendedMapResolver(false)); add(new ExtendedListResolver(false)); @@ -65,7 +65,7 @@ public final class UelUtil { private UelUtil() { } public static String getLocalizedMapLocaleKey() { - return localizedMapLocaleKey; + return LOCALIZED_MAP_LOCALE_KEY; } /** Evaluates a Unified Expression Language expression and returns the result. @@ -85,7 +85,7 @@ public final class UelUtil { */ public static Object evaluate(Map<String, ? extends Object> context, String expression, Class<?> expectedType) { ELContext elContext = new ReadOnlyContext(context); - ValueExpression ve = exprFactory.createValueExpression(elContext, expression, expectedType); + ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, expectedType); return ve.getValue(elContext); } @@ -100,7 +100,7 @@ public final class UelUtil { Debug.logVerbose("UelUtil.setValue invoked, expression = " + expression + ", value = " + value, MODULE); } ELContext elContext = new BasicContext(context); - ValueExpression ve = exprFactory.createValueExpression(elContext, expression, expectedType); + ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, expectedType); ve.setValue(elContext, value); } @@ -114,7 +114,7 @@ public final class UelUtil { Debug.logVerbose("UelUtil.removeValue invoked, expression = " + expression, MODULE); } ELContext elContext = new BasicContext(context); - ValueExpression ve = exprFactory.createValueExpression(elContext, expression, Object.class); + ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, Object.class); ve.setValue(elContext, null); } @@ -127,7 +127,7 @@ public final class UelUtil { } @Override public ELResolver getELResolver() { - return defaultResolver; + return DEFAULT_RESOLVER; } @Override public FunctionMapper getFunctionMapper() { @@ -148,7 +148,7 @@ public final class UelUtil { } @Override public ELResolver getELResolver() { - return defaultResolver; + return DEFAULT_RESOLVER; } @Override public FunctionMapper getFunctionMapper() { @@ -417,7 +417,7 @@ public final class UelUtil { Locale locale = null; try { VariableMapper vm = context.getVariableMapper(); - ValueExpression ve = vm.resolveVariable(localizedMapLocaleKey); + ValueExpression ve = vm.resolveVariable(LOCALIZED_MAP_LOCALE_KEY); if (ve != null) { locale = (Locale) ve.getValue(context); } @@ -520,7 +520,7 @@ public final class UelUtil { } if (variables instanceof LocalizedMap<?>) { if (locale == null) { - locale = (Locale) variables.get(localizedMapLocaleKey); + locale = (Locale) variables.get(LOCALIZED_MAP_LOCALE_KEY); if (locale == null) { locale = (Locale) variables.get("locale"); if (locale == null) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java index 7005dc0..a7573fd 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java @@ -37,10 +37,10 @@ import junit.framework.TestCase; @SourceMonitored public class FlexibleStringExpanderTests extends TestCase { - private static final Locale localeToTest = new Locale("en", "US"); - private static final Locale badLocale = new Locale("fr"); - private static final TimeZone timeZoneToTest = TimeZone.getTimeZone("PST"); - private static final TimeZone badTimeZone = TimeZone.getTimeZone("GMT"); + private static final Locale LOCALE_TO_TEST = new Locale("en", "US"); + private static final Locale BAD_LOCALE = new Locale("fr"); + private static final TimeZone TIME_ZONE_TO_TEST = TimeZone.getTimeZone("PST"); + private static final TimeZone BAD_TIME_ZONE = TimeZone.getTimeZone("GMT"); private boolean wasVerbose; @@ -58,9 +58,14 @@ public class FlexibleStringExpanderTests extends TestCase { } } + /** + * Test parsing. + */ public void testParsing() { parserTest("visible nested replacement", "${'Hello ${var}'}!", true, "${'Hello ${var}'}!"); - parserTest("hidden (runtime) nested null callreplacement", "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".staticReturnNull()}}World!", true, "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".staticReturnNull()}}World!"); + parserTest("hidden (runtime) nested null callreplacement", "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + + ".staticReturnNull()}}World!", true, "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + + ".staticReturnNull()}}World!"); parserTest("UEL integration(nested): throw Exception", "${${throwException.value}}", true, "${${throwException.value}}"); parserTest("nested-constant-emptynest-emptynest", "${a${}${}", true, "${a${}${}"); parserTest("null", null, true, ""); @@ -102,7 +107,8 @@ public class FlexibleStringExpanderTests extends TestCase { fseTest(label, input, context, null, null, compare, isEmpty); } - private static void doFseTest(String label, String input, FlexibleStringExpander fse, Map<String, Object> context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { + private static void doFseTest(String label, String input, FlexibleStringExpander fse, Map<String, Object> context, TimeZone timeZone, + Locale locale, String compare, Object expand, boolean isEmpty) { assertEquals("isEmpty:" + label, isEmpty, fse.isEmpty()); if (input == null) { assertEquals("getOriginal():" + label, "", fse.getOriginal()); @@ -140,8 +146,8 @@ public class FlexibleStringExpanderTests extends TestCase { TimeZone.setDefault(timeZone); assertEquals(label, compare, fse.expandString(context, null, null)); assertEquals(label, expand, fse.expand(context, null, null)); - Locale.setDefault(badLocale); - TimeZone.setDefault(badTimeZone); + Locale.setDefault(BAD_LOCALE); + TimeZone.setDefault(BAD_TIME_ZONE); assertNotSame(label, compare, fse.expandString(context, null, null)); if (input != null) { assertNotSame(label, expand, fse.expand(context, null, null)); @@ -152,8 +158,8 @@ public class FlexibleStringExpanderTests extends TestCase { context.put("autoUserLogin", autoUserLogin); assertEquals(label, compare, fse.expandString(context, null, null)); assertEquals(label, expand, fse.expand(context, null, null)); - autoUserLogin.put("lastLocale", badLocale.toString()); - autoUserLogin.put("lastTimeZone", badTimeZone.getID()); + autoUserLogin.put("lastLocale", BAD_LOCALE.toString()); + autoUserLogin.put("lastTimeZone", BAD_TIME_ZONE.getID()); assertNotSame(label, compare, fse.expandString(context, null, null)); if (input != null) { assertNotSame(label, expand, fse.expand(context, null, null)); @@ -163,8 +169,8 @@ public class FlexibleStringExpanderTests extends TestCase { context.put("timeZone", timeZone); assertEquals(label, compare, fse.expandString(context, null, null)); assertEquals(label, expand, fse.expand(context, null, null)); - context.put("locale", badLocale); - context.put("timeZone", badTimeZone); + context.put("locale", BAD_LOCALE); + context.put("timeZone", BAD_TIME_ZONE); assertNotSame(label, compare, fse.expandString(context, null, null)); if (input != null) { assertNotSame(label, expand, fse.expand(context, null, null)); @@ -173,9 +179,9 @@ public class FlexibleStringExpanderTests extends TestCase { context.remove("timeZone"); assertEquals(label, compare, fse.expandString(context, timeZone, locale)); assertEquals(label, expand, fse.expand(context, timeZone, locale)); - assertNotSame(label, compare, fse.expandString(context, badTimeZone, badLocale)); + assertNotSame(label, compare, fse.expandString(context, BAD_TIME_ZONE, BAD_LOCALE)); if (input != null) { - assertNotSame(label, expand, fse.expand(context, badTimeZone, badLocale)); + assertNotSame(label, expand, fse.expand(context, BAD_TIME_ZONE, BAD_LOCALE)); } } finally { Locale.setDefault(defaultLocale); @@ -184,11 +190,13 @@ public class FlexibleStringExpanderTests extends TestCase { } } - private static void fseTest(String label, String input, Map<String, Object> context, TimeZone timeZone, Locale locale, String compare, boolean isEmpty) { + private static void fseTest(String label, String input, Map<String, Object> context, TimeZone timeZone, Locale locale, + String compare, boolean isEmpty) { fseTest(label, input, context, timeZone, locale, compare, compare, isEmpty); } - private static void fseTest(String label, String input, Map<String, Object> context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { + private static void fseTest(String label, String input, Map<String, Object> context, TimeZone timeZone, Locale locale, String compare, + Object expand, boolean isEmpty) { FlexibleStringExpander fse = FlexibleStringExpander.getInstance(input); doFseTest(label, input, fse, context, timeZone, locale, compare, expand, isEmpty); assertEquals("static expandString:" + label, compare, FlexibleStringExpander.expandString(input, context, timeZone, locale)); @@ -225,12 +233,21 @@ public class FlexibleStringExpanderTests extends TestCase { @SuppressWarnings("serial") public static class ThrowException extends Exception { + /** + * Gets value. + * @return the value + * @throws Exception the exception + */ public Object getValue() throws Exception { throw new Exception(); } } public static class ThrowNPE { + /** + * Gets value. + * @return the value + */ public Object getValue() { throw new NullPointerException(); } @@ -259,10 +276,16 @@ public class FlexibleStringExpanderTests extends TestCase { } } + /** + * Test with verbosity. + */ public void testWithVerbosity() { everythingTest(); } + /** + * Test quietly. + */ public void testQuietly() { everythingTest(); } @@ -290,7 +313,7 @@ public class FlexibleStringExpanderTests extends TestCase { fseTest("null context", "Hello World!", null, null, null, "Hello World!", null, false); fseTest("plain string", "Hello World!", testMap, null, null, "Hello World!", "Hello World!", false); fseTest("simple replacement", "Hello ${var}!", testMap, "Hello World!", false); - fseTest("null FlexibleStringExpander with timeZone/locale", null, testMap, timeZoneToTest, localeToTest, "", null, true); + fseTest("null FlexibleStringExpander with timeZone/locale", null, testMap, TIME_ZONE_TO_TEST, LOCALE_TO_TEST, "", null, true); fseTest("empty FlexibleStringExpander", "", testMap, null, null, "", null, true); fseTest("UEL integration(nested): throw Exception", "${${throwException.value}}", testMap, "", false); fseTest("UEL integration: throw Exception", "${throwException.value}", testMap, null, null, "", null, false); @@ -301,15 +324,17 @@ public class FlexibleStringExpanderTests extends TestCase { fseTest("UEL integration(nested): null", "${${nu${nullVar}ll}}", testMap, "", false); fseTest("UEL integration(nested): NPE", "${${nullVar.noProp}}", testMap, "", false); fseTest("UEL integration(nested): missing", "${${noL${nullVar}ist[0]}}", testMap, "", false); - fseTest("date w/ timezone", "The date is ${date}.", testMap, timeZoneToTest, localeToTest, "The date is 1970-01-14 22:56:07.890.", "The date is 1970-01-14 22:56:07.890.", false); + fseTest("date w/ timezone", "The date is ${date}.", testMap, TIME_ZONE_TO_TEST, LOCALE_TO_TEST, "The date is 1970-01-14 22:56:07.890.", + "The date is 1970-01-14 22:56:07.890.", false); fseTest("just bad", "${foobar", testMap, "${foobar", false); fseTest("constant and bad", "Hello${foobar", testMap, "Hello${foobar", false); fseTest("good and bad", "Hello ${var}${foobar", testMap, "Hello World${foobar", false); - fseTest("plain-currency(USD)", "${amount?currency(${usd})}", testMap, null, localeToTest, "$1,234,567.89", false); - fseTest("currency(USD)", "The total is ${amount?currency(${usd})}.", testMap, null, localeToTest, "The total is $1,234,567.89.", false); - fseTest("currency(USD): null", "The total is ${testMap.missing?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); - fseTest("currency(USD): missing", "The total is ${noList[0]?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); - fseTest("currency(USD): exception", "The total is ${throwException.value?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); + fseTest("plain-currency(USD)", "${amount?currency(${usd})}", testMap, null, LOCALE_TO_TEST, "$1,234,567.89", false); + fseTest("currency(USD)", "The total is ${amount?currency(${usd})}.", testMap, null, LOCALE_TO_TEST, "The total is $1,234,567.89.", false); + fseTest("currency(USD): null", "The total is ${testMap.missing?currency(${usd})}.", testMap, null, LOCALE_TO_TEST, "The total is .", false); + fseTest("currency(USD): missing", "The total is ${noList[0]?currency(${usd})}.", testMap, null, LOCALE_TO_TEST, "The total is .", false); + fseTest("currency(USD): exception", "The total is ${throwException.value?currency(${usd})}.", testMap, null, LOCALE_TO_TEST, + "The total is .", false); fseTest("null nested", "${${nullVar}}!", testMap, "!", false); fseTest("groovy: script", "${groovy:return \"Hello \" + var + \"!\";}", testMap, "Hello World!", false); fseTest("groovy: null", "${groovy:return null;}!", testMap, "!", false); @@ -321,7 +346,8 @@ public class FlexibleStringExpanderTests extends TestCase { fseTest("UEL integration: List", "Hello ${testList[0]}!", testMap, "Hello World!", false); fseTest("UEL integration: null", "${null}", testMap, null, null, "", null, false); fseTest("UEL integration: null dereference", "${nullVar.noProp}", testMap, null, null, "", null, false); - fseTest("UEL integration: throw NPE", "${" + FlexibleStringExpanderTests.class.getName() + ".ThrowNPE.noProp}", testMap, null, null, "", null, false); + fseTest("UEL integration: throw NPE", "${" + FlexibleStringExpanderTests.class.getName() + ".ThrowNPE.noProp}", testMap, null, null, "", + null, false); fseTest("UEL integration: missing", "${noList[0]}", testMap, null, null, "", null, false); fseTest("Escaped expression", "This is an \\${escaped} expression", testMap, "This is an ${escaped} expression", false); fseTest("Escaped(groovy) expression", "This is an \\${groovy:escaped} expression", testMap, "This is an ${groovy:escaped} expression", false); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/template/XslTransform.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/template/XslTransform.java index 8fb83c8..17b1f89 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/template/XslTransform.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/template/XslTransform.java @@ -54,20 +54,19 @@ import org.xml.sax.XMLReader; public final class XslTransform { private static final String MODULE = XslTransform.class.getName(); - private static final UtilCache<String, Templates> xslTemplatesCache = UtilCache.createUtilCache("XsltTemplates", 0, 0); + private static final UtilCache<String, Templates> XSL_TEMPLATE_CACHE = UtilCache.createUtilCache("XsltTemplates", 0, 0); /** * @param template the content or url of the xsl template * @param data the content or url of the xml data file * @throws TransformerException */ - public static String renderTemplate(String template, String data) - throws TransformerException { + public static String renderTemplate(String template, String data) throws TransformerException { String result = null; TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(SAXSource.FEATURE)) { // setup for xml data file preprocessing to be able to xinclude - SAXParserFactory pfactory= SAXParserFactory.newInstance(); + SAXParserFactory pfactory = SAXParserFactory.newInstance(); pfactory.setNamespaceAware(true); pfactory.setValidating(false); pfactory.setXIncludeAware(true); @@ -107,7 +106,7 @@ public final class XslTransform { Templates translet = null; String templateName = (String) context.get("templateName"); if (UtilValidate.isNotEmpty(templateName)) { - translet = xslTemplatesCache.get(templateName); + translet = XSL_TEMPLATE_CACHE.get(templateName); } if (translet == null) { @@ -117,7 +116,7 @@ public final class XslTransform { Source templateSource = getSource(templateDocument, templateUrl, templateString); translet = tFactory.newTemplates(templateSource); if (UtilValidate.isNotEmpty(templateName)) { - translet = xslTemplatesCache.putIfAbsentAndGet(templateName, translet); + translet = XSL_TEMPLATE_CACHE.putIfAbsentAndGet(templateName, translet); } } if (translet != null) { @@ -160,7 +159,7 @@ public final class XslTransform { URL url = FlexibleLocation.resolveLocation(inputUrl); URLConnection conn = URLConnector.openConnection(url); try (InputStream in = conn.getInputStream()) { - source = new StreamSource(in); + source = new StreamSource(in); } } return source; diff --git a/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/OFBizRealm.java b/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/OFBizRealm.java index 0b180a7..b0b24d2 100644 --- a/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/OFBizRealm.java +++ b/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/OFBizRealm.java @@ -31,8 +31,7 @@ import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; -public class OFBizRealm extends RealmBase -{ +public class OFBizRealm extends RealmBase { private static final String MODULE = OFBizRealm.class.getName(); @Override @@ -40,7 +39,7 @@ public class OFBizRealm extends RealmBase Delegator delegator = DelegatorFactory.getDelegator(null); try { GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", username).queryOne(); - if (userLogin!=null) { + if (userLogin != null) { return userLogin.getString("currentPassword"); } } catch (GenericEntityException e) { @@ -56,5 +55,4 @@ public class OFBizRealm extends RealmBase getPassword(username), roles); } - -} \ No newline at end of file +} diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/CdyneServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/CdyneServices.java index 8368f2a..9025b88 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/CdyneServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/CdyneServices.java @@ -43,7 +43,7 @@ public class CdyneServices { private static final String MODULE = CdyneServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; - public static final String licenseKey = UtilProperties.getPropertyValue("cdyne", "LicenseKey", "0"); + public static final String LICENSE_KEY = UtilProperties.getPropertyValue("cdyne", "LicenseKey", "0"); /** * CDyne ReturnCityState Service @@ -54,7 +54,7 @@ public class CdyneServices { public static Map<String, Object> cdyneReturnCityState(DispatchContext dctx, Map<String, ?> context) { String zipcode = (String) context.get("zipcode"); Locale locale = (Locale) context.get("locale"); - String serviceUrl = "http://ws.cdyne.com/psaddress/addresslookup.asmx/ReturnCityState?zipcode=" + zipcode + "&LicenseKey=" + licenseKey; + String serviceUrl = "http://ws.cdyne.com/psaddress/addresslookup.asmx/ReturnCityState?zipcode=" + zipcode + "&LicenseKey=" + LICENSE_KEY; try { String httpResponse = HttpClient.getUrlContent(serviceUrl); @@ -65,19 +65,23 @@ public class CdyneServices { populateCdyneAddress(addressRootElement, response); if ("true".equals(response.get("ServiceError"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneServiceError", UtilMisc.toMap("zipcode", zipcode), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneServiceError", + UtilMisc.toMap("zipcode", zipcode), locale)); } if ("true".equals(response.get("AddressError"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneAddressError", UtilMisc.toMap("zipcode", zipcode), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneAddressError", + UtilMisc.toMap("zipcode", zipcode), locale)); } return response; } catch (HttpClientException e) { Debug.logError(e, "Error calling CDyne service at URL [" + serviceUrl + "]: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneCallingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneCallingError", + UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale)); } catch (SAXException | ParserConfigurationException | IOException e) { Debug.logError(e, "Error parsing XML result from CDyne service at URL [" + serviceUrl + "]: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneParsingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonCDyneParsingError", + UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale)); } } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/CommonServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/CommonServices.java index 8eaee14..c84b74b 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/CommonServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/CommonServices.java @@ -126,7 +126,7 @@ public class CommonServices { public static Map<String, Object> blockingTestService(DispatchContext dctx, Map<String, ?> context) { Long duration = (Long) context.get("duration"); if (duration == null) { - duration = 30000l; + duration = 30000L; } Debug.logInfo("-----SERVICE BLOCKING----- : " + duration / 1000d + " seconds", MODULE); try { @@ -190,7 +190,8 @@ public class CommonServices { delegator.create(newValue); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonNoteCannotBeUpdated", UtilMisc.toMap("errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonNoteCannotBeUpdated", + UtilMisc.toMap("errorString", e.getMessage()), locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); @@ -336,7 +337,7 @@ public class CommonServices { public static Map<String, Object> displayXaDebugInfo(DispatchContext dctx, Map<String, ?> context) { if (TransactionUtil.debugResources()) { - if (UtilValidate.isNotEmpty(TransactionUtil.debugResMap)) { + if (UtilValidate.isNotEmpty(TransactionUtil.DEBUG_RES_MAP)) { TransactionUtil.logRunningTx(); } else { Debug.logInfo("No running transaction to display.", MODULE); @@ -356,7 +357,8 @@ public class CommonServices { String ofbizHome = System.getProperty("ofbiz.home"); String outputPath1 = ofbizHome + (fileName1.startsWith("/") ? fileName1 : "/" + fileName1); String outputPath2 = ofbizHome + (fileName2.startsWith("/") ? fileName2 : "/" + fileName2); - RandomAccessFile file1 = null, file2 = null; + RandomAccessFile file1 = null; + RandomAccessFile file2 = null; try { file1 = new RandomAccessFile(outputPath1, "rw"); @@ -533,7 +535,8 @@ public class CommonServices { Locale locale = (Locale) context.get("locale"); String name = UtilCodec.getDecoder("url").decode(originalName); if (name == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonExceptionThrownWhileDecodingMetric", UtilMisc.toMap("originalName", originalName), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "CommonExceptionThrownWhileDecodingMetric", + UtilMisc.toMap("originalName", originalName), locale)); } Metrics metric = MetricsFactory.getMetric(name); if (metric != null) { diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/FindServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/FindServices.java index 2440a91..b395e5b 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/FindServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/FindServices.java @@ -69,22 +69,22 @@ public class FindServices { private static final String MODULE = FindServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; - public static final Map<String, EntityComparisonOperator<?, ?>> entityOperators; + public static final Map<String, EntityComparisonOperator<?, ?>> ENTITY_OPERATORS; static { - entityOperators = new LinkedHashMap<>(); - entityOperators.put("between", EntityOperator.BETWEEN); - entityOperators.put("equals", EntityOperator.EQUALS); - entityOperators.put("greaterThan", EntityOperator.GREATER_THAN); - entityOperators.put("greaterThanEqualTo", EntityOperator.GREATER_THAN_EQUAL_TO); - entityOperators.put("in", EntityOperator.IN); - entityOperators.put("not-in", EntityOperator.NOT_IN); - entityOperators.put("lessThan", EntityOperator.LESS_THAN); - entityOperators.put("lessThanEqualTo", EntityOperator.LESS_THAN_EQUAL_TO); - entityOperators.put("like", EntityOperator.LIKE); - entityOperators.put("notLike", EntityOperator.NOT_LIKE); - entityOperators.put("not", EntityOperator.NOT); - entityOperators.put("notEqual", EntityOperator.NOT_EQUAL); + ENTITY_OPERATORS = new LinkedHashMap<>(); + ENTITY_OPERATORS.put("between", EntityOperator.BETWEEN); + ENTITY_OPERATORS.put("equals", EntityOperator.EQUALS); + ENTITY_OPERATORS.put("greaterThan", EntityOperator.GREATER_THAN); + ENTITY_OPERATORS.put("greaterThanEqualTo", EntityOperator.GREATER_THAN_EQUAL_TO); + ENTITY_OPERATORS.put("in", EntityOperator.IN); + ENTITY_OPERATORS.put("not-in", EntityOperator.NOT_IN); + ENTITY_OPERATORS.put("lessThan", EntityOperator.LESS_THAN); + ENTITY_OPERATORS.put("lessThanEqualTo", EntityOperator.LESS_THAN_EQUAL_TO); + ENTITY_OPERATORS.put("like", EntityOperator.LIKE); + ENTITY_OPERATORS.put("notLike", EntityOperator.NOT_LIKE); + ENTITY_OPERATORS.put("not", EntityOperator.NOT); + ENTITY_OPERATORS.put("notEqual", EntityOperator.NOT_EQUAL); } public FindServices() { } @@ -360,7 +360,7 @@ public class FindServices { EntityCondition endCond = EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN, endValue); return EntityCondition.makeCondition(startCond, endCond); } else { - fieldOp = entityOperators.get(operation); + fieldOp = ENTITY_OPERATORS.get(operation); } } else { List<Object> fieldList = (fieldValue instanceof List) ? UtilGenerics.cast(fieldValue) : null; diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/JsLanguageFilesMapping.java b/framework/common/src/main/java/org/apache/ofbiz/common/JsLanguageFilesMapping.java index c742024..5fcf8c6 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/JsLanguageFilesMapping.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/JsLanguageFilesMapping.java @@ -29,7 +29,7 @@ public final class JsLanguageFilesMapping { // DO NOT EDIT THIS FILE! THIS IS AUTO GENERATED AND WILL GET WRITTEN OVER PERIODICALLY WHEN THE DATA CHANGE // Rather use the createJsLanguageFileMapping service to create or update it. You will still need to compile thereafter - public static class datejs { + public static class DateJs { private static Map<String, String> localeFiles = new HashMap<>(); private static String defaultDateJs = "/common/js/jquery/plugins/datejs/date-en-US.js"; @@ -197,15 +197,15 @@ public final class JsLanguageFilesMapping { } public static String getFilePath(String locale) { - if (datejs.localeFiles.containsKey(locale)) { - return datejs.localeFiles.get(locale); + if (DateJs.localeFiles.containsKey(locale)) { + return DateJs.localeFiles.get(locale); } - return datejs.defaultDateJs; + return DateJs.defaultDateJs; } } - public static class jquery { + public static class JQuery { private static Map<String, String> localeFiles = new HashMap<>(); private static String defaultDateJs = "/common/js/jquery/ui/i18n/jquery.ui.datepicker-en.js"; @@ -372,15 +372,15 @@ public final class JsLanguageFilesMapping { } public static String getFilePath(String locale) { - if (datejs.localeFiles.containsKey(locale)) { - return jquery.localeFiles.get(locale); + if (DateJs.localeFiles.containsKey(locale)) { + return JQuery.localeFiles.get(locale); } - return jquery.defaultDateJs; + return JQuery.defaultDateJs; } } - public static class validation { + public static class Validation { private static Map<String, String> localeFiles = new HashMap<>(); private static String defaultValidation = "/common/js/jquery/plugins/validate/localization/messages_en.js"; @@ -547,14 +547,14 @@ public final class JsLanguageFilesMapping { } public static String getFilePath(String locale) { - if (validation.localeFiles.containsKey(locale)) { - return validation.localeFiles.get(locale); + if (Validation.localeFiles.containsKey(locale)) { + return Validation.localeFiles.get(locale); } - return validation.defaultValidation; + return Validation.defaultValidation; } } - public static class dateTime { + public static class DateTime { private static Map<String, String> localeFiles = new HashMap<>(); private static String defaultDateTime = "/common/js/jquery/ui/i18n/jquery.ui.datepicker-en.js"; @@ -721,14 +721,14 @@ public final class JsLanguageFilesMapping { } public static String getFilePath(String locale) { - if (dateTime.localeFiles.containsKey(locale)) { - return dateTime.localeFiles.get(locale); + if (DateTime.localeFiles.containsKey(locale)) { + return DateTime.localeFiles.get(locale); } - return dateTime.defaultDateTime; + return DateTime.defaultDateTime; } } - public static class select2 { + public static class Select2 { private static Map<String, String> localeFiles = new HashMap<>(); private static String defaultSelect2 = "/common/js/jquery/plugins/select2/js/i18n/en.js"; @@ -895,10 +895,10 @@ public final class JsLanguageFilesMapping { } public static String getFilePath(String locale) { - if (select2.localeFiles.containsKey(locale)) { - return select2.localeFiles.get(locale); + if (Select2.localeFiles.containsKey(locale)) { + return Select2.localeFiles.get(locale); } - return select2.defaultSelect2; + return Select2.defaultSelect2; } } } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/authentication/AuthHelper.java b/framework/common/src/main/java/org/apache/ofbiz/common/authentication/AuthHelper.java index 36ab349..bb58535 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/authentication/AuthHelper.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/authentication/AuthHelper.java @@ -99,11 +99,11 @@ public final class AuthHelper { public static void loadAuthenticators(LocalDispatcher dispatcher) { if (!authenticatorsLoaded) { - loadAuthenticators_internal(dispatcher); + loadAuthenticatorsInternal(dispatcher); } } - private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) { + private static synchronized void loadAuthenticatorsInternal(LocalDispatcher dispatcher) { if (!authenticatorsLoaded) { Iterator<Authenticator> it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator(); while (it.hasNext()) { diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/test/PerformFindTests.java b/framework/common/src/main/java/org/apache/ofbiz/common/test/PerformFindTests.java index 4992e09..954853d 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/test/PerformFindTests.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/test/PerformFindTests.java @@ -31,6 +31,7 @@ import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityListIterator; +import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ServiceUtil; import org.apache.ofbiz.service.testtools.OFBizTestCase; import org.apache.ofbiz.entity.util.EntityQuery; @@ -115,6 +116,7 @@ public class PerformFindTests extends OFBizTestCase { GenericValue userLogin = getUserLogin("system"); prepareData(); + LocalDispatcher dispatcher = getDispatcher(); Map<String, Object> inputFields = new HashMap<>(); //first test without condition Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields); @@ -152,6 +154,7 @@ public class PerformFindTests extends OFBizTestCase { GenericValue userLogin = getUserLogin("system"); prepareData(); + LocalDispatcher dispatcher = getDispatcher(); //first test like condition Map<String, Object> inputFields = UtilMisc.toMap("testingName", "nice", "testingName_op", "like"); Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields); @@ -189,17 +192,20 @@ public class PerformFindTests extends OFBizTestCase { GenericValue userLogin = getUserLogin("system"); prepareData(); + LocalDispatcher dispatcher = getDispatcher(); //first test without distinct condition Map<String, Object> inputFields = UtilMisc.toMap("testingTypeId", "PERFOMFINDTEST"); - List<String> fieldList= UtilMisc.toList("testingName", "testingTypeId"); - Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, "fieldList", fieldList, "distinct", "N"); + List<String> fieldList = UtilMisc.toList("testingName", "testingTypeId"); + Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", + inputFields, "fieldList", fieldList, "distinct", "N"); Map<String, Object> result = dispatcher.runSync("performFind", performFindMap); assertTrue(ServiceUtil.isSuccess(result)); List<GenericValue> foundElements = getCompleteList(result); assertEquals("performFind search with distinct N", 9, foundElements.size()); //second test with distinct condition - performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, "fieldList", fieldList, "distinct", "Y"); + performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, + "fieldList", fieldList, "distinct", "Y"); result = dispatcher.runSync("performFind", performFindMap); assertTrue(ServiceUtil.isSuccess(result)); foundElements = getCompleteList(result); @@ -210,16 +216,19 @@ public class PerformFindTests extends OFBizTestCase { GenericValue userLogin = getUserLogin("system"); prepareData(); + LocalDispatcher dispatcher = getDispatcher(); //first test without filterDate condition Map<String, Object> inputFields = UtilMisc.toMap("testingNodeId", "NODE_1"); - Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields, "filterByDate", "N", "filterByDateValue", UtilDateTime.nowTimestamp()); + Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", + "inputFields", inputFields, "filterByDate", "N", "filterByDateValue", UtilDateTime.nowTimestamp()); Map<String, Object> result = dispatcher.runSync("performFind", performFindMap); assertTrue(ServiceUtil.isSuccess(result)); List<GenericValue> foundElements = getCompleteList(result); assertEquals("performFind search with filterDate N", 5, foundElements.size()); //second test with filterDate condition - performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields, "filterByDate", "Y", "filterByDateValue", UtilDateTime.nowTimestamp()); + performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", + inputFields, "filterByDate", "Y", "filterByDateValue", UtilDateTime.nowTimestamp()); result = dispatcher.runSync("performFind", performFindMap); assertTrue(ServiceUtil.isSuccess(result)); foundElements = getCompleteList(result); @@ -230,6 +239,7 @@ public class PerformFindTests extends OFBizTestCase { GenericValue userLogin = getUserLogin("system"); prepareData(); + LocalDispatcher dispatcher = getDispatcher(); //first test without filterDate condition Map<String, Object> inputFields = UtilMisc.toMap("testingNodeId", "NODE_1"); Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields, diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/DelegatorFactory.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/DelegatorFactory.java index bfc2416..c810e07 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/DelegatorFactory.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/DelegatorFactory.java @@ -33,9 +33,10 @@ import org.apache.ofbiz.base.util.UtilObject; /** <code>Delegator</code> factory abstract class. */ public abstract class DelegatorFactory implements Factory<Delegator, String> { private static final String MODULE = DelegatorFactory.class.getName(); - private static final ConcurrentHashMap<String, Future<Delegator>> delegators = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, Future<Delegator>> DELEGATORS = new ConcurrentHashMap<>(); private static final ThreadGroup DELEGATOR_THREAD_GROUP = new ThreadGroup("DelegatorFactory"); - private static final ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(DELEGATOR_THREAD_GROUP, "delegator-startup", Runtime.getRuntime().availableProcessors(), 10, true); + private static final ScheduledExecutorService EXECUTOR = ExecutionPool.getScheduledExecutor(DELEGATOR_THREAD_GROUP, "delegator-startup", + Runtime.getRuntime().availableProcessors(), 10, true); public static Delegator getDelegator(String delegatorName) { Future<Delegator> future = getDelegatorFuture(delegatorName); @@ -52,15 +53,15 @@ public abstract class DelegatorFactory implements Factory<Delegator, String> { delegatorName = "default"; } do { - Future<Delegator> future = delegators.get(delegatorName); + Future<Delegator> future = DELEGATORS.get(delegatorName); if (future != null) { return future; } FutureTask<Delegator> futureTask = new FutureTask<>(new DelegatorConfigurable(delegatorName)); - if (delegators.putIfAbsent(delegatorName, futureTask) != null) { + if (DELEGATORS.putIfAbsent(delegatorName, futureTask) != null) { continue; } - executor.submit(futureTask); + EXECUTOR.submit(futureTask); } while (true); } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionValue.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionValue.java index 6697041..6e9baa3 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionValue.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionValue.java @@ -39,8 +39,10 @@ import org.apache.ofbiz.entity.model.ModelField; @SuppressWarnings("serial") public abstract class EntityConditionValue implements Serializable { - private static final Map<String, String> emptyAliases = Collections.unmodifiableMap(new HashMap<>()); - public static EntityConditionValue CONSTANT_NUMBER(Number value) { return new ConstantNumberValue(value); } + private static final Map<String, String> EMPTY_ALIASES = Collections.unmodifiableMap(new HashMap<>()); + public static EntityConditionValue constantNumber(Number value) { + return new ConstantNumberValue(value); + } public static final class ConstantNumberValue extends EntityConditionValue { private Number value; @@ -82,9 +84,17 @@ public abstract class EntityConditionValue implements Serializable { public abstract void setModelField(ModelField modelEntity); + /** + * Add sql value. + * @param sql the sql + * @param modelEntity the model entity + * @param entityConditionParams the entity condition params + * @param includeTableNamePrefix the include table name prefix + * @param datasourceinfo the datasourceinfo + */ public void addSqlValue(StringBuilder sql, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceinfo) { - addSqlValue(sql, emptyAliases, modelEntity, entityConditionParams, includeTableNamePrefix, datasourceinfo); + addSqlValue(sql, EMPTY_ALIASES, modelEntity, entityConditionParams, includeTableNamePrefix, datasourceinfo); } public abstract void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/config/model/EntityConfig.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/config/model/EntityConfig.java index 4f911ea..a512598 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/config/model/EntityConfig.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/config/model/EntityConfig.java @@ -44,7 +44,7 @@ public final class EntityConfig { private static final String MODULE = EntityConfig.class.getName(); - private static final EntityConfig instance = createNewInstance(); + private static final EntityConfig INSTANCE = createNewInstance(); private final List<ResourceLoader> resourceLoaderList; // <resource-loader> private final Map<String, ResourceLoader> resourceLoaderMap; // <resource-loader> private final TransactionFactory transactionFactory; // <transaction-factory> @@ -222,10 +222,10 @@ public final class EntityConfig { } public static EntityConfig getInstance() throws GenericEntityConfException { - if (instance == null) { + if (INSTANCE == null) { throw new GenericEntityConfException("EntityConfig is not initialized."); } - return instance; + return INSTANCE; } public static String createConfigFileLineNumberText(Element element) { @@ -354,12 +354,14 @@ public final class EntityConfig { } String jdbcPasswordLookup = inlineJdbcElement.getJdbcPasswordLookup(); if (jdbcPasswordLookup.isEmpty()) { - throw new GenericEntityConfException("No jdbc-password or jdbc-password-lookup specified for inline-jdbc element, line: " + inlineJdbcElement.getLineNumber()); + throw new GenericEntityConfException("No jdbc-password or jdbc-password-lookup specified for inline-jdbc element, line: " + + inlineJdbcElement.getLineNumber()); } String key = "jdbc-password.".concat(jdbcPasswordLookup); jdbcPassword = UtilProperties.getPropertyValue("passwords", key); if (jdbcPassword.isEmpty()) { - throw new GenericEntityConfException("'" + key + "' property not found in passwords.properties file for inline-jdbc element, line: " + inlineJdbcElement.getLineNumber()); + throw new GenericEntityConfException("'" + key + "' property not found in passwords.properties file for inline-jdbc element, line: " + + inlineJdbcElement.getLineNumber()); } return jdbcPassword; } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/connection/DBCPConnectionFactory.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/connection/DBCPConnectionFactory.java index 42e0791..66c51c3 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/connection/DBCPConnectionFactory.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/connection/DBCPConnectionFactory.java @@ -54,14 +54,15 @@ public class DBCPConnectionFactory implements ConnectionFactory { private static final String MODULE = DBCPConnectionFactory.class.getName(); // ManagedDataSource is useful to debug the usage of connections in the pool (must be verbose) - // In case you don't want to be disturbed in the log (focusing on something else), it's still easy to comment out the line from DebugManagedDataSource - protected static final ConcurrentHashMap<String, DebugManagedDataSource<? extends Connection>> dsCache = + // In case you don't want to be disturbed in the log (focusing on something else), it's still easy to comment out the line + // from DebugManagedDataSource + protected static final ConcurrentHashMap<String, DebugManagedDataSource<? extends Connection>> DS_CACHE = new ConcurrentHashMap<>(); @Override public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException { String cacheKey = helperInfo.getHelperFullName(); - DebugManagedDataSource<? extends Connection> mds = dsCache.get(cacheKey); + DebugManagedDataSource<? extends Connection> mds = DS_CACHE.get(cacheKey); if (mds != null) { return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); } @@ -88,7 +89,8 @@ public class DBCPConnectionFactory implements ConnectionFactory { synchronized (DBCPConnectionFactory.class) { // Sync needed for MS SQL JDBC driver. See OFBIZ-5216. try { - jdbcDriver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).getDeclaredConstructor().newInstance(); + jdbcDriver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()) + .getDeclaredConstructor().newInstance(); } catch (Exception e) { Debug.logError(e, MODULE); throw new GenericEntityException(e.getMessage(), e); @@ -139,7 +141,8 @@ public class DBCPConnectionFactory implements ConnectionFactory { poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections // settings for when the pool is exhausted poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available - poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread + poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, + // no connection is available for the requesting thread // settings for the execution of the validation query poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate()); poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow()); @@ -153,8 +156,8 @@ public class DBCPConnectionFactory implements ConnectionFactory { mds.setAccessToUnderlyingConnectionAllowed(true); // cache the pool - dsCache.putIfAbsent(cacheKey, mds); - mds = dsCache.get(cacheKey); + DS_CACHE.putIfAbsent(cacheKey, mds); + mds = DS_CACHE.get(cacheKey); return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); } @@ -162,12 +165,12 @@ public class DBCPConnectionFactory implements ConnectionFactory { @Override public void closeAll() { // no methods on the pool to shutdown; so just clearing for GC - dsCache.clear(); + DS_CACHE.clear(); } public static Map<String, Object> getDataSourceInfo(String helperName) { Map<String, Object> dataSourceInfo = new HashMap<>(); - DebugManagedDataSource<? extends Connection> mds = dsCache.get(helperName); + DebugManagedDataSource<? extends Connection> mds = DS_CACHE.get(helperName); if (mds != null) { dataSourceInfo = mds.getInfo(); } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericDAO.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericDAO.java index 2c0e008..2348ae9 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericDAO.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericDAO.java @@ -70,7 +70,7 @@ public class GenericDAO { private static final String MODULE = GenericDAO.class.getName(); - private static final ConcurrentHashMap<String, GenericDAO> genericDAOs = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, GenericDAO> GENERIC_DAOS = new ConcurrentHashMap<>(); private final GenericHelperInfo helperInfo; private final ModelFieldTypeReader modelFieldTypeReader; private final Datasource datasource; @@ -83,10 +83,10 @@ public class GenericDAO { public static GenericDAO getGenericDAO(GenericHelperInfo helperInfo) { String cacheKey = helperInfo.getHelperFullName(); - GenericDAO newGenericDAO = genericDAOs.get(cacheKey); + GenericDAO newGenericDAO = GENERIC_DAOS.get(cacheKey); if (newGenericDAO == null) { - genericDAOs.putIfAbsent(cacheKey, new GenericDAO(helperInfo)); - newGenericDAO = genericDAOs.get(cacheKey); + GENERIC_DAOS.putIfAbsent(cacheKey, new GenericDAO(helperInfo)); + newGenericDAO = GENERIC_DAOS.get(cacheKey); } return newGenericDAO; } @@ -101,6 +101,12 @@ public class GenericDAO { fieldsToSave.add(modelEntity.getField(fieldName)); } + /** + * Insert int. + * @param entity the entity + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int insert(GenericEntity entity) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); @@ -146,7 +152,8 @@ public class GenericDAO { // if we have a STAMP_FIELD or CREATE_STAMP_FIELD then set it with NOW boolean stampIsField = modelEntity.isField(ModelEntity.STAMP_FIELD); boolean createStampIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_FIELD); - if ((stampIsField || createStampIsField) && (!entity.getIsFromEntitySync() || (stampIsField && entity.get(ModelEntity.STAMP_FIELD) == null) || (createStampIsField && entity.get(ModelEntity.CREATE_STAMP_FIELD) == null))) { + if ((stampIsField || createStampIsField) && (!entity.getIsFromEntitySync() || (stampIsField && entity.get(ModelEntity.STAMP_FIELD) == null) + || (createStampIsField && entity.get(ModelEntity.CREATE_STAMP_FIELD) == null))) { Timestamp startStamp = TransactionUtil.getTransactionUniqueNowStamp(); if (stampIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) { entity.set(ModelEntity.STAMP_FIELD, startStamp); @@ -177,12 +184,24 @@ public class GenericDAO { } } + /** + * Update all int. + * @param entity the entity + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int updateAll(GenericEntity entity) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); return customUpdate(entity, modelEntity, modelEntity.getNopksCopy()); } + /** + * Update int. + * @param entity the entity + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int update(GenericEntity entity) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); @@ -282,6 +301,15 @@ public class GenericDAO { return retVal; } + /** + * Update by condition int. + * @param delegator the delegator + * @param modelEntity the model entity + * @param fieldsToSet the fields to set + * @param condition the condition + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int updateByCondition(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException { @@ -295,6 +323,15 @@ public class GenericDAO { } } + /** + * Update by condition int. + * @param modelEntity the model entity + * @param fieldsToSet the fields to set + * @param condition the condition + * @param sqlP the sql p + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int updateByCondition(ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition, SQLProcessor sqlP) throws GenericEntityException { if (modelEntity == null || fieldsToSet == null || condition == null) { @@ -492,12 +529,23 @@ public class GenericDAO { /* ====================================================================== */ + /** + * Select. + * @param entity the entity + * @throws GenericEntityException the generic entity exception + */ public void select(GenericEntity entity) throws GenericEntityException { try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) { select(entity, sqlP); } } + /** + * Select. + * @param entity the entity + * @param sqlP the sql p + * @throws GenericEntityException the generic entity exception + */ public void select(GenericEntity entity, SQLProcessor sqlP) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); @@ -536,6 +584,12 @@ public class GenericDAO { } } + /** + * Partial select. + * @param entity the entity + * @param keys the keys + * @throws GenericEntityException the generic entity exception + */ public void partialSelect(GenericEntity entity, Set<String> keys) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); @@ -792,6 +846,15 @@ public class GenericDAO { findOptions.getDistinct()); } + /** + * Make condition where string string builder. + * @param modelEntity the model entity + * @param whereEntityCondition the where entity condition + * @param viewWhereConditions the view where conditions + * @param whereEntityConditionParams the where entity condition params + * @return the string builder + * @throws GenericEntityException the generic entity exception + */ @Deprecated protected StringBuilder makeConditionWhereString(ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, @@ -799,6 +862,17 @@ public class GenericDAO { return makeConditionWhereString(new StringBuilder(), "", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams); } + /** + * Make condition where string string builder. + * @param whereString the where string + * @param prefix the prefix + * @param modelEntity the model entity + * @param whereEntityCondition the where entity condition + * @param viewWhereConditions the view where conditions + * @param whereEntityConditionParams the where entity condition params + * @return the string builder + * @throws GenericEntityException the generic entity exception + */ protected StringBuilder makeConditionWhereString(StringBuilder whereString, String prefix, ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException { @@ -834,6 +908,15 @@ public class GenericDAO { return whereString; } + /** + * Make condition having string string builder. + * @param modelEntity the model entity + * @param havingEntityCondition the having entity condition + * @param viewHavingConditions the view having conditions + * @param havingEntityConditionParams the having entity condition params + * @return the string builder + * @throws GenericEntityException the generic entity exception + */ @Deprecated protected StringBuilder makeConditionHavingString(ModelEntity modelEntity, EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, @@ -842,6 +925,17 @@ public class GenericDAO { havingEntityConditionParams); } + /** + * Make condition having string string builder. + * @param havingString the having string + * @param prefix the prefix + * @param modelEntity the model entity + * @param havingEntityCondition the having entity condition + * @param viewHavingConditions the view having conditions + * @param havingEntityConditionParams the having entity condition params + * @return the string builder + * @throws GenericEntityException the generic entity exception + */ protected StringBuilder makeConditionHavingString(StringBuilder havingString, String prefix, ModelEntity modelEntity, EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException { @@ -883,6 +977,12 @@ public class GenericDAO { return havingString; } + /** + * Make offset string string builder. + * @param offsetString the offset string + * @param findOptions the find options + * @return the string builder + */ protected StringBuilder makeOffsetString(StringBuilder offsetString, EntityFindOptions findOptions) { if (UtilValidate.isNotEmpty(datasource.getOffsetStyle())) { if ("limit".equals(datasource.getOffsetStyle())) { @@ -906,6 +1006,17 @@ public class GenericDAO { return offsetString; } + /** + * Select by multi relation list. + * @param value the value + * @param modelRelationOne the model relation one + * @param modelEntityOne the model entity one + * @param modelRelationTwo the model relation two + * @param modelEntityTwo the model entity two + * @param orderBy the order by + * @return the list + * @throws GenericEntityException the generic entity exception + */ public List<GenericValue> selectByMultiRelation(GenericValue value, ModelRelation modelRelationOne, ModelEntity modelEntityOne, ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) throws GenericEntityException { @@ -1006,11 +1117,32 @@ public class GenericDAO { return retlist; } + /** + * Select count by condition long. + * @param delegator the delegator + * @param modelEntity the model entity + * @param whereEntityCondition the where entity condition + * @param havingEntityCondition the having entity condition + * @param findOptions the find options + * @return the long + * @throws GenericEntityException the generic entity exception + */ public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException { return selectCountByCondition(delegator, modelEntity, whereEntityCondition, havingEntityCondition, null, findOptions); } + /** + * Select count by condition long. + * @param delegator the delegator + * @param modelEntity the model entity + * @param whereEntityCondition the where entity condition + * @param havingEntityCondition the having entity condition + * @param selectFields the select fields + * @param findOptions the find options + * @return the long + * @throws GenericEntityException the generic entity exception + */ public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) throws GenericEntityException { @@ -1087,8 +1219,8 @@ public class GenericDAO { viewWhereConditions = new LinkedList<>(); viewHavingConditions = new LinkedList<>(); viewOrderByList = new LinkedList<>(); - modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList - , null); + modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, + null); } // FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well @@ -1156,10 +1288,12 @@ public class GenericDAO { } } - /* ====================================================================== */ - - /* ====================================================================== */ - + /** + * Delete int. + * @param entity the entity + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int delete(GenericEntity entity) throws GenericEntityException { try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) { try { @@ -1171,6 +1305,13 @@ public class GenericDAO { } } + /** + * Delete int. + * @param entity the entity + * @param sqlP the sql p + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int delete(GenericEntity entity, SQLProcessor sqlP) throws GenericEntityException { ModelEntity modelEntity = entity.getModelEntity(); @@ -1190,6 +1331,14 @@ public class GenericDAO { return retVal; } + /** + * Delete by condition int. + * @param delegator the delegator + * @param modelEntity the model entity + * @param condition the condition + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int deleteByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition condition) throws GenericEntityException { try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) { try { @@ -1201,9 +1350,18 @@ public class GenericDAO { } } + /** + * Delete by condition int. + * @param modelEntity the model entity + * @param condition the condition + * @param sqlP the sql p + * @return the int + * @throws GenericEntityException the generic entity exception + */ public int deleteByCondition(ModelEntity modelEntity, EntityCondition condition, SQLProcessor sqlP) throws GenericEntityException { - if (modelEntity == null || condition == null) + if (modelEntity == null || condition == null) { return 0; + } if (modelEntity instanceof ModelViewEntity) { throw new org.apache.ofbiz.entity.GenericNotImplementedException("Operation deleteByCondition not supported yet for view entities"); } @@ -1219,8 +1377,12 @@ public class GenericDAO { return sqlP.executeUpdate(); } - /* ====================================================================== */ - + /** + * Check db. + * @param modelEntities the model entities + * @param messages the messages + * @param addMissing the add missing + */ public void checkDb(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) { DatabaseUtil dbUtil = new DatabaseUtil(this.helperInfo); dbUtil.checkDb(modelEntities, messages, addMissing); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperFactory.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperFactory.java index b2afbdd..52d296a 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperFactory.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperFactory.java @@ -36,15 +36,15 @@ public class GenericHelperFactory { private static final String MODULE = GenericHelperFactory.class.getName(); // protected static UtilCache helperCache = new UtilCache("entity.GenericHelpers", 0, 0); - protected static final Map<String, GenericHelper> helperCache = new HashMap<>(); + protected static final Map<String, GenericHelper> HELPER_CACHE = new HashMap<>(); public static GenericHelper getHelper(GenericHelperInfo helperInfo) { - GenericHelper helper = helperCache.get(helperInfo.getHelperFullName()); + GenericHelper helper = HELPER_CACHE.get(helperInfo.getHelperFullName()); if (helper == null) { // don't want to block here synchronized (GenericHelperFactory.class) { // must check if null again as one of the blocked threads can still enter - helper = helperCache.get(helperInfo.getHelperFullName()); + helper = HELPER_CACHE.get(helperInfo.getHelperFullName()); if (helper == null) { try { Datasource datasourceInfo = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); @@ -86,8 +86,9 @@ public class GenericHelperFactory { throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage()); } - if (helper != null) - helperCache.put(helperInfo.getHelperFullName(), helper); + if (helper != null) { + HELPER_CACHE.put(helperInfo.getHelperFullName(), helper); + } } catch (SecurityException e) { Debug.logError(e, MODULE); throw new IllegalStateException("Error loading GenericHelper class: " + e.toString()); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/ConnectionFactoryLoader.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/ConnectionFactoryLoader.java index a7d2abe..ccae445 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/ConnectionFactoryLoader.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/ConnectionFactoryLoader.java @@ -24,12 +24,11 @@ import org.apache.ofbiz.entity.connection.ConnectionFactory; /** * ConnectionFactoryLoader - utility class that loads the connection manager and provides to client code a reference to it (ConnectionFactory) - * */ public class ConnectionFactoryLoader { // Debug MODULE name private static final String MODULE = ConnectionFactoryLoader.class.getName(); - private static final ConnectionFactory connFactory = createConnectionFactory(); + private static final ConnectionFactory CONN_FACTORY = createConnectionFactory(); private static ConnectionFactory createConnectionFactory() { ConnectionFactory instance = null; @@ -53,9 +52,9 @@ public class ConnectionFactoryLoader { } public static ConnectionFactory getInstance() { - if (connFactory == null) { + if (CONN_FACTORY == null) { throw new IllegalStateException("The Connection Factory is not initialized."); } - return connFactory; + return CONN_FACTORY; } } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/JdbcValueHandler.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/JdbcValueHandler.java index 1dc27e5..91b46c6 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/JdbcValueHandler.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/JdbcValueHandler.java @@ -45,8 +45,8 @@ import org.apache.ofbiz.base.util.Debug; */ public abstract class JdbcValueHandler<T> { private static final String MODULE = JdbcValueHandler.class.getName(); - private static final Map<String, JdbcValueHandler<?>> JdbcValueHandlerMap = createJdbcValueHandlerMap(); - private static final Map<String, Integer> SqlTypeMap = createSqlTypeMap(); + private static final Map<String, JdbcValueHandler<?>> JDBC_VALUE_HANDLER_MAP = createJdbcValueHandlerMap(); + private static final Map<String, Integer> SQL_TYPE_MAP = createSqlTypeMap(); private static Map<String, JdbcValueHandler<?>> createJdbcValueHandlerMap() { /* @@ -169,10 +169,10 @@ public abstract class JdbcValueHandler<T> { * @return A <code>JdbcValueHandler</code> instance */ public static JdbcValueHandler<?> getInstance(String javaType, String sqlType) { - JdbcValueHandler<?> handler = JdbcValueHandlerMap.get(javaType); + JdbcValueHandler<?> handler = JDBC_VALUE_HANDLER_MAP.get(javaType); if (handler != null) { String key = parseSqlType(sqlType); - Integer sqlTypeInt = SqlTypeMap.get(key); + Integer sqlTypeInt = SQL_TYPE_MAP.get(key); if (sqlTypeInt != null) { handler = handler.create(sqlTypeInt); } @@ -220,6 +220,11 @@ public abstract class JdbcValueHandler<T> { */ protected abstract void castAndSetValue(PreparedStatement ps, int parameterIndex, T obj) throws SQLException; + /** + * Create jdbc value handler. + * @param sqlType the sql type + * @return the jdbc value handler + */ protected JdbcValueHandler<T> create(int sqlType) { if (sqlType == this.getSqlType()) { return this; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SQLProcessor.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SQLProcessor.java index bad3329..264f4e4 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SQLProcessor.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SQLProcessor.java @@ -66,27 +66,27 @@ public class SQLProcessor implements AutoCloseable { private GenericHelperInfo helperInfo; // / The database resources to be used - private Connection _connection = null; + private Connection connection = null; // / The database resources to be used - private PreparedStatement _ps = null; + private PreparedStatement ps = null; // / The database resources to be used - private ResultSet _rs = null; + private ResultSet resultSet = null; - private ResultSetMetaData _rsmd = null; + private ResultSetMetaData resultSetMetaData = null; // / The SQL String used. Use for debugging only - private String _sql; + private String sql; - // / Index to be used with preparedStatement.setValue(_ind, ...) - private int _ind; + // / Index to be used with preparedStatement.setValue(ind, ...) + private int ind; // / true in case of manual transactions - private boolean _manualTX; + private boolean manualTx; // / true in case the connection shall be closed. - private boolean _bDeleteConnection = false; + private boolean bDeleteConnection = false; /** * Construct an object based on the helper/datasource @@ -95,7 +95,7 @@ public class SQLProcessor implements AutoCloseable { public SQLProcessor(Delegator delegator, GenericHelperInfo helperInfo) { this.delegator = delegator; this.helperInfo = helperInfo; - this._manualTX = true; + this.manualTx = true; } /** @@ -107,33 +107,41 @@ public class SQLProcessor implements AutoCloseable { public SQLProcessor(Delegator delegator, GenericHelperInfo helperInfo, Connection connection) { this.delegator = delegator; this.helperInfo = helperInfo; - this._connection = connection; + this.connection = connection; // Do not commit while closing - if (_connection != null) { - _manualTX = false; + if (connection != null) { + manualTx = false; } } + /** + * Gets delegator. + * @return the delegator + */ public Delegator getDelegator() { return delegator; } + /** + * Gets result set meta data. + * @return the result set meta data + */ ResultSetMetaData getResultSetMetaData() { - if (_rsmd == null) { + if (resultSetMetaData == null) { // try the ResultSet, if not null, or try the PreparedStatement, also if not null try { - if (_rs != null) { - _rsmd = _rs.getMetaData(); - } else if (_ps != null) { - _rsmd = _ps.getMetaData(); + if (resultSet != null) { + resultSetMetaData = resultSet.getMetaData(); + } else if (ps != null) { + resultSetMetaData = ps.getMetaData(); } } catch (SQLException sqle2) { Debug.logWarning("[SQLProcessor.rollback]: SQL Exception while rolling back insert. Error was:" + sqle2, MODULE); Debug.logWarning(sqle2, MODULE); } } - return _rsmd; + return resultSetMetaData; } /** @@ -141,17 +149,17 @@ public class SQLProcessor implements AutoCloseable { * @throws GenericDataSourceException */ public void commit() throws GenericDataSourceException { - if (_connection == null) { + if (connection == null) { return; } if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:commit() _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:commit() manualTx=" + manualTx, MODULE); } - if (_manualTX) { + if (manualTx) { try { - _connection.commit(); + connection.commit(); if (Debug.verboseOn()) { Debug.logVerbose("SQLProcessor:commit() : called commit on connection", MODULE); } @@ -171,25 +179,25 @@ public class SQLProcessor implements AutoCloseable { * Rollback all modifications */ public void rollback() throws GenericDataSourceException { - if (_connection == null) { + if (connection == null) { return; } if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:rollback() _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:rollback() manualTx=" + manualTx, MODULE); } try { - if (_manualTX) { - _connection.rollback(); + if (manualTx) { + connection.rollback(); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:rollback() : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:rollback() : manualTx=" + manualTx, MODULE); } } else { try { TransactionUtil.setRollbackOnly("rollback called in Entity Engine SQLProcessor", new Exception("Current Location Stack")); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:rollback() : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:rollback() : manualTx=" + manualTx, MODULE); } } catch (GenericTransactionException e) { Debug.logError(e, "Error setting rollback only", MODULE); @@ -208,52 +216,52 @@ public class SQLProcessor implements AutoCloseable { */ @Override public void close() throws GenericDataSourceException { - if (_manualTX) { + if (manualTx) { if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:close() calling commit : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:close() calling commit : manualTx=" + manualTx, MODULE); } commit(); } - _sql = null; + sql = null; - if (_rs != null) { + if (resultSet != null) { try { - _rs.close(); + resultSet.close(); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:close() result close : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:close() result close : manualTx=" + manualTx, MODULE); } } catch (SQLException sqle) { Debug.logWarning(sqle.getMessage(), MODULE); } - _rs = null; + resultSet = null; } - if (_ps != null) { + if (ps != null) { try { - _ps.close(); + ps.close(); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:close() preparedStatement close : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:close() preparedStatement close : manualTx=" + manualTx, MODULE); } } catch (SQLException sqle) { Debug.logWarning(sqle.getMessage(), MODULE); } - _ps = null; + ps = null; } - if ((_connection != null) && _bDeleteConnection) { + if ((connection != null) && bDeleteConnection) { try { - _connection.close(); + connection.close(); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:close() connection close : _manualTX=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:close() connection close : manualTx=" + manualTx, MODULE); } } catch (SQLException sqle) { Debug.logWarning(sqle.getMessage(), MODULE); } - _connection = null; + connection = null; } } @@ -264,34 +272,34 @@ public class SQLProcessor implements AutoCloseable { * @throws GenericEntityException */ public Connection getConnection() throws GenericDataSourceException, GenericEntityException { - if (_connection != null) { - return _connection; + if (connection != null) { + return connection; } - _manualTX = true; + manualTx = true; try { - _connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); + connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:connection() : manualTx=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:connection() : manualTx=" + manualTx, MODULE); } } catch (SQLException sqle) { throw new GenericDataSourceException("Unable to establish a connection with the database.", sqle); } // make sure we actually did get a connection - if (_connection == null) { + if (connection == null) { throw new GenericDataSourceException("Unable to establish a connection with the database. Connection was null!"); } // test the connection - testConnection(_connection); + testConnection(connection); /* causes problems w/ postgres ?? if (Debug.verboseOn()) { int isoLevel = -999; try { - isoLevel = _connection.getTransactionIsolation(); + isoLevel = connection.getTransactionIsolation(); } catch (SQLException e) { Debug.logError(e, "Problems getting the connection's isolation level", MODULE); } @@ -311,14 +319,14 @@ public class SQLProcessor implements AutoCloseable { // always try to set auto commit to false, but if we can't then later on we won't commit try { - if (_connection.getAutoCommit()) { + if (connection.getAutoCommit()) { try { - _connection.setAutoCommit(false); + connection.setAutoCommit(false); if (Debug.verboseOn()) { - Debug.logVerbose("SQLProcessor:setAutoCommit(false) : manualTx=" + _manualTX, MODULE); + Debug.logVerbose("SQLProcessor:setAutoCommit(false) : manualTx=" + manualTx, MODULE); } } catch (SQLException sqle) { - _manualTX = false; + manualTx = false; } } } catch (SQLException e) { @@ -330,7 +338,7 @@ public class SQLProcessor implements AutoCloseable { if (Debug.verboseOn()) { Debug.logVerbose("[SQLProcessor.getConnection] : active transaction", MODULE); } - _manualTX = false; + manualTx = false; } } catch (GenericTransactionException e) { // nevermind, don't worry about it, but print the exc anyway @@ -339,11 +347,11 @@ public class SQLProcessor implements AutoCloseable { } if (Debug.verboseOn()) { - Debug.logVerbose("[SQLProcessor.getConnection] : con=" + _connection, MODULE); + Debug.logVerbose("[SQLProcessor.getConnection] : con=" + connection, MODULE); } - _bDeleteConnection = true; - return _connection; + bDeleteConnection = true; + return connection; } /** @@ -364,7 +372,8 @@ public class SQLProcessor implements AutoCloseable { * @throws GenericDataSourceException * @throws GenericEntityException */ - public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency) throws GenericDataSourceException, GenericEntityException { + public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency) + throws GenericDataSourceException, GenericEntityException { this.prepareStatement(sql, specifyTypeAndConcur, resultSetType, resultSetConcurrency, -1, -1); } @@ -375,36 +384,37 @@ public class SQLProcessor implements AutoCloseable { * @throws GenericDataSourceException * @throws GenericEntityException */ - public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency, int fetchSize, int maxRows) throws GenericDataSourceException, GenericEntityException { + public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency, int fetchSize, int maxRows) + throws GenericDataSourceException, GenericEntityException { if (Debug.verboseOn()) { Debug.logVerbose("[SQLProcessor.prepareStatement] sql=" + sql, MODULE); } - if (_connection == null) { + if (connection == null) { getConnection(); } try { - _sql = sql; - _ind = 1; + sql = sql; + ind = 1; if (specifyTypeAndConcur) { - _ps = _connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + ps = connection.prepareStatement(sql, resultSetType, resultSetConcurrency); if (Debug.verboseOn()) { - Debug.logVerbose("[SQLProcessor.prepareStatement] _ps=" + _ps, MODULE); + Debug.logVerbose("[SQLProcessor.prepareStatement] ps=" + ps, MODULE); } } else { - _ps = _connection.prepareStatement(sql); + ps = connection.prepareStatement(sql); if (Debug.verboseOn()) { - Debug.logVerbose("[SQLProcessor.prepareStatement] (def) _ps=" + _ps, MODULE); + Debug.logVerbose("[SQLProcessor.prepareStatement] (def) ps=" + ps, MODULE); } } if (maxRows > 0) { - _ps.setMaxRows(maxRows); + ps.setMaxRows(maxRows); if (Debug.verboseOn()) { Debug.logVerbose("[SQLProcessor.prepareStatement] max rows set : " + maxRows, MODULE); } } - this.setFetchSize(_ps, fetchSize); + this.setFetchSize(ps, fetchSize); } catch (SQLException sqle) { throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle); } @@ -417,14 +427,14 @@ public class SQLProcessor implements AutoCloseable { */ public ResultSet executeQuery() throws GenericDataSourceException { try { - // if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeQuery] ps=" + _ps.toString(), MODULE); - _rs = _ps.executeQuery(); + // if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeQuery] ps=" + ps.toString(), MODULE); + resultSet = ps.executeQuery(); } catch (SQLException sqle) { this.checkLockWaitInfo(sqle); - throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle); + throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle); } - return _rs; + return resultSet; } /** @@ -446,13 +456,14 @@ public class SQLProcessor implements AutoCloseable { */ public int executeUpdate() throws GenericDataSourceException { try { - // if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeUpdate] ps=" + _ps.toString(), MODULE); + // if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeUpdate] ps=" + ps.toString(), MODULE); //TransactionUtil.printAllThreadsTransactionBeginStacks(); - return _ps.executeUpdate(); + return ps.executeUpdate(); } catch (SQLException sqle) { this.checkLockWaitInfo(sqle); - // don't display this here, may not be critical, allow handling further up... Debug.logError(sqle, "SQLProcessor.executeUpdate() : ERROR : ", MODULE); - throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle); + // don't display this here, may not be critical, allow handling further up... + // Debug.logError(sqle, "SQLProcessor.executeUpdate() : ERROR : ", MODULE); + throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle); } } @@ -463,11 +474,12 @@ public class SQLProcessor implements AutoCloseable { */ public int executeUpdate(String sql) throws GenericDataSourceException { - try (Statement stmt = _connection.createStatement()) { + try (Statement stmt = connection.createStatement()) { return stmt.executeUpdate(sql); } catch (SQLException sqle) { - // passing on this exception as nested, no need to log it here: Debug.logError(sqle, "SQLProcessor.executeUpdate(sql) : ERROR : ", MODULE); - throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle); + // passing on this exception as nested, no need to log it here: + // Debug.logError(sqle, "SQLProcessor.executeUpdate(sql) : ERROR : ", MODULE); + throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle); } } @@ -478,9 +490,9 @@ public class SQLProcessor implements AutoCloseable { */ public boolean next() throws GenericDataSourceException { try { - return _rs.next(); + return resultSet.next(); } catch (SQLException sqle) { - throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle); + throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle); } } @@ -489,7 +501,7 @@ public class SQLProcessor implements AutoCloseable { * @return ResultSet */ public ResultSet getResultSet() { - return _rs; + return resultSet; } /** @@ -497,7 +509,7 @@ public class SQLProcessor implements AutoCloseable { * @return PreparedStatement */ public PreparedStatement getPreparedStatement() { - return _ps; + return ps; } /** @@ -508,7 +520,7 @@ public class SQLProcessor implements AutoCloseable { * @throws GenericEntityException */ public void execQuery(String sql, ExecQueryCallbackFunctionIF aListener) throws GenericEntityException { - if (_connection == null) { + if (connection == null) { getConnection(); } @@ -522,19 +534,19 @@ public class SQLProcessor implements AutoCloseable { // each row... boolean keepGoing = true; - while (keepGoing && _rs.next()) { - keepGoing = aListener.processNextRow(_rs); + while (keepGoing && resultSet.next()) { + keepGoing = aListener.processNextRow(resultSet); } - if (_manualTX) { - _connection.commit(); + if (manualTx) { + connection.commit(); } } catch (SQLException sqle) { Debug.logWarning("[SQLProcessor.execQuery]: SQL Exception while executing the following:\n" + sql + "\nError was:", MODULE); Debug.logWarning(sqle.getMessage(), MODULE); - throw new GenericEntityException("SQL Exception while executing the following:" + _sql, sqle); + throw new GenericEntityException("SQL Exception while executing the following:" + sql, sqle); } finally { close(); } @@ -547,8 +559,8 @@ public class SQLProcessor implements AutoCloseable { * @throws SQLException */ public <T> void setValue(JdbcValueHandler<T> handler, T field) throws SQLException { - handler.setValue(_ps, _ind, field); - _ind++; + handler.setValue(ps, ind, field); + ind++; } /** @@ -558,31 +570,31 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(String field) throws SQLException { //ResultSetMetaData rsmd = this.getResultSetMetaData(); - //this doesn't seem to work, query not yet parsed: int colType = rsmd.getColumnType(_ind); + //this doesn't seem to work, query not yet parsed: int colType = rsmd.getColumnType(ind); if (field != null) { //if (field.length() > 4000) { //Clob clb = new Cl - // doesn't work with Oracle drivers, need the funky work-around: _ps.setCharacterStream(_ind, new StringReader(field), field.length()); - //_needClobWorkAroundWrite.put(Integer.valueOf(_ind), field); - //_ps.setString(_ind, " "); + // doesn't work with Oracle drivers, need the funky work-around: ps.setCharacterStream(ind, new StringReader(field), field.length()); + //_needClobWorkAroundWrite.put(Integer.valueOf(ind), field); + //ps.setString(ind, " "); //} else { - _ps.setString(_ind, field); + ps.setString(ind, field); //} } else { // silly workaround for Derby (Cloudscape 10 beta Bug #5928) // this should be removed after the know bug is fixed try { - _ps.setNull(_ind, Types.VARCHAR); + ps.setNull(ind, Types.VARCHAR); } catch (SQLException e) { try { - _ps.setString(_ind, null); + ps.setString(ind, null); } catch (SQLException e2) { Debug.logError(e2, MODULE); throw e; } } } - _ind++; + ind++; } /** @@ -592,11 +604,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(java.sql.Timestamp field) throws SQLException { if (field != null) { - _ps.setTimestamp(_ind, field); + ps.setTimestamp(ind, field); } else { - _ps.setNull(_ind, Types.TIMESTAMP); + ps.setNull(ind, Types.TIMESTAMP); } - _ind++; + ind++; } /** @@ -606,11 +618,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(java.sql.Time field) throws SQLException { if (field != null) { - _ps.setTime(_ind, field); + ps.setTime(ind, field); } else { - _ps.setNull(_ind, Types.TIME); + ps.setNull(ind, Types.TIME); } - _ind++; + ind++; } /** @@ -620,11 +632,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(java.sql.Date field) throws SQLException { if (field != null) { - _ps.setDate(_ind, field); + ps.setDate(ind, field); } else { - _ps.setNull(_ind, Types.DATE); + ps.setNull(ind, Types.DATE); } - _ind++; + ind++; } /** @@ -634,11 +646,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Integer field) throws SQLException { if (field != null) { - _ps.setInt(_ind, field); + ps.setInt(ind, field); } else { - _ps.setNull(_ind, Types.NUMERIC); + ps.setNull(ind, Types.NUMERIC); } - _ind++; + ind++; } /** @@ -648,11 +660,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Long field) throws SQLException { if (field != null) { - _ps.setLong(_ind, field); + ps.setLong(ind, field); } else { - _ps.setNull(_ind, Types.NUMERIC); + ps.setNull(ind, Types.NUMERIC); } - _ind++; + ind++; } /** @@ -662,11 +674,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Float field) throws SQLException { if (field != null) { - _ps.setFloat(_ind, field); + ps.setFloat(ind, field); } else { - _ps.setNull(_ind, Types.NUMERIC); + ps.setNull(ind, Types.NUMERIC); } - _ind++; + ind++; } /** @@ -676,11 +688,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Double field) throws SQLException { if (field != null) { - _ps.setDouble(_ind, field); + ps.setDouble(ind, field); } else { - _ps.setNull(_ind, Types.NUMERIC); + ps.setNull(ind, Types.NUMERIC); } - _ind++; + ind++; } /** @@ -690,11 +702,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(BigDecimal field) throws SQLException { if (field != null) { - _ps.setBigDecimal(_ind, field); + ps.setBigDecimal(ind, field); } else { - _ps.setNull(_ind, Types.NUMERIC); + ps.setNull(ind, Types.NUMERIC); } - _ind++; + ind++; } /** @@ -704,11 +716,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Boolean field) throws SQLException { if (field != null) { - _ps.setBoolean(_ind, field); + ps.setBoolean(ind, field); } else { - _ps.setNull(_ind, Types.BOOLEAN); + ps.setNull(ind, Types.BOOLEAN); } - _ind++; + ind++; } /** @@ -718,11 +730,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Object field) throws SQLException { if (field != null) { - _ps.setObject(_ind, field, Types.JAVA_OBJECT); + ps.setObject(ind, field, Types.JAVA_OBJECT); } else { - _ps.setNull(_ind, Types.JAVA_OBJECT); + ps.setNull(ind, Types.JAVA_OBJECT); } - _ind++; + ind++; } /** @@ -732,16 +744,16 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Blob field) throws SQLException { if (field != null) { - _ps.setBlob(_ind, field); + ps.setBlob(ind, field); } else { Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName()); if (datasourceInfo.getUseBinaryTypeForBlob()) { - _ps.setNull(_ind, Types.BINARY); + ps.setNull(ind, Types.BINARY); } else { - _ps.setNull(_ind, Types.BLOB); + ps.setNull(ind, Types.BLOB); } } - _ind++; + ind++; } /** @@ -751,11 +763,11 @@ public class SQLProcessor implements AutoCloseable { */ public void setValue(Clob field) throws SQLException { if (field != null) { - _ps.setClob(_ind, field); + ps.setClob(ind, field); } else { - _ps.setNull(_ind, Types.CLOB); + ps.setNull(ind, Types.CLOB); } - _ind++; + ind++; } /** @@ -775,7 +787,7 @@ public class SQLProcessor implements AutoCloseable { byte[] buf = os.toByteArray(); os.close(); ByteArrayInputStream is = new ByteArrayInputStream(buf); - _ps.setBinaryStream(_ind, is, buf.length); + ps.setBinaryStream(ind, is, buf.length); is.close(); } catch (IOException ex) { throw new SQLException(ex.getMessage()); @@ -783,13 +795,13 @@ public class SQLProcessor implements AutoCloseable { } else { Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName()); if (datasourceInfo.getUseBinaryTypeForBlob()) { - _ps.setNull(_ind, Types.BINARY); + ps.setNull(ind, Types.BINARY); } else { - _ps.setNull(_ind, Types.BLOB); + ps.setNull(ind, Types.BLOB); } } - _ind++; + ind++; } /** @@ -800,18 +812,23 @@ public class SQLProcessor implements AutoCloseable { */ public void setBytes(byte[] bytes) throws SQLException { if (bytes != null) { - _ps.setBytes(_ind, bytes); + ps.setBytes(ind, bytes); } else { Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName()); if (datasourceInfo.getUseBinaryTypeForBlob()) { - _ps.setNull(_ind, Types.BINARY); + ps.setNull(ind, Types.BINARY); } else { - _ps.setNull(_ind, Types.BLOB); + ps.setNull(ind, Types.BLOB); } } - _ind++; + ind++; } + /** + * Test connection. + * @param con the con + * @throws GenericEntityException the generic entity exception + */ protected void testConnection(Connection con) throws GenericEntityException { if (SQLProcessor.ENABLE_TEST) { if (SQLProcessor.CONNECTION_TEST_LIST.contains(con.toString())) { @@ -824,9 +841,15 @@ public class SQLProcessor implements AutoCloseable { } } + /** + * Sets fetch size. + * @param stmt the stmt + * @param fetchSize the fetch size + * @throws SQLException the sql exception + */ protected void setFetchSize(Statement stmt, int fetchSize) throws SQLException { // do not set fetch size when using the cursor connection - if (_connection instanceof CursorConnection) return; + if (connection instanceof CursorConnection) return; // check if the statement was called with a specific fetch size, if not grab the default from the datasource if (fetchSize < 0) { @@ -851,7 +874,8 @@ public class SQLProcessor implements AutoCloseable { // the string for Derby is "A lock could not be obtained within the time requested" // the string for MySQL is "Lock wait timeout exceeded; try restarting transaction" if (eMsg.indexOf("A lock could not be obtained within the time requested") >= 0 || eMsg.indexOf("Lock wait timeout exceeded") >= 0) { - Debug.logWarning(sqle, "Lock wait timeout error found in thread [" + Thread.currentThread().getId() + "]: (" + eMsg + ") when executing the SQL [" + _sql + "]", MODULE); + Debug.logWarning(sqle, "Lock wait timeout error found in thread [" + Thread.currentThread().getId() + "]: (" + eMsg + + ") when executing the SQL [" + sql + "]", MODULE); TransactionUtil.printAllThreadsTransactionBeginStacks(); } } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntityChecker.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntityChecker.java index 2a306da..8761d73 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntityChecker.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntityChecker.java @@ -35,7 +35,6 @@ import org.apache.ofbiz.entity.GenericEntityException; /** * Generic Entity - Entity Definition Checker - * */ public class ModelEntityChecker { @@ -46,10 +45,10 @@ public class ModelEntityChecker { Set<String> reservedWords = new HashSet<>(); if (Debug.infoOn()) { - Debug.logInfo("[initReservedWords] array length = " + rwArray.length, MODULE); + Debug.logInfo("[initReservedWords] array length = " + RW_ARRAY.length, MODULE); } - for (int i = 0; i < rwArray.length; i++) { - reservedWords.add(rwArray[i]); + for (int i = 0; i < RW_ARRAY.length; i++) { + reservedWords.add(RW_ARRAY[i]); } Map<String, Set<String>> packages = new HashMap<>(); @@ -64,8 +63,9 @@ public class ModelEntityChecker { //make sure the table name is in the list of all table names, if // not null - if (UtilValidate.isNotEmpty(ent.getPlainTableName())) - tableNames.add(ent.getPlainTableName()); + if (UtilValidate.isNotEmpty(ent.getPlainTableName())) { + tableNames.add(ent.getPlainTableName()); + } Set<String> entities = packages.get(ent.getPackageName()); if (entities == null) { @@ -88,16 +88,19 @@ public class ModelEntityChecker { if (helperName == null) { //only show group name warning if helper name not found if (UtilValidate.isEmpty(groupName)) { - warningList.add("[GroupNotFound] No Group Name found for entity " + entity.getEntityName() + "."); + warningList.add("[GroupNotFound] No Group Name found for entity " + entity.getEntityName() + "."); } else { - warningList.add("[HelperNotFound] No Helper (DataSource) definition found for entity [" + entity.getEntityName() + "] because there is no helper (datasource) configured for the entity group it is in: [" + groupName + "]"); + warningList.add("[HelperNotFound] No Helper (DataSource) definition found for entity [" + entity.getEntityName() + + "] because there is no helper (datasource) configured for the entity group it is in: [" + groupName + "]"); } } if (entity.getPlainTableName() != null && entity.getPlainTableName().length() > 30) { - warningList.add("[TableNameGT30] Table name [" + entity.getPlainTableName() + "] of entity " + entity.getEntityName() + " is longer than 30 characters."); + warningList.add("[TableNameGT30] Table name [" + entity.getPlainTableName() + "] of entity " + entity.getEntityName() + + " is longer than 30 characters."); } if (entity.getPlainTableName() != null && reservedWords.contains(entity.getPlainTableName().toUpperCase(Locale.getDefault()))) { - warningList.add("[TableNameRW] Table name [" + entity.getPlainTableName() + "] of entity " + entity.getEntityName() + " is a reserved word."); + warningList.add("[TableNameRW] Table name [" + entity.getPlainTableName() + "] of entity " + entity.getEntityName() + + " is a reserved word."); } // don't check columns/relations/keys when never-check is set to "true" @@ -112,21 +115,27 @@ public class ModelEntityChecker { ModelFieldType type = delegator.getEntityFieldType(entity, field.getType()); if (ufields.contains(field.getName())) { - warningList.add("[FieldNotUnique] Field [" + field.getName() + " of entity " + entity.getEntityName() + " is not unique for that entity."); + warningList.add("[FieldNotUnique] Field [" + field.getName() + " of entity " + entity.getEntityName() + + " is not unique for that entity."); } else { ufields.add(field.getName()); } if (field.getColName().length() > 30 && !(entity instanceof ModelViewEntity)) { - warningList.add("[FieldNameGT30] Column name [" + field.getColName() + "] of entity " + entity.getEntityName() + " is longer than 30 characters."); + warningList.add("[FieldNameGT30] Column name [" + field.getColName() + "] of entity " + entity.getEntityName() + + " is longer than 30 characters."); } if (field.getColName().length() == 0) { - warningList.add("[FieldNameEQ0] Column name for field name \"" + field.getName() + "\" of entity " + entity.getEntityName() + " is empty (zero length)."); + warningList.add("[FieldNameEQ0] Column name for field name \"" + field.getName() + "\" of entity " + entity.getEntityName() + + " is empty (zero length)."); + } + if (reservedWords.contains(field.getColName().toUpperCase(Locale.getDefault()))) { + warningList.add("[FieldNameRW] Column name " + field.getColName() + " of entity " + entity.getEntityName() + + " is a reserved word."); } - if (reservedWords.contains(field.getColName().toUpperCase(Locale.getDefault()))) - warningList.add("[FieldNameRW] Column name " + field.getColName() + " of entity " + entity.getEntityName() + " is a reserved word."); if (type == null) { StringBuilder warningMsg = new StringBuilder(); - warningMsg.append("[FieldTypeNotFound] Field type " + field.getType() + " of entity " + entity.getEntityName() + " not found in field type definitions"); + warningMsg.append("[FieldTypeNotFound] Field type " + field.getType() + " of entity " + entity.getEntityName() + + " not found in field type definitions"); if (helperName == null) { warningMsg.append(" (no helper definition found)"); } @@ -178,14 +187,14 @@ public class ModelEntityChecker { } if (relations.contains(relation.getTitle() + relation.getRelEntityName())) { warningList.add("[RelationNameNotUnique] Relation " + relation.getTitle() + relation.getRelEntityName() - + " of entity "+ entity.getEntityName() + " is not unique for that entity."); + + " of entity " + entity.getEntityName() + " is not unique for that entity."); } else { relations.add(relation.getTitle() + relation.getRelEntityName()); } if (relation.getFkName().length() > 0) { if (fkNames.contains(relation.getFkName())) { - warningList.add("[RelationFkDuplicate] Relation to "+ relation.getRelEntityName() + warningList.add("[RelationFkDuplicate] Relation to " + relation.getRelEntityName() + " from entity " + entity.getEntityName() + " has a duplicate fk-name \"" + relation.getFkName() + "\"."); } else { @@ -206,9 +215,9 @@ public class ModelEntityChecker { // make sure all FK names are <= 18 characters if (relation.getFkName().length() > 18) { warningList.add("[RelFKNameGT18] The foreign key named " + relation.getFkName() - + " (length:" + relation.getFkName().length() - + ") was greater than 18 characters in length for relation " + relation.getTitle() + relation.getRelEntityName() - + " of entity " + entity.getEntityName() + "."); + + " (length:" + relation.getFkName().length() + + ") was greater than 18 characters in length for relation " + relation.getTitle() + relation.getRelEntityName() + + " of entity " + entity.getEntityName() + "."); } ModelEntity relatedEntity = null; @@ -221,20 +230,21 @@ public class ModelEntityChecker { //if relation is of type one, make sure keyMaps // match the PK of the relatedEntity if ("one".equals(relation.getType()) || "one-nofk".equals(relation.getType())) { - if (relatedEntity.getPksSize() != relation.getKeyMaps().size()) - warningList.add("[RelatedOneKeyMapsWrongSize] The number of primary keys (" + relatedEntity.getPksSize() - + ") of related entity " + relation.getRelEntityName() - + " does not match the number of keymaps (" + relation.getKeyMaps().size() - + ") for relation of type one \"" + relation.getTitle() + relation.getRelEntityName() - + "\" of entity " + entity.getEntityName() + "."); + if (relatedEntity.getPksSize() != relation.getKeyMaps().size()) { + warningList.add("[RelatedOneKeyMapsWrongSize] The number of primary keys (" + relatedEntity.getPksSize() + + ") of related entity " + relation.getRelEntityName() + + " does not match the number of keymaps (" + relation.getKeyMaps().size() + + ") for relation of type one \"" + relation.getTitle() + relation.getRelEntityName() + + "\" of entity " + entity.getEntityName() + "."); + } Iterator<ModelField> pksIter = relatedEntity.getPksIterator(); while (pksIter.hasNext()) { ModelField pk = pksIter.next(); if (relation.findKeyMapByRelated(pk.getName()) == null) { warningList.add("[RelationOneRelatedPrimaryKeyMissing] The primary key \"" + pk.getName() - + "\" of related entity " + relation.getRelEntityName() - + " is missing in the keymaps for relation of type one " + relation.getTitle() + relation.getRelEntityName() - + " of entity " + entity.getEntityName() + "."); + + "\" of related entity " + relation.getRelEntityName() + + " is missing in the keymaps for relation of type one " + relation.getTitle() + + relation.getRelEntityName() + " of entity " + entity.getEntityName() + "."); } } } @@ -253,14 +263,14 @@ public class ModelEntityChecker { } if (rfield == null) { warningList.add("[RelationRelatedFieldNotFound] The field \"" + keyMap.getRelFieldName() - + "\" of related entity " + relation.getRelEntityName() - + " was specified in the keymaps but is not found for relation " + relation.getTitle() + relation.getRelEntityName() - + " of entity " + entity.getEntityName() + "."); + + "\" of related entity " + relation.getRelEntityName() + + " was specified in the keymaps but is not found for relation " + relation.getTitle() + + relation.getRelEntityName() + " of entity " + entity.getEntityName() + "."); } if (field == null) { warningList.add("[RelationFieldNotFound] The field " + keyMap.getFieldName() - + " was specified in the keymaps but is not found for relation " + relation.getTitle() + relation.getRelEntityName() - + " of entity " + entity.getEntityName() + "."); + + " was specified in the keymaps but is not found for relation " + relation.getTitle() + + relation.getRelEntityName() + " of entity " + entity.getEntityName() + "."); } if (field != null && rfield != null) { //this was the old check, now more constrained @@ -272,11 +282,11 @@ public class ModelEntityChecker { // !rfield.getType().startsWith(field.getType())) // { if (!field.getType().equals(rfield.getType())) { - warningList.add("[RelationFieldTypesDifferent] The field type ("+ field.getType() - + ") of " + field.getName() + " of entity " + entity.getEntityName() - + " is not the same as field type (" + rfield.getType() + ") of " - + rfield.getName() + " of entity " + relation.getRelEntityName() + " for relation " - + relation.getTitle() + relation.getRelEntityName() + "."); + warningList.add("[RelationFieldTypesDifferent] The field type (" + field.getType() + + ") of " + field.getName() + " of entity " + entity.getEntityName() + + " is not the same as field type (" + rfield.getType() + ") of " + + rfield.getName() + " of entity " + relation.getRelEntityName() + " for relation " + + relation.getTitle() + relation.getRelEntityName() + "."); } } } @@ -286,7 +296,7 @@ public class ModelEntityChecker { } } - protected static final String[] rwArray = {"ABORT", "ABS", "ABSOLUTE", + protected static final String[] RW_ARRAY = {"ABORT", "ABS", "ABSOLUTE", "ACCEPT", "ACCES", "ACCESS", "ACS", "ACTION", "ACTIVATE", "ADD", "ADDFORM", "ADMIN", "AFTER", "AGGREGATE", "ALIAS", "ALL", "ALLOCATE", "ALTER", "ANALYZE", "AND", "ANDFILENAME", "ANY", "ANYFINISH", "APPEND", diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelFieldTypeReader.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelFieldTypeReader.java index f336d7a..1e9f601 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelFieldTypeReader.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelFieldTypeReader.java @@ -46,7 +46,7 @@ import org.w3c.dom.Element; public class ModelFieldTypeReader implements Serializable { private static final String MODULE = ModelFieldTypeReader.class.getName(); - protected static final UtilCache<String, ModelFieldTypeReader> readers = UtilCache.createUtilCache("entity.ModelFieldTypeReader", 0, 0); + protected static final UtilCache<String, ModelFieldTypeReader> READERS = UtilCache.createUtilCache("entity.ModelFieldTypeReader", 0, 0); protected static Map<String, ModelFieldType> createFieldTypeCache(Element docElement, String location) { docElement.normalize(); @@ -70,7 +70,7 @@ public class ModelFieldTypeReader implements Serializable { throw new IllegalArgumentException("Could not find a datasource/helper with the name " + helperName); } String tempModelName = datasourceInfo.getFieldTypeName(); - ModelFieldTypeReader reader = readers.get(tempModelName); + ModelFieldTypeReader reader = READERS.get(tempModelName); while (reader == null) { FieldType fieldTypeInfo = null; try { @@ -81,9 +81,11 @@ public class ModelFieldTypeReader implements Serializable { if (fieldTypeInfo == null) { throw new IllegalArgumentException("Could not find a field-type definition with name \"" + tempModelName + "\""); } - ResourceHandler fieldTypeResourceHandler = new MainResourceHandler(EntityConfig.ENTITY_ENGINE_XML_FILENAME, fieldTypeInfo.getLoader(), fieldTypeInfo.getLocation()); + ResourceHandler fieldTypeResourceHandler = new MainResourceHandler(EntityConfig.ENTITY_ENGINE_XML_FILENAME, fieldTypeInfo.getLoader(), + fieldTypeInfo.getLocation()); UtilTimer utilTimer = new UtilTimer(); - utilTimer.timerString("[ModelFieldTypeReader.getModelFieldTypeReader] Reading field types from " + fieldTypeResourceHandler.getLocation()); + utilTimer.timerString("[ModelFieldTypeReader.getModelFieldTypeReader] Reading field types from " + + fieldTypeResourceHandler.getLocation()); Document document = null; try { document = fieldTypeResourceHandler.getDocument(); @@ -92,13 +94,13 @@ public class ModelFieldTypeReader implements Serializable { throw new IllegalStateException("Error loading field type file " + fieldTypeResourceHandler.getLocation()); } Map<String, ModelFieldType> fieldTypeMap = createFieldTypeCache(document.getDocumentElement(), fieldTypeResourceHandler.getLocation()); - reader = readers.putIfAbsentAndGet(tempModelName, new ModelFieldTypeReader(fieldTypeMap)); + reader = READERS.putIfAbsentAndGet(tempModelName, new ModelFieldTypeReader(fieldTypeMap)); utilTimer.timerString("[ModelFieldTypeReader.getModelFieldTypeReader] Read " + fieldTypeMap.size() + " field types"); } return reader; } - protected final Map<String, ModelFieldType> fieldTypeCache; + private final Map<String, ModelFieldType> fieldTypeCache; public ModelFieldTypeReader(Map<String, ModelFieldType> fieldTypeMap) { this.fieldTypeCache = fieldTypeMap; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java index cf1bc9f..b8ed191 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java @@ -35,7 +35,7 @@ import org.apache.ofbiz.entity.model.ModelViewEntity.ModelAlias; public final class ModelUtil { private static final String MODULE = ModelUtil.class.getName(); - private static final String vowelBag = "aeiouyAEIOUY"; + private static final String VOWEL_BAG = "aeiouyAEIOUY"; private ModelUtil() { } @@ -145,7 +145,8 @@ public final class ModelUtil { return dbName.toString(); } - /** Start by removing all vowels, then pull 1 letter at a time off the end of each _ separated segment, go until it is less than or equal to the desired length + /** Start by removing all vowels, then pull 1 letter at a time off the end of each _ separated segment, go until it is less + * than or equal to the desired length * @param dbName * @param desiredLength * @return shortened String @@ -161,7 +162,7 @@ public final class ModelUtil { } char curChar = dbBuf.charAt(i); - if (vowelBag.indexOf(curChar) > 0) { + if (VOWEL_BAG.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } @@ -270,7 +271,8 @@ public final class ModelUtil { public static String induceFieldType(String sqlTypeName, int length, int precision, ModelFieldTypeReader fieldTypeReader) { if (sqlTypeName == null) return "invalid"; - if ("VARCHAR".equalsIgnoreCase(sqlTypeName) || "VARCHAR2".equalsIgnoreCase(sqlTypeName) || ("CHAR".equalsIgnoreCase(sqlTypeName) && length > 1)) { + if ("VARCHAR".equalsIgnoreCase(sqlTypeName) || "VARCHAR2".equalsIgnoreCase(sqlTypeName) + || ("CHAR".equalsIgnoreCase(sqlTypeName) && length > 1)) { if (length <= 10) return "very-short"; if (length <= 60) return "short-varchar"; if (length <= 255) return "long-varchar"; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelViewEntity.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelViewEntity.java index cfec11b..18f48c1 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelViewEntity.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelViewEntity.java @@ -56,25 +56,25 @@ import org.w3c.dom.NodeList; public class ModelViewEntity extends ModelEntity { private static final String MODULE = ModelViewEntity.class.getName(); - private static final Map<String, String> functionPrefixMap = new HashMap<>(); - private static final Set<String> numericFunctionsSet = new HashSet<>(); // names of functions that return a numeric type + private static final Map<String, String> FUNCTION_PREFIX_MAP = new HashMap<>(); + private static final Set<String> NUMERIC_FUNCTION_SET = new HashSet<>(); // names of functions that return a numeric type static { - functionPrefixMap.put("min", "MIN("); - functionPrefixMap.put("max", "MAX("); - functionPrefixMap.put("sum", "SUM("); - functionPrefixMap.put("avg", "AVG("); - functionPrefixMap.put("count", "COUNT("); - functionPrefixMap.put("count-distinct", "COUNT(DISTINCT "); - functionPrefixMap.put("upper", "UPPER("); - functionPrefixMap.put("lower", "LOWER("); - functionPrefixMap.put("extract-year", "EXTRACT(YEAR FROM "); - functionPrefixMap.put("extract-month", "EXTRACT(MONTH FROM "); - functionPrefixMap.put("extract-day", "EXTRACT(DAY FROM "); - numericFunctionsSet.add("count"); - numericFunctionsSet.add("count-distinct"); - numericFunctionsSet.add("extract-year"); - numericFunctionsSet.add("extract-month"); - numericFunctionsSet.add("extract-day"); + FUNCTION_PREFIX_MAP.put("min", "MIN("); + FUNCTION_PREFIX_MAP.put("max", "MAX("); + FUNCTION_PREFIX_MAP.put("sum", "SUM("); + FUNCTION_PREFIX_MAP.put("avg", "AVG("); + FUNCTION_PREFIX_MAP.put("count", "COUNT("); + FUNCTION_PREFIX_MAP.put("count-distinct", "COUNT(DISTINCT "); + FUNCTION_PREFIX_MAP.put("upper", "UPPER("); + FUNCTION_PREFIX_MAP.put("lower", "LOWER("); + FUNCTION_PREFIX_MAP.put("extract-year", "EXTRACT(YEAR FROM "); + FUNCTION_PREFIX_MAP.put("extract-month", "EXTRACT(MONTH FROM "); + FUNCTION_PREFIX_MAP.put("extract-day", "EXTRACT(DAY FROM "); + NUMERIC_FUNCTION_SET.add("count"); + NUMERIC_FUNCTION_SET.add("count-distinct"); + NUMERIC_FUNCTION_SET.add("extract-year"); + NUMERIC_FUNCTION_SET.add("extract-month"); + NUMERIC_FUNCTION_SET.add("extract-day"); } /** Contains member-entity alias name definitions: key is alias, value is ModelMemberEntity */ @@ -595,12 +595,12 @@ public class ModelViewEntity extends ModelEntity { fieldSet = alias.getFieldSet(); } } - if (numericFunctionsSet.contains(alias.function)) { + if (NUMERIC_FUNCTION_SET.contains(alias.function)) { // if we have a numeric function we have to change the type type = "numeric"; } if (UtilValidate.isNotEmpty(alias.function)) { - String prefix = functionPrefixMap.get(alias.function); + String prefix = FUNCTION_PREFIX_MAP.get(alias.function); if (prefix == null) { Debug.logWarning("[" + this.getEntityName() + "]: Specified alias function [" + alias.function + "] not valid; must be: min, max, sum, avg, count or count-distinct; using a column name with no function function", MODULE); } else { @@ -643,6 +643,9 @@ public class ModelViewEntity extends ModelEntity { return conversion; } + /** + * Populate reverse links. + */ public void populateReverseLinks() { Map<String, List<String>> containedModelFields = new HashMap<>(); Iterator<ModelAlias> it = getAliasesIterator(); @@ -715,6 +718,12 @@ public class ModelViewEntity extends ModelEntity { Debug.logVerbose(this + ":" + conversions, MODULE); } + /** + * Convert list. + * @param fromEntityName the from entity name + * @param data the data + * @return the list + */ public List<Map<String, Object>> convert(String fromEntityName, Map<String, ? extends Object> data) { ModelConversion[] conversions = this.conversions.get(fromEntityName); if (conversions == null) return null; @@ -1183,7 +1192,7 @@ public class ModelViewEntity extends ModelEntity { } if (UtilValidate.isNotEmpty(function)) { - String prefix = functionPrefixMap.get(function); + String prefix = FUNCTION_PREFIX_MAP.get(function); if (prefix == null) { Debug.logWarning("[" + modelViewEntity.getEntityName() + "]: Specified alias function [" + function + "] not valid; must be: min, max, sum, avg, count or count-distinct; using a column name with no function function", MODULE); } else { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/test/EntityTestSuite.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/test/EntityTestSuite.java index 27c29e7..bd0fc0a 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/test/EntityTestSuite.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/test/EntityTestSuite.java @@ -79,8 +79,12 @@ public class EntityTestSuite extends EntityTestCase { super(name); } - static final private int _level1max = 3; // number of TestingNode entities to create + private static final int LEVEL_1_MAX = 3; // number of TestingNode entities to create + /** + * Test models. + * @throws Exception the exception + */ public void testModels() throws Exception { ModelEntity modelEntity = delegator.getModelEntity("TestingType"); assertNotNull("TestingType entity model not null", modelEntity); @@ -95,7 +99,7 @@ public class EntityTestSuite extends EntityTestCase { assertNull("TestingType.newDesc field model is null", modelField); } - /* + /** * Tests storing values with the delegator's .create, .makeValue, and .storeAll methods */ public void testMakeValue() throws Exception { @@ -121,7 +125,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("4 TestingTypes(for make) found", 4, newlyCreatedValues.size()); } - /* + /** * Tests updating entities by doing a GenericValue .put(key, value) and .store() */ public void testUpdateValue() throws Exception { @@ -150,6 +154,10 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Retrieved value has the correct description", "New Testing Type #Update-1", testValue.getString("description")); } + /** + * Test remove value. + * @throws Exception the exception + */ public void testRemoveValue() throws Exception { // Retrieve a sample GenericValue, make sure it's correct delegator.removeByCondition("TestingType", EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, "TEST-REMOVE-%")); @@ -175,7 +183,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Finding removed value returns null", null, testValue); } - /* + /** * Tests the entity cache */ public void testEntityCache() throws Exception { @@ -293,7 +301,8 @@ public class EntityTestSuite extends EntityTestCase { assertNotNull("TestingSubtype created", testValue); // Confirm member entity appears in the view testValue = EntityQuery.use(delegator).from("TestingViewPks").where("testingTypeId", "TEST-CACHE-3").cache(true).queryOne(); - assertEquals("View retrieved from cache has the correct member description", "Testing Subtype #Cache-3", testValue.getString("subtypeDescription")); + assertEquals("View retrieved from cache has the correct member description", "Testing Subtype #Cache-3", + testValue.getString("subtypeDescription")); testValue = EntityQuery.use(delegator).from("TestingSubtype").where("testingTypeId", "TEST-CACHE-3").cache(true).queryOne(); // Modify member entity testValue = (GenericValue) testValue.clone(); @@ -301,11 +310,13 @@ public class EntityTestSuite extends EntityTestCase { testValue.store(); // Check if cached view contains the modification testValue = EntityQuery.use(delegator).from("TestingViewPks").where("testingTypeId", "TEST-CACHE-3").cache(true).queryOne(); - assertEquals("View retrieved from cache has the correct member description", "New Testing Subtype #Cache-3", testValue.getString("subtypeDescription")); + assertEquals("View retrieved from cache has the correct member description", "New Testing Subtype #Cache-3", + testValue.getString("subtypeDescription")); } - /* - * Tests XML serialization by serializing/deserializing a GenericValue + /** + * Test xml serialization. + * @throws Exception the exception */ public void testXmlSerialization() throws Exception { // Must use the default delegator because the deserialized GenericValue can't @@ -325,6 +336,12 @@ public class EntityTestSuite extends EntityTestCase { TransactionUtil.rollback(transBegin, null, null); } + /** + * Flush and recreate tree long. + * @param descriptionPrefix the description prefix + * @return the long + * @throws Exception the exception + */ protected long flushAndRecreateTree(String descriptionPrefix) throws Exception { // // The tree has a root, the root has level1max children. @@ -336,7 +353,7 @@ public class EntityTestSuite extends EntityTestCase { "primaryParentNodeId", GenericEntity.NULL_FIELD, "description", descriptionPrefix + ":0:root"); int level1; - for (level1 = 0; level1 < _level1max; level1++) { + for (level1 = 0; level1 < LEVEL_1_MAX; level1++) { String nextSeqId = delegator.getNextSeqId("TestingNode"); GenericValue v = delegator.create("TestingNode", "testingNodeId", nextSeqId, "primaryParentNodeId", root.get("testingNodeId"), @@ -346,7 +363,7 @@ public class EntityTestSuite extends EntityTestCase { return level1 + 1; } - /* + /** * Tests storing data with the delegator's .create method. Also tests .findCountByCondition and .getNextSeqId */ public void testCreateTree() throws Exception { @@ -360,7 +377,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Created/Stored Nodes", created, newlyStored); } - /* + /** * More tests of storing data with .storeAll. Also prepares data for testing view-entities (see below.) */ public void testAddMembersToTree() throws Exception { @@ -371,7 +388,8 @@ public class EntityTestSuite extends EntityTestCase { // get the level1 nodes List<GenericValue> nodeLevel1 = EntityQuery.use(delegator) .from("TestingNode") - .where(EntityCondition.makeCondition("primaryParentNodeId", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD)) + .where(EntityCondition.makeCondition("primaryParentNodeId", + EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD)) .queryList(); List<GenericValue> newValues = new LinkedList<>(); @@ -401,11 +419,23 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Created/Stored Nodes", newValues.size(), n); } + /** + * Purge testing by type id. + * @param likeTypeId the like type id + * @throws GenericEntityException the generic entity exception + */ protected void purgeTestingByTypeId(String likeTypeId) throws GenericEntityException { delegator.removeByCondition("Testing", EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, likeTypeId)); delegator.removeByCondition("TestingTest", EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, likeTypeId)); } + /** + * Create node members. + * @param typeId the type id + * @param typeDescription the type description + * @param descriptionPrefix the description prefix + * @throws GenericEntityException the generic entity exception + */ protected void createNodeMembers(String typeId, String typeDescription, String descriptionPrefix) throws GenericEntityException { delegator.removeByCondition("TestingType", EntityCondition.makeCondition("testingTypeId", EntityOperator.EQUALS, typeId)); delegator.create("TestingType", "testingTypeId", typeId, "description", typeDescription); @@ -431,7 +461,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * Tests findByCondition and tests searching on a view-entity */ public void testCountViews() throws Exception { @@ -459,15 +489,13 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Number of views should equal number of created entities in the test.", testingcount, nodeWithMembers.size()); } - /* + /** * Tests findByCondition and a find by distinct */ public void testFindDistinct() throws Exception { delegator.removeByCondition("Testing", EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, "TEST-DISTINCT-%")); - List<GenericValue> testingDistinctList = EntityQuery.use(delegator) - .from("Testing") - .where(EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, "TEST-DISTINCT-%")) - .queryList(); + List<GenericValue> testingDistinctList = EntityQuery.use(delegator).from("Testing") + .where(EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, "TEST-DISTINCT-%")).queryList(); assertEquals("No existing Testing entities for distinct", 0, testingDistinctList.size()); delegator.removeByCondition("TestingType", EntityCondition.makeCondition("testingTypeId", EntityOperator.LIKE, "TEST-DISTINCT-%")); @@ -477,10 +505,14 @@ public class EntityTestSuite extends EntityTestCase { testValue = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "TEST-DISTINCT-1").cache(true).queryOne(); assertNotNull("Found newly created type value", testValue); - delegator.create("Testing", "testingId", "TEST-DISTINCT-1", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 10L, "comments", "No-comments"); - delegator.create("Testing", "testingId", "TEST-DISTINCT-2", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 10L, "comments", "Some-comments"); - delegator.create("Testing", "testingId", "TEST-DISTINCT-3", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 9L, "comments", "No-comments"); - delegator.create("Testing", "testingId", "TEST-DISTINCT-4", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 11L, "comments", "Some-comments"); + delegator.create("Testing", "testingId", "TEST-DISTINCT-1", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 10L, + "comments", "No-comments"); + delegator.create("Testing", "testingId", "TEST-DISTINCT-2", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 10L, + "comments", "Some-comments"); + delegator.create("Testing", "testingId", "TEST-DISTINCT-3", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 9L, + "comments", "No-comments"); + delegator.create("Testing", "testingId", "TEST-DISTINCT-4", "testingTypeId", "TEST-DISTINCT-1", "testingSize", 11L, + "comments", "Some-comments"); List<GenericValue> testingSize10 = EntityQuery.use(delegator) .select("testingSize", "comments") @@ -494,7 +526,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("There should only be 1 result found by findDistinct()", 1, testingSize10.size()); } - /* + /** * Tests a findByCondition using not like */ public void testNotLike() throws Exception { @@ -511,7 +543,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * Tests foreign key integrity by trying to remove an entity which has foreign-key dependencies. Should cause an exception. */ public void testForeignKeyCreate() { @@ -535,7 +567,7 @@ public class EntityTestSuite extends EntityTestCase { Debug.logInfo(caught.toString(), MODULE); } - /* + /** * Tests foreign key integrity by trying to remove an entity which has foreign-key dependencies. Should cause an exception. */ public void testForeignKeyRemove() throws Exception { @@ -568,7 +600,7 @@ public class EntityTestSuite extends EntityTestCase { Debug.logInfo(caught.toString(), MODULE); } - /* + /** * Tests the .getRelatedOne method and removeAll for removing entities */ public void testRemoveNodeMemberAndTesting() throws Exception { @@ -603,7 +635,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("No more Testing entities", 0, values.size()); } - /* + /** * Tests the storeByCondition operation */ public void testStoreByCondition() throws Exception { @@ -618,7 +650,7 @@ public class EntityTestSuite extends EntityTestCase { assertTrue("testStoreByCondition updated nodes > 0", n > 0); } - /* + /** * Tests the .removeByCondition method for removing entities directly */ public void testRemoveByCondition() throws Exception { @@ -631,7 +663,7 @@ public class EntityTestSuite extends EntityTestCase { assertTrue("testRemoveByCondition nodes > 0", n > 0); } - /* + /** * Test the .removeByPrimaryKey by using findByCondition and then retrieving the GenericPk from a GenericValue */ public void testRemoveByPK() throws Exception { @@ -658,7 +690,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("No more TestingNode after removing the roots", 0, testingNodes.size()); } - /* + /** * Tests the .removeAll method only. */ public void testRemoveType() throws Exception { @@ -679,7 +711,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("No more TestingRemoveAll: finish", 0, values.size()); } - /* + /** * This test will create a large number of unique items and add them to the delegator at once */ public void testCreateManyAndStoreAtOnce() throws Exception { @@ -705,7 +737,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * This test will create a large number of unique items and add them to the delegator at once */ public void testCreateManyAndStoreOneAtATime() throws Exception { @@ -729,7 +761,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * This test will use the large number of unique items from above and test the EntityListIterator looping through the list */ public void testEntityListIterator() throws Exception { @@ -780,7 +812,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * This test will verify transaction rollbacks using TransactionUtil. */ public void testTransactionUtilRollback() throws Exception { @@ -792,7 +824,7 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Test that transaction rollback removes value: ", null, testValueOut); } - /* + /** * This test will verify that a transaction which takes longer than the pre-set timeout are rolled back. */ public void testTransactionUtilMoreThanTimeout() throws Exception { @@ -801,7 +833,7 @@ public class EntityTestSuite extends EntityTestCase { GenericValue testValue = delegator.makeValue("Testing", "testingId", "timeout-test"); boolean transBegin = TransactionUtil.begin(10); // timeout set to 10 seconds delegator.create(testValue); - Thread.sleep(20*1000); + Thread.sleep(20 * 1000); TransactionUtil.commit(transBegin); } catch (GenericTransactionException e) { caught = e; @@ -811,7 +843,7 @@ public class EntityTestSuite extends EntityTestCase { } } - /* + /** * This test will verify that the same transaction transaction which takes less time than timeout will be committed. */ public void testTransactionUtilLessThanTimeout() throws Exception { @@ -820,14 +852,14 @@ public class EntityTestSuite extends EntityTestCase { boolean transBegin = TransactionUtil.begin(); TransactionUtil.setTransactionTimeout(20); // now set timeout to 20 seconds delegator.create(testValue); - Thread.sleep(10*1000); + Thread.sleep(10 * 1000); TransactionUtil.commit(transBegin); } finally { delegator.removeByAnd("Testing", "testingId", "timeout-test"); } } - /* + /** * Tests field types. */ public void testFieldTypes() throws Exception { @@ -941,7 +973,7 @@ public class EntityTestSuite extends EntityTestCase { } - /* + /** * This test will verify that the LIMIT and OFFSET options can work properly. * Commented out because it makes the framework dependent on the content component */ @@ -1032,7 +1064,7 @@ public class EntityTestSuite extends EntityTestCase { } }*/ - /* + /** * Tests EntitySaxReader, verification loading data with tag create, create-update, create-replace, delete */ public void testEntitySaxReaderCreation() throws Exception { @@ -1063,6 +1095,10 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Create Testing(T2).testingDate", UtilDateTime.toTimestamp("02/01/2010 00:00:00"), t2.getTimestamp("testingDate")); } + /** + * Test entity sax reader create skip. + * @throws Exception the exception + */ public void testEntitySaxReaderCreateSkip() throws Exception { String xmlContentLoad = "<entity-engine-xml>" @@ -1086,6 +1122,10 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Create Skip Testing(T1).testingDate", UtilDateTime.toTimestamp("01/01/2010 00:00:00"), t1.getTimestamp("testingDate")); } + /** + * Test entity sax reader update. + * @throws Exception the exception + */ public void testEntitySaxReaderUpdate() throws Exception { String xmlContentLoad = "<entity-engine-xml>" @@ -1115,6 +1155,10 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Update Testing(T3).testingDate", UtilDateTime.toTimestamp("03/01/2010 00:00:00"), t3.getTimestamp("testingDate")); } + /** + * Test entity sax reader replace. + * @throws Exception the exception + */ public void testEntitySaxReaderReplace() throws Exception { String xmlContentLoad = "<entity-engine-xml>" @@ -1143,6 +1187,10 @@ public class EntityTestSuite extends EntityTestCase { assertEquals("Replace Testing(T2).testingDate", UtilDateTime.toTimestamp("02/01/2010 00:00:00"), t2.getTimestamp("testingDate")); } + /** + * Test entity sax reader delete. + * @throws Exception the exception + */ public void testEntitySaxReaderDelete() throws Exception { String xmlContentLoad = "<delete>" @@ -1167,6 +1215,9 @@ public class EntityTestSuite extends EntityTestCase { assertNull("Delete TestingType 2", testType); } + /** + * Test sequence value item. + */ public void testSequenceValueItem() { SequenceUtil sequencer = new SequenceUtil(delegator.getGroupHelperInfo(delegator.getEntityGroupName("SequenceValueItem")), delegator.getModelEntity("SequenceValueItem"), @@ -1182,6 +1233,9 @@ public class EntityTestSuite extends EntityTestCase { assertEquals(10020, seqId.longValue()); } + /** + * Test sequence value item with concurrent threads. + */ public void testSequenceValueItemWithConcurrentThreads() { final SequenceUtil sequencer = new SequenceUtil(delegator.getGroupHelperInfo(delegator.getEntityGroupName("SequenceValueItem")), delegator.getModelEntity("SequenceValueItem"), @@ -1223,7 +1277,7 @@ public class EntityTestSuite extends EntityTestCase { assertFalse("Duplicate sequence id returned", duplicateFound.get()); } - /* + /** This test is useful to confirm that the default setting of use-transaction="true" for screen definitions is the best one for performance. With this setting one database transaction is started by the framework before rendering the screen. @@ -1257,7 +1311,8 @@ public class EntityTestSuite extends EntityTestCase { } long endTime = System.currentTimeMillis(); long totalTimeOneTransaction = endTime - startTime; - Debug.logInfo("Selected " + totalNumberOfRows + " rows with " + numberOfQueries + " queries (all contained in one big transaction) in " + totalTimeOneTransaction + " ms", MODULE); + Debug.logInfo("Selected " + totalNumberOfRows + " rows with " + numberOfQueries + " queries (all contained in one big transaction) in " + + totalTimeOneTransaction + " ms", MODULE); assertTrue("Errors detected executing the big transaction", noErrors); totalNumberOfRows = 0; @@ -1279,7 +1334,8 @@ public class EntityTestSuite extends EntityTestCase { } endTime = System.currentTimeMillis(); long totalTimeSeveralSmallTransactions = endTime - startTime; - Debug.logInfo("Selected " + totalNumberOfRows + " rows with " + numberOfQueries + " queries (each in its own transaction) in " + totalTimeSeveralSmallTransactions + " ms", MODULE); + Debug.logInfo("Selected " + totalNumberOfRows + " rows with " + numberOfQueries + " queries (each in its own transaction) in " + + totalTimeSeveralSmallTransactions + " ms", MODULE); assertTrue("Errors detected executing the small transactions", noErrors); assertTrue("One big transaction was not faster than several small ones", totalTimeOneTransaction < totalTimeSeveralSmallTransactions); } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/DebugXaResource.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/DebugXaResource.java index 5b76f51..c3a0e8b 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/DebugXaResource.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/DebugXaResource.java @@ -26,7 +26,7 @@ import org.apache.ofbiz.base.util.Debug; public class DebugXaResource extends GenericXaResource { private static final String MODULE = DebugXaResource.class.getName(); - public Exception ex = null; + private Exception ex = null; public DebugXaResource(String info) { this.ex = new Exception(info); @@ -38,7 +38,7 @@ public class DebugXaResource extends GenericXaResource { @Override public void commit(Xid xid, boolean onePhase) throws XAException { - TransactionUtil.debugResMap.remove(xid); + TransactionUtil.DEBUG_RES_MAP.remove(xid); if (Debug.verboseOn()) { Debug.logVerbose("Xid : " + xid.toString() + " cleared [commit]", MODULE); } @@ -46,7 +46,7 @@ public class DebugXaResource extends GenericXaResource { @Override public void rollback(Xid xid) throws XAException { - TransactionUtil.debugResMap.remove(xid); + TransactionUtil.DEBUG_RES_MAP.remove(xid); if (Debug.verboseOn()) { Debug.logVerbose("Xid : " + xid.toString() + " cleared [rollback]", MODULE); } @@ -55,9 +55,12 @@ public class DebugXaResource extends GenericXaResource { @Override public void enlist() throws XAException { super.enlist(); - TransactionUtil.debugResMap.put(xid, this); + TransactionUtil.DEBUG_RES_MAP.put(xid, this); } + /** + * Log. + */ public void log() { Debug.logInfo("Xid : " + xid, MODULE); Debug.logInfo(ex, MODULE); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/JNDITransactionFactory.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/JNDITransactionFactory.java index de08de4..de6b907 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/JNDITransactionFactory.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/JNDITransactionFactory.java @@ -54,7 +54,7 @@ public class JNDITransactionFactory implements TransactionFactory { volatile TransactionManager transactionManager = null; volatile UserTransaction userTransaction = null; - protected static final ConcurrentHashMap<String, DataSource> dsCache = new ConcurrentHashMap<>(); + protected static final ConcurrentHashMap<String, DataSource> DS_CACHE = new ConcurrentHashMap<>(); @Override public TransactionManager getTransactionManager() { @@ -144,7 +144,6 @@ public class JNDITransactionFactory implements TransactionFactory { if (con != null) { return TransactionUtil.getCursorConnection(helperInfo, con); } - } else { } if (datasourceInfo.getInlineJdbc() != null) { @@ -156,7 +155,7 @@ public class JNDITransactionFactory implements TransactionFactory { } public static Connection getJndiConnection(String jndiName, String jndiServerName) throws SQLException, GenericEntityException { - DataSource ds = dsCache.get(jndiName); + DataSource ds = DS_CACHE.get(jndiName); if (ds != null) { if (ds instanceof XADataSource) { XADataSource xads = (XADataSource) ds; @@ -179,10 +178,10 @@ public class JNDITransactionFactory implements TransactionFactory { if (ds != null) { if (Debug.verboseOn()) { - Debug.logVerbose("Got a Datasource object.", MODULE); + Debug.logVerbose("Got a Datasource object.", MODULE); } - dsCache.putIfAbsent(jndiName, ds); - ds = dsCache.get(jndiName); + DS_CACHE.putIfAbsent(jndiName, ds); + ds = DS_CACHE.get(jndiName); Connection con; if (ds instanceof XADataSource) { @@ -204,7 +203,8 @@ public class JNDITransactionFactory implements TransactionFactory { } Debug.logError("Datasource returned was NULL.", MODULE); } catch (NamingException ne) { - Debug.logWarning(ne, "Failed to find DataSource named " + jndiName + " in JNDI server with name " + jndiServerName + ". Trying normal database.", MODULE); + Debug.logWarning(ne, "Failed to find DataSource named " + jndiName + " in JNDI server with name " + + jndiServerName + ". Trying normal database.", MODULE); } catch (GenericConfigException gce) { throw new GenericEntityException("Problems with the JNDI configuration.", gce.getNested()); } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionFactoryLoader.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionFactoryLoader.java index 91afb75..af1b675 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionFactoryLoader.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionFactoryLoader.java @@ -28,7 +28,7 @@ import org.apache.ofbiz.entity.config.model.EntityConfig; public class TransactionFactoryLoader { private static final String MODULE = TransactionFactoryLoader.class.getName(); - private static final TransactionFactory txFactory = createTransactionFactory(); + private static final TransactionFactory TX_FACTORY = createTransactionFactory(); private static TransactionFactory createTransactionFactory() { TransactionFactory instance = null; @@ -51,9 +51,9 @@ public class TransactionFactoryLoader { } public static TransactionFactory getInstance() { - if (txFactory == null) { + if (TX_FACTORY == null) { throw new IllegalStateException("The Transaction Factory is not initialized."); } - return txFactory; + return TX_FACTORY; } } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionUtil.java index 9df54c4..2e422dc 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/transaction/TransactionUtil.java @@ -72,8 +72,8 @@ public final class TransactionUtil implements Status { private static ThreadLocal<Timestamp> transactionStartStamp = new ThreadLocal<>(); private static ThreadLocal<Timestamp> transactionLastNowStamp = new ThreadLocal<>(); - private static final boolean debugResources = readDebugResources(); - public static final Map<Xid, DebugXaResource> debugResMap = Collections.<Xid, DebugXaResource>synchronizedMap(new HashMap<Xid, DebugXaResource>()); + private static final boolean DEBUG_RESOURCES = readDebugResources(); + public static final Map<Xid, DebugXaResource> DEBUG_RES_MAP = Collections.<Xid, DebugXaResource>synchronizedMap(new HashMap<Xid, DebugXaResource>()); // in order to improve performance allThreadsTransactionBeginStack and allThreadsTransactionBeginStackSave are only maintained when logging level INFO is on private static Map<Long, Exception> allThreadsTransactionBeginStack = Collections.<Long, Exception>synchronizedMap(new HashMap<>()); private static Map<Long, List<Exception>> allThreadsTransactionBeginStackSave = Collections.<Long, List<Exception>>synchronizedMap(new HashMap<>()); @@ -525,13 +525,13 @@ public final class TransactionUtil implements Status { } public static boolean debugResources() { - return debugResources; + return DEBUG_RESOURCES; } public static void logRunningTx() { if (debugResources()) { - if (UtilValidate.isNotEmpty(debugResMap)) { - for (DebugXaResource dxa: debugResMap.values()) { + if (UtilValidate.isNotEmpty(DEBUG_RES_MAP)) { + for (DebugXaResource dxa: DEBUG_RES_MAP.values()) { dxa.log(); } } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityCrypto.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityCrypto.java index 2bf0557..c353fa4 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityCrypto.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityCrypto.java @@ -62,8 +62,8 @@ public final class EntityCrypto { handlers = new StorageHandler[] { new ShiroStorageHandler(kek), new SaltedBase64StorageHandler(kek), - NormalHashStorageHandler, - OldFunnyHashStorageHandler, + NORMAL_HASH_STORAGE_HANDLER, + OLD_FUNNY_HASH_STORAGE_HANDLER, }; } @@ -325,7 +325,7 @@ public final class EntityCrypto { } } - protected static final StorageHandler OldFunnyHashStorageHandler = new LegacyStorageHandler() { + protected static final StorageHandler OLD_FUNNY_HASH_STORAGE_HANDLER = new LegacyStorageHandler() { @Override protected String getHashedKeyName(String originalKeyName) { return HashCrypt.digestHashOldFunnyHex(null, originalKeyName); @@ -337,7 +337,7 @@ public final class EntityCrypto { } }; - protected static final StorageHandler NormalHashStorageHandler = new LegacyStorageHandler() { + protected static final StorageHandler NORMAL_HASH_STORAGE_HANDLER = new LegacyStorageHandler() { @Override protected String getHashedKeyName(String originalKeyName) { return HashCrypt.digestHash("SHA", originalKeyName.getBytes()); diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMapProcessor.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMapProcessor.java index 053c511..ffabe7b 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMapProcessor.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMapProcessor.java @@ -37,8 +37,10 @@ import org.w3c.dom.Element; */ public class SimpleMapProcessor { - private static final UtilCache<String, Map<String, MapProcessor>> simpleMapProcessorsResourceCache = UtilCache.createUtilCache("minilang.SimpleMapProcessorsResource", 0, 0); - private static final UtilCache<URL, Map<String, MapProcessor>> simpleMapProcessorsURLCache = UtilCache.createUtilCache("minilang.SimpleMapProcessorsURL", 0, 0); + private static final UtilCache<String, Map<String, MapProcessor>> SIMPLE_MAP_PROC_RES_CACHE = + UtilCache.createUtilCache("minilang.SimpleMapProcessorsResource", 0, 0); + private static final UtilCache<URL, Map<String, MapProcessor>> SIMPLE_MAP_PROC_URL_CACHE = + UtilCache.createUtilCache("minilang.SimpleMapProcessorsURL", 0, 0); protected static Map<String, MapProcessor> getAllProcessors(URL xmlURL) throws MiniLangException { Map<String, MapProcessor> mapProcessors = new HashMap<>(); @@ -65,35 +67,38 @@ public class SimpleMapProcessor { } protected static Map<String, MapProcessor> getProcessors(String xmlResource, String name, ClassLoader loader) throws MiniLangException { - Map<String, MapProcessor> simpleMapProcessors = simpleMapProcessorsResourceCache.get(xmlResource); + Map<String, MapProcessor> simpleMapProcessors = SIMPLE_MAP_PROC_RES_CACHE.get(xmlResource); if (simpleMapProcessors == null) { URL xmlURL = null; try { xmlURL = FlexibleLocation.resolveLocation(xmlResource, loader); } catch (MalformedURLException e) { - throw new MiniLangException("Could not find SimpleMapProcessor XML document in resource: " + xmlResource + "; error was: " + e.toString(), e); + throw new MiniLangException("Could not find SimpleMapProcessor XML document in resource: " + xmlResource + "; error was: " + + e.toString(), e); } if (xmlURL == null) { throw new MiniLangException("Could not find SimpleMapProcessor XML document in resource: " + xmlResource); } - simpleMapProcessors = simpleMapProcessorsResourceCache.putIfAbsentAndGet(xmlResource, getAllProcessors(xmlURL)); + simpleMapProcessors = SIMPLE_MAP_PROC_RES_CACHE.putIfAbsentAndGet(xmlResource, getAllProcessors(xmlURL)); } return simpleMapProcessors; } protected static Map<String, MapProcessor> getProcessors(URL xmlURL, String name) throws MiniLangException { - Map<String, MapProcessor> simpleMapProcessors = simpleMapProcessorsURLCache.get(xmlURL); + Map<String, MapProcessor> simpleMapProcessors = SIMPLE_MAP_PROC_URL_CACHE.get(xmlURL); if (simpleMapProcessors == null) { - simpleMapProcessors = simpleMapProcessorsURLCache.putIfAbsentAndGet(xmlURL, getAllProcessors(xmlURL)); + simpleMapProcessors = SIMPLE_MAP_PROC_URL_CACHE.putIfAbsentAndGet(xmlURL, getAllProcessors(xmlURL)); } return simpleMapProcessors; } - public static void runSimpleMapProcessor(String xmlResource, String name, Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale) throws MiniLangException { + public static void runSimpleMapProcessor(String xmlResource, String name, Map<String, Object> inMap, Map<String, Object> results, + List<Object> messages, Locale locale) throws MiniLangException { runSimpleMapProcessor(xmlResource, name, inMap, results, messages, locale, null); } - public static void runSimpleMapProcessor(String xmlResource, String name, Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) throws MiniLangException { + public static void runSimpleMapProcessor(String xmlResource, String name, Map<String, Object> inMap, Map<String, Object> results, + List<Object> messages, Locale locale, ClassLoader loader) throws MiniLangException { if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); } @@ -106,9 +111,11 @@ public class SimpleMapProcessor { } } - public static void runSimpleMapProcessor(URL xmlURL, String name, Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) throws MiniLangException { - if (loader == null) + public static void runSimpleMapProcessor(URL xmlURL, String name, Map<String, Object> inMap, Map<String, Object> results, + List<Object> messages, Locale locale, ClassLoader loader) throws MiniLangException { + if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); + } Map<String, MapProcessor> mapProcessors = getProcessors(xmlURL, name); MapProcessor processor = mapProcessors.get(name); if (processor == null) { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMethod.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMethod.java index a9932bd..7547644 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMethod.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMethod.java @@ -84,10 +84,10 @@ public final class SimpleMethod extends MiniLangElement { private static final String ERR_RESOURCE = "MiniLangErrorUiLabels"; private static final String[] DEPRECATED_ATTRIBUTES = {"parameter-map-name", "locale-name", "delegator-name", "security-name", "dispatcher-name", "user-login-name"}; - private static final Map<String, MethodOperation.Factory<MethodOperation>> methodOperationFactories; - private static final UtilCache<String, Map<String, SimpleMethod>> simpleMethodsDirectCache = + private static final Map<String, MethodOperation.Factory<MethodOperation>> METHOD_OPER_FACTORIES; + private static final UtilCache<String, Map<String, SimpleMethod>> SIMPLE_METHOD_DIRECT_CACHE = UtilCache.createUtilCache("minilang.SimpleMethodsDirect", 0, 0); - private static final UtilCache<String, SimpleMethod> simpleMethodsResourceCache = + private static final UtilCache<String, SimpleMethod> SIMPLE_METHODS_RES_CACHE = UtilCache.createUtilCache("minilang.SimpleMethodsResource", 0, 0); static { @@ -98,7 +98,7 @@ public final class SimpleMethod extends MiniLangElement { MethodOperation.Factory<MethodOperation> factory = it.next(); mapFactories.put(factory.getName(), factory); } - methodOperationFactories = Collections.unmodifiableMap(mapFactories); + METHOD_OPER_FACTORIES = Collections.unmodifiableMap(mapFactories); } private final String defaultErrorCode; @@ -177,7 +177,8 @@ public final class SimpleMethod extends MiniLangElement { return elementModified; } - private static void compileAllSimpleMethods(Element rootElement, Map<String, SimpleMethod> simpleMethods, String location) throws MiniLangException { + private static void compileAllSimpleMethods(Element rootElement, Map<String, SimpleMethod> simpleMethods, String location) + throws MiniLangException { for (Element simpleMethodElement : UtilXml.childElementList(rootElement, "simple-method")) { SimpleMethod simpleMethod = new SimpleMethod(simpleMethodElement, location); if (simpleMethods.containsKey(simpleMethod.getMethodName())) { @@ -223,10 +224,10 @@ public final class SimpleMethod extends MiniLangElement { public static Map<String, SimpleMethod> getDirectSimpleMethods(String name, String content, String fromLocation) throws MiniLangException { Assert.notNull("name", name, "content", content); - Map<String, SimpleMethod> simpleMethods = simpleMethodsDirectCache.get(name); + Map<String, SimpleMethod> simpleMethods = SIMPLE_METHOD_DIRECT_CACHE.get(name); if (simpleMethods == null) { simpleMethods = getAllDirectSimpleMethods(name, content, fromLocation); - simpleMethods = simpleMethodsDirectCache.putIfAbsentAndGet(name, simpleMethods); + simpleMethods = SIMPLE_METHOD_DIRECT_CACHE.putIfAbsentAndGet(name, simpleMethods); } return simpleMethods; } @@ -234,30 +235,30 @@ public final class SimpleMethod extends MiniLangElement { public static SimpleMethod getSimpleMethod(String xmlResource, String methodName, ClassLoader loader) throws MiniLangException { Assert.notNull("methodName", methodName); String key = xmlResource.concat("#").concat(methodName); - SimpleMethod method = simpleMethodsResourceCache.get(key); + SimpleMethod method = SIMPLE_METHODS_RES_CACHE.get(key); if (method == null) { Map<String, SimpleMethod> simpleMethods = getSimpleMethods(xmlResource, loader); for (Map.Entry<String, SimpleMethod> entry : simpleMethods.entrySet()) { String putKey = xmlResource.concat("#").concat(entry.getKey()); - simpleMethodsResourceCache.putIfAbsent(putKey, entry.getValue()); + SIMPLE_METHODS_RES_CACHE.putIfAbsent(putKey, entry.getValue()); } } - return simpleMethodsResourceCache.get(key); + return SIMPLE_METHODS_RES_CACHE.get(key); } public static SimpleMethod getSimpleMethod(URL xmlUrl, String methodName) throws MiniLangException { Assert.notNull("methodName", methodName); String xmlResource = xmlUrl.toString(); String key = xmlResource.concat("#").concat(methodName); - SimpleMethod method = simpleMethodsResourceCache.get(key); + SimpleMethod method = SIMPLE_METHODS_RES_CACHE.get(key); if (method == null) { Map<String, SimpleMethod> simpleMethods = getAllSimpleMethods(xmlUrl); for (Map.Entry<String, SimpleMethod> entry : simpleMethods.entrySet()) { String putKey = xmlResource.concat("#").concat(entry.getKey()); - simpleMethodsResourceCache.putIfAbsent(putKey, entry.getValue()); + SIMPLE_METHODS_RES_CACHE.putIfAbsent(putKey, entry.getValue()); } } - return simpleMethodsResourceCache.get(key); + return SIMPLE_METHODS_RES_CACHE.get(key); } private static Map<String, SimpleMethod> getSimpleMethods(String xmlResource, ClassLoader loader) throws MiniLangException { @@ -297,10 +298,10 @@ public final class SimpleMethod extends MiniLangElement { for (Element curOperElem : operationElements) { String nodeName = UtilXml.getNodeNameIgnorePrefix(curOperElem); MethodOperation methodOp = null; - MethodOperation.Factory<MethodOperation> factory = methodOperationFactories.get(nodeName); + MethodOperation.Factory<MethodOperation> factory = METHOD_OPER_FACTORIES.get(nodeName); if (factory != null) { methodOp = factory.createMethodOperation(curOperElem, simpleMethod); - } else if ("else".equals(nodeName)) { + //} else if ("else".equals(nodeName)) { // don't add anything, but don't complain either, this one is handled in the individual operations } else { MiniLangValidate.handleError("Invalid element found", simpleMethod, curOperElem); diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ConditionalFactory.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ConditionalFactory.java index b0890c9..f37ec4a 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ConditionalFactory.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ConditionalFactory.java @@ -39,7 +39,7 @@ import org.w3c.dom.Element; public abstract class ConditionalFactory<C extends Conditional> { private static final String MODULE = ConditionalFactory.class.getName(); - private static final Map<String, ConditionalFactory<?>> conditionalFactories; + private static final Map<String, ConditionalFactory<?>> CONDITIONAL_FACTORIES; static { Map<String, ConditionalFactory<?>> factories = new HashMap<>(); @@ -48,12 +48,12 @@ public abstract class ConditionalFactory<C extends Conditional> { ConditionalFactory<?> factory = it.next(); factories.put(factory.getName(), factory); } - conditionalFactories = Collections.unmodifiableMap(factories); + CONDITIONAL_FACTORIES = Collections.unmodifiableMap(factories); } public static Conditional makeConditional(Element element, SimpleMethod simpleMethod) throws MiniLangException { String tagName = element.getTagName(); - ConditionalFactory<?> factory = conditionalFactories.get(tagName); + ConditionalFactory<?> factory = CONDITIONAL_FACTORIES.get(tagName); if (factory != null) { return factory.createCondition(element, simpleMethod); } else { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ValidateMethodCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ValidateMethodCondition.java index 7532827..1c7c768 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ValidateMethodCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/ValidateMethodCondition.java @@ -41,7 +41,7 @@ import org.w3c.dom.Element; public final class ValidateMethodCondition extends MethodOperation implements Conditional { private static final String MODULE = ValidateMethodCondition.class.getName(); - private static final Class<?>[] paramTypes = new Class<?>[] {String.class }; + private static final Class<?>[] PARAM_TYPES = new Class<?>[] {String.class }; private final String className; private final FlexibleMapAccessor<Object> fieldFma; @@ -90,7 +90,7 @@ public final class ValidateMethodCondition extends MethodOperation implements Co Object[] params = new Object[] {fieldVal }; try { Class<?> valClass = methodContext.getLoader().loadClass(className); - Method valMethod = valClass.getMethod(methodName, paramTypes); + Method valMethod = valClass.getMethod(methodName, PARAM_TYPES); Boolean resultBool = (Boolean) valMethod.invoke(null, params); return resultBool; } catch (Exception e) { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/test/MiniLangTests.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/test/MiniLangTests.java index 7a18c56..55b5a44 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/test/MiniLangTests.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/test/MiniLangTests.java @@ -47,8 +47,8 @@ public class MiniLangTests extends OFBizTestCase { } private MethodContext createServiceMethodContext() { - MethodContext context = new MethodContext(dispatcher.getDispatchContext(), createContext(), null); - context.setUserLogin(dispatcher.getDelegator().makeValidValue("UserLogin", UtilMisc.toMap("userLoginId", "system")), "userLogin"); + MethodContext context = new MethodContext(getDispatcher().getDispatchContext(), createContext(), null); + context.setUserLogin(getDispatcher().getDelegator().makeValidValue("UserLogin", UtilMisc.toMap("userLoginId", "system")), "userLogin"); if (traceEnabled) { context.setTraceOn(Debug.INFO); } @@ -59,6 +59,10 @@ public class MiniLangTests extends OFBizTestCase { return new SimpleMethod(UtilXml.readXmlDocument(xmlString).getDocumentElement(), MODULE); } + /** + * Test assignment operators. + * @throws Exception the exception + */ public void testAssignmentOperators() throws Exception { // <check-errors> and <add-error> tests SimpleMethod methodToTest = createSimpleMethod("<simple-method name=\"testCheckErrors\"><check-errors/></simple-method>"); @@ -67,7 +71,8 @@ public class MiniLangTests extends OFBizTestCase { assertEquals("<check-errors> success result", methodToTest.getDefaultSuccessCode(), result); List<String> messages = context.getEnv(methodToTest.getServiceErrorMessageListName()); assertNull("<check-errors> null error message list", messages); - methodToTest = createSimpleMethod("<simple-method name=\"testCheckErrors\"><add-error><fail-message message=\"This should fail\"/></add-error><check-errors/></simple-method>"); + methodToTest = createSimpleMethod("<simple-method name=\"testCheckErrors\"><add-error><fail-message message=\"This should fail\"/>" + + "</add-error><check-errors/></simple-method>"); context = createServiceMethodContext(); result = methodToTest.exec(context); assertEquals("<check-errors> error result", methodToTest.getDefaultErrorCode(), result); @@ -75,13 +80,15 @@ public class MiniLangTests extends OFBizTestCase { assertNotNull("<check-errors> error message list", messages); assertTrue("<check-errors> error message text", messages.contains("This should fail")); // <assert>, <not>, and <if-empty> tests - methodToTest = createSimpleMethod("<simple-method name=\"testAssert\"><assert><not><if-empty field=\"locale\"/></not></assert><check-errors/></simple-method>"); + methodToTest = createSimpleMethod("<simple-method name=\"testAssert\"><assert><not><if-empty field=\"locale\"/></not></assert>" + + "<check-errors/></simple-method>"); context = createServiceMethodContext(); result = methodToTest.exec(context); assertEquals("<assert> success result", methodToTest.getDefaultSuccessCode(), result); messages = context.getEnv(methodToTest.getServiceErrorMessageListName()); assertNull("<assert> null error message list", messages); - methodToTest = createSimpleMethod("<simple-method name=\"testAssert\"><assert><if-empty field=\"locale\"/></assert><check-errors/></simple-method>"); + methodToTest = createSimpleMethod("<simple-method name=\"testAssert\"><assert><if-empty field=\"locale\"/></assert><check-errors/>" + + "</simple-method>"); context = createServiceMethodContext(); result = methodToTest.exec(context); assertEquals("<assert> error result", methodToTest.getDefaultErrorCode(), result); @@ -91,6 +98,10 @@ public class MiniLangTests extends OFBizTestCase { assertTrue("<assert> error message text", errorMessage.startsWith("Assertion failed:")); } + /** + * Test field to result operation. + * @throws Exception the exception + */ public void testFieldToResultOperation() throws Exception { String simpleMethodXml = "<simple-method name=\"testFieldToResult\">" + " <set field=\"resultValue\" value=\"someResultValue\"/>" diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/SecurityFactory.java b/framework/security/src/main/java/org/apache/ofbiz/security/SecurityFactory.java index 100ccb2..65f67c0 100644 --- a/framework/security/src/main/java/org/apache/ofbiz/security/SecurityFactory.java +++ b/framework/security/src/main/java/org/apache/ofbiz/security/SecurityFactory.java @@ -50,7 +50,7 @@ public final class SecurityFactory { // The default implementation stores a Delegator reference, so we will cache by delegator name. // The goal is to remove Delegator references in the Security interface, then we can use a singleton // and eliminate the cache. - private static final UtilCache<String, Security> authorizationCache = UtilCache.createUtilCache("security.AuthorizationCache"); + private static final UtilCache<String, Security> AUTHORIZATION_CACHE = UtilCache.createUtilCache("security.AuthorizationCache"); /** * Returns a <code>Security</code> instance. The method uses Java's @@ -63,7 +63,7 @@ public final class SecurityFactory { @SuppressWarnings("deprecation") public static Security getInstance(Delegator delegator) throws SecurityConfigurationException { Assert.notNull("delegator", delegator); - Security security = authorizationCache.get(delegator.getDelegatorName()); + Security security = AUTHORIZATION_CACHE.get(delegator.getDelegatorName()); if (security == null) { Iterator<Security> iterator = ServiceLoader.load(Security.class).iterator(); if (iterator.hasNext()) { @@ -72,9 +72,10 @@ public final class SecurityFactory { security = new OFBizSecurity(); } security.setDelegator(delegator); - security = authorizationCache.putIfAbsentAndGet(delegator.getDelegatorName(), security); + security = AUTHORIZATION_CACHE.putIfAbsentAndGet(delegator.getDelegatorName(), security); if (Debug.verboseOn()) { - Debug.logVerbose("Security implementation " + security.getClass().getName() + " created for delegator " + delegator.getDelegatorName(), MODULE); + Debug.logVerbose("Security implementation " + security.getClass().getName() + " created for delegator " + + delegator.getDelegatorName(), MODULE); } } return security; @@ -96,7 +97,8 @@ public final class SecurityFactory { @Override public void clearUserData(GenericValue userLogin) { if (userLogin != null) { - delegator.getCache().remove("UserLoginSecurityGroup", EntityCondition.makeCondition("userLoginId", EntityOperator.EQUALS, userLogin.getString("userLoginId"))); + delegator.getCache().remove("UserLoginSecurityGroup", EntityCondition.makeCondition("userLoginId", EntityOperator.EQUALS, + userLogin.getString("userLoginId"))); } } @@ -104,7 +106,8 @@ public final class SecurityFactory { @Deprecated public Iterator<GenericValue> findUserLoginSecurityGroupByUserLoginId(String userLoginId) { try { - List<GenericValue> collection = EntityUtil.filterByDate(EntityQuery.use(delegator).from("UserLoginSecurityGroup").where("userLoginId", userLoginId).cache(true).queryList()); + List<GenericValue> collection = EntityUtil.filterByDate(EntityQuery.use(delegator).from("UserLoginSecurityGroup") + .where("userLoginId", userLoginId).cache(true).queryList()); return collection.iterator(); } catch (GenericEntityException e) { Debug.logWarning(e, MODULE); @@ -126,10 +129,12 @@ public final class SecurityFactory { Iterator<GenericValue> iterator = findUserLoginSecurityGroupByUserLoginId(userLogin.getString("userLoginId")); while (iterator.hasNext()) { GenericValue userLoginSecurityGroup = iterator.next(); - if (securityGroupPermissionExists(userLoginSecurityGroup.getString("groupId"), permission)) + if (securityGroupPermissionExists(userLoginSecurityGroup.getString("groupId"), permission)) { return true; - if (securityGroupPermissionExists(userLoginSecurityGroup.getString("groupId"), adminPermission)) + } + if (securityGroupPermissionExists(userLoginSecurityGroup.getString("groupId"), adminPermission)) { return true; + } } return false; @@ -264,7 +269,8 @@ public final class SecurityFactory { @Deprecated public boolean securityGroupPermissionExists(String groupId, String permission) { try { - return EntityQuery.use(delegator).from("SecurityGroupPermission").where("groupId", groupId, "permissionId", permission).cache(true).filterByDate().queryFirst() != null; + return EntityQuery.use(delegator).from("SecurityGroupPermission") + .where("groupId", groupId, "permissionId", permission).cache(true).filterByDate().queryFirst() != null; } catch (GenericEntityException e) { Debug.logWarning(e, MODULE); return false; diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/SecurityUtil.java b/framework/security/src/main/java/org/apache/ofbiz/security/SecurityUtil.java index 4e2f789..6eabff1 100644 --- a/framework/security/src/main/java/org/apache/ofbiz/security/SecurityUtil.java +++ b/framework/security/src/main/java/org/apache/ofbiz/security/SecurityUtil.java @@ -43,7 +43,7 @@ import org.apache.ofbiz.webapp.control.JWTManager; public final class SecurityUtil { private static final String MODULE = SecurityUtil.class.getName(); - private static final List<String> adminPermissions = UtilMisc.toList( + private static final List<String> ADMIN_PERMISSIONS = UtilMisc.toList( "IMPERSONATE_ADMIN", "ARTIFACT_INFO_VIEW", "SERVICE_MAINT", @@ -64,7 +64,7 @@ public final class SecurityUtil { .from("UserLoginAndPermission") .where(EntityCondition.makeCondition( EntityCondition.makeCondition("userLoginId", userLoginId), - EntityCondition.makeCondition("permissionId", EntityOperator.IN, adminPermissions))) + EntityCondition.makeCondition("permissionId", EntityOperator.IN, ADMIN_PERMISSIONS))) .filterByDate("fromDate", "thruDate", "permissionFromDate", "permissionThruDate") .queryCount() != 0; } catch (GenericEntityException e) { @@ -138,11 +138,11 @@ public final class SecurityUtil { * Return a JWToken for authenticate a userLogin with salt the token by userLoginId and currentPassword */ public static String generateJwtToAuthenticateUserLogin(Delegator delegator, String userLoginId) - throws GenericEntityException { + throws GenericEntityException { GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne(); Map<String, String> claims = UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")); return JWTManager.createJwt(delegator, claims, - userLogin.getString("userLoginId") + userLogin.getString("currentPassword"), - 1); + userLogin.getString("userLoginId") + userLogin.getString("currentPassword"), -1); } /** diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/DispatchContext.java b/framework/service/src/main/java/org/apache/ofbiz/service/DispatchContext.java index 928d091..b798e28 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/DispatchContext.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/DispatchContext.java @@ -55,7 +55,8 @@ public class DispatchContext implements Serializable { private static final String MODULE = DispatchContext.class.getName(); - private static final UtilCache<String, Map<String, ModelService>> modelServiceMapByModel = UtilCache.createUtilCache("service.ModelServiceMapByModel", 0, 0, false); + private static final UtilCache<String, Map<String, ModelService>> MODEL_SERVICE_MAP_BY_MODEL = + UtilCache.createUtilCache("service.ModelServiceMapByModel", 0, 0, false); // these four fields represent the immutable state of a DispatchContext object private final String name; @@ -155,7 +156,8 @@ public class DispatchContext implements Serializable { * @return Map contains any valid values * @throws GenericServiceException */ - public Map<String, Object> makeValidContext(String serviceName, String mode, Map<String, ? extends Object> context) throws GenericServiceException { + public Map<String, Object> makeValidContext(String serviceName, String mode, Map<String, ? extends Object> context) + throws GenericServiceException { ModelService model = getModelService(serviceName); return makeValidContext(model, mode, context); } @@ -169,7 +171,8 @@ public class DispatchContext implements Serializable { * @return Map contains any valid values * @throws GenericServiceException */ - public static Map<String, Object> makeValidContext(ModelService model, String mode, Map<String, ? extends Object> context) throws GenericServiceException { + public static Map<String, Object> makeValidContext(ModelService model, String mode, Map<String, ? extends Object> context) + throws GenericServiceException { Map<String, Object> newContext; int modeInt = 0; @@ -213,16 +216,28 @@ public class DispatchContext implements Serializable { return retVal; } + /** + * Gets all service names. + * @return the all service names + */ public Set<String> getAllServiceNames() { Set<String> serviceNames = new TreeSet<>(); - Map<String, ModelService> globalServices = modelServiceMapByModel.get(this.model); + Map<String, ModelService> globalServices = MODEL_SERVICE_MAP_BY_MODEL.get(this.model); if (globalServices != null) { serviceNames.addAll(globalServices.keySet()); } return serviceNames; } + /** + * Gets wsdl. + * @param serviceName the service name + * @param locationURI the location uri + * @return the wsdl + * @throws GenericServiceException the generic service exception + * @throws WSDLException the wsdl exception + */ public Document getWSDL(String serviceName, String locationURI) throws GenericServiceException, WSDLException { ModelService model = this.getModelService(serviceName); return model.toWSDL(locationURI); @@ -233,7 +248,7 @@ public class DispatchContext implements Serializable { } private Map<String, ModelService> getGlobalServiceMap() { - Map<String, ModelService> serviceMap = modelServiceMapByModel.get(this.model); + Map<String, ModelService> serviceMap = MODEL_SERVICE_MAP_BY_MODEL.get(this.model); if (serviceMap == null) { serviceMap = new HashMap<>(); @@ -247,7 +262,8 @@ public class DispatchContext implements Serializable { throw new RuntimeException(e.getMessage()); } for (GlobalServices globalServices : globalServicesList) { - ResourceHandler handler = new MainResourceHandler(ServiceConfigUtil.getServiceEngineXmlFileName(), globalServices.getLoader(), globalServices.getLocation()); + ResourceHandler handler = new MainResourceHandler(ServiceConfigUtil.getServiceEngineXmlFileName(), globalServices.getLoader(), + globalServices.getLocation()); futures.add(ExecutionPool.GLOBAL_FORK_JOIN.submit(createServiceReaderCallable(handler))); } @@ -261,7 +277,7 @@ public class DispatchContext implements Serializable { } } - Map<String, ModelService> cachedServiceMap = modelServiceMapByModel.putIfAbsentAndGet(this.model, serviceMap); + Map<String, ModelService> cachedServiceMap = MODEL_SERVICE_MAP_BY_MODEL.putIfAbsentAndGet(this.model, serviceMap); if (cachedServiceMap == serviceMap) { // same object: this means that the object created by this thread was actually added to the cache ServiceEcaUtil.reloadConfig(); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/LocalDispatcher.java b/framework/service/src/main/java/org/apache/ofbiz/service/LocalDispatcher.java index f04dfe2..0da848c 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/LocalDispatcher.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/LocalDispatcher.java @@ -72,8 +72,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - Map<String, Object> runSync(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + Map<String, Object> runSync(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service synchronously and IGNORE the result. @@ -95,8 +97,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runSyncIgnore(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - void runSyncIgnore(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runSyncIgnore(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runSyncIgnore(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously, passing an instance of GenericRequester that will receive the result. @@ -110,8 +114,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - void runAsync(String serviceName, GenericRequester requester, boolean persist, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist, int transactionTimeout, + boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, GenericRequester requester, boolean persist, int transactionTimeout, boolean requireNewTransaction, + Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously, passing an instance of GenericRequester that will receive the result. @@ -123,8 +129,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - void runAsync(String serviceName, GenericRequester requester, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, GenericRequester requester, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously, passing an instance of GenericRequester that will receive the result. @@ -136,8 +144,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - void runAsync(String serviceName, GenericRequester requester, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, GenericRequester requester, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously and IGNORE the result. @@ -148,8 +158,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runAsync(String serviceName, Map<String, ? extends Object> context, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - void runAsync(String serviceName, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, Map<String, ? extends Object> context, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously and IGNORE the result. This method WILL persist the job. @@ -159,7 +171,8 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void runAsync(String serviceName, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + void runAsync(String serviceName, Map<String, ? extends Object> context) throws ServiceAuthException, + ServiceValidationException, GenericServiceException; /** * Run the service asynchronously. @@ -171,8 +184,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException; - GenericResultWaiter runAsyncWait(String serviceName, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; + GenericResultWaiter runAsyncWait(String serviceName, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Run the service asynchronously. This method WILL persist the job. @@ -183,7 +198,8 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException; + GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException; /** * Register a callback listener on a specific service. @@ -207,8 +223,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void schedule(String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws GenericServiceException; - void schedule(String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, int maxRetry, Object... context) throws GenericServiceException; + void schedule(String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, + int interval, int count, long endTime, int maxRetry) throws GenericServiceException; + void schedule(String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, + int maxRetry, Object... context) throws GenericServiceException; /** * Schedule a service to run asynchronously at a specific start time. @@ -226,8 +244,10 @@ public interface LocalDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - void schedule(String jobName, String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws GenericServiceException; - void schedule(String jobName, String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, int maxRetry, Object... context) throws GenericServiceException; + void schedule(String jobName, String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, + int frequency, int interval, int count, long endTime, int maxRetry) throws GenericServiceException; + void schedule(String jobName, String poolName, String serviceName, long startTime, int frequency, int interval, int count, + long endTime, int maxRetry, Object... context) throws GenericServiceException; /** @@ -241,8 +261,10 @@ public interface LocalDispatcher { * @param endTime The time in milliseconds the service should expire * @throws GenericServiceException */ - void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime) throws GenericServiceException; - void schedule(String serviceName, long startTime, int frequency, int interval, int count, long endTime, Object... context) throws GenericServiceException; + void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, + int count, long endTime) throws GenericServiceException; + void schedule(String serviceName, long startTime, int frequency, int interval, int count, long endTime, Object... context) + throws GenericServiceException; /** * Schedule a service to run asynchronously at a specific start time. @@ -254,8 +276,10 @@ public interface LocalDispatcher { * @param count The number of times to repeat. * @throws GenericServiceException */ - void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count) throws GenericServiceException; - void schedule(String serviceName, long startTime, int frequency, int interval, int count, Object... context) throws GenericServiceException; + void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, + int count) throws GenericServiceException; + void schedule(String serviceName, long startTime, int frequency, int interval, int count, Object... context) + throws GenericServiceException; /** * Schedule a service to run asynchronously at a specific start time. @@ -267,8 +291,9 @@ public interface LocalDispatcher { * @param endTime The time in milliseconds the service should expire * @throws GenericServiceException */ - void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, long endTime) throws GenericServiceException; - void schedule(String serviceName, long startTime, int frequency, int interval, long endTime, Object... context) throws GenericServiceException; + void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, + long endTime) throws GenericServiceException; + void schedule(String serviceName, long startTime, int frequency, int interval, long endTime, Object... context)throws GenericServiceException; /** * Schedule a service to run asynchronously at a specific start time. diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceContainer.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceContainer.java index 9fcfa28..0fd234b 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceContainer.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceContainer.java @@ -38,7 +38,7 @@ import org.apache.ofbiz.service.job.JobManager; */ public class ServiceContainer implements Container { private static final String MODULE = ServiceContainer.class.getName(); - private static final ConcurrentHashMap<String, LocalDispatcher> dispatcherCache = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, LocalDispatcher> DISPATCHER_CACHE = new ConcurrentHashMap<>(); private static LocalDispatcherFactory dispatcherFactory; private String name; @@ -88,18 +88,18 @@ public class ServiceContainer implements Container { if (UtilValidate.isNotEmpty(delegator.getDelegatorTenantId())) { dispatcherName = dispatcherName.concat("#").concat(delegator.getDelegatorTenantId()); } - LocalDispatcher dispatcher = dispatcherCache.get(dispatcherName); + LocalDispatcher dispatcher = DISPATCHER_CACHE.get(dispatcherName); if (dispatcher == null) { dispatcher = dispatcherFactory.createLocalDispatcher(dispatcherName, delegator); - dispatcherCache.putIfAbsent(dispatcherName, dispatcher); - dispatcher = dispatcherCache.get(dispatcherName); + DISPATCHER_CACHE.putIfAbsent(dispatcherName, dispatcher); + dispatcher = DISPATCHER_CACHE.get(dispatcherName); Debug.logInfo("Created new dispatcher: " + dispatcherName, MODULE); } return dispatcher; } public static void deregister(String dispatcherName) { - LocalDispatcher dispatcher = dispatcherCache.get(dispatcherName); + LocalDispatcher dispatcher = DISPATCHER_CACHE.get(dispatcherName); if (dispatcher != null) { dispatcher.deregister(); } @@ -107,10 +107,10 @@ public class ServiceContainer implements Container { public static LocalDispatcher removeFromCache(String dispatcherName) { Debug.logInfo("Removing from cache dispatcher: " + dispatcherName, MODULE); - return dispatcherCache.remove(dispatcherName); + return DISPATCHER_CACHE.remove(dispatcherName); } public static Set<String> getAllDispatcherNames() { - return Collections.unmodifiableSet(dispatcherCache.keySet()); + return Collections.unmodifiableSet(DISPATCHER_CACHE.keySet()); } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceDispatcher.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceDispatcher.java index 3ba63ca..dd85ece 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceDispatcher.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceDispatcher.java @@ -103,7 +103,7 @@ public final class ServiceDispatcher { // clean up the service semaphores of same instance try { - int rn = delegator.removeByAnd("ServiceSemaphore", "lockedByInstanceId", JobManager.instanceId); + int rn = delegator.removeByAnd("ServiceSemaphore", "lockedByInstanceId", JobManager.INSTANCE_ID); if (rn > 0) { Debug.logInfo("[ServiceDispatcher.init] : Clean up " + rn + " service semaphors.", MODULE); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceUtil.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceUtil.java index 6c67ac4..708d016 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceUtil.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceUtil.java @@ -47,7 +47,7 @@ import org.apache.ofbiz.security.Security; public final class ServiceUtil { private static final String MODULE = ServiceUtil.class.getName(); - private static final String resource = "ServiceErrorUiLabels"; + private static final String RESOURCE = "ServiceErrorUiLabels"; private ServiceUtil() { } @@ -94,12 +94,15 @@ public final class ServiceUtil { return returnProblem(ModelService.RESPOND_FAIL, null, null, null, null); } - /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code, also forwards any error messages from the nestedResult */ - public static Map<String, Object> returnError(String errorMessage, List<? extends Object> errorMessageList, Map<String, ? extends Object> errorMessageMap, Map<String, ? extends Object> nestedResult) { + /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code, + * also forwards any error messages from the nestedResult */ + public static Map<String, Object> returnError(String errorMessage, List<? extends Object> errorMessageList, Map<String, ? extends Object> + errorMessageMap, Map<String, ? extends Object> nestedResult) { return returnProblem(ModelService.RESPOND_ERROR, errorMessage, errorMessageList, errorMessageMap, nestedResult); } - public static Map<String, Object> returnProblem(String returnType, String errorMessage, List<? extends Object> errorMessageList, Map<String, ? extends Object> errorMessageMap, Map<String, ? extends Object> nestedResult) { + public static Map<String, Object> returnProblem(String returnType, String errorMessage, List<? extends Object> errorMessageList, + Map<String, ? extends Object> errorMessageMap, Map<String, ? extends Object> nestedResult) { Map<String, Object> result = new HashMap<>(); result.put(ModelService.RESPONSE_MESSAGE, returnType); if (errorMessage != null) { @@ -173,10 +176,12 @@ public final class ServiceUtil { /** A small routine used all over to improve code efficiency, get the partyId and does a security check *<b>security check</b>: userLogin partyId must equal partyId, or must have [secEntity][secOperation] permission */ - public static String getPartyIdCheckSecurity(GenericValue userLogin, Security security, Map<String, ? extends Object> context, Map<String, Object> result, String secEntity, String secOperation) { + public static String getPartyIdCheckSecurity(GenericValue userLogin, Security security, Map<String, ? extends Object> context, + Map<String, Object> result, String secEntity, String secOperation) { return getPartyIdCheckSecurity(userLogin, security, context, result, secEntity, secOperation, null, null); } - public static String getPartyIdCheckSecurity(GenericValue userLogin, Security security, Map<String, ? extends Object> context, Map<String, Object> result, String secEntity, String secOperation, String adminSecEntity, String adminSecOperation) { + public static String getPartyIdCheckSecurity(GenericValue userLogin, Security security, Map<String, ? extends Object> context, + Map<String, Object> result, String secEntity, String secOperation, String adminSecEntity, String adminSecOperation) { String partyId = (String) context.get("partyId"); Locale locale = getLocale(context); if (UtilValidate.isEmpty(partyId)) { @@ -186,16 +191,17 @@ public final class ServiceUtil { // partyId might be null, so check it if (UtilValidate.isEmpty(partyId)) { result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); - String errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.party_id_missing", locale) + "."; + String errMsg = UtilProperties.getMessage(ServiceUtil.RESOURCE, "serviceUtil.party_id_missing", locale) + "."; result.put(ModelService.ERROR_MESSAGE, errMsg); return partyId; } // <b>security check</b>: userLogin partyId must equal partyId, or must have either of the two permissions if (!partyId.equals(userLogin.getString("partyId"))) { - if (!security.hasEntityPermission(secEntity, secOperation, userLogin) && !(adminSecEntity != null && adminSecOperation != null && security.hasEntityPermission(adminSecEntity, adminSecOperation, userLogin))) { + if (!security.hasEntityPermission(secEntity, secOperation, userLogin) && !(adminSecEntity != null && adminSecOperation != null + && security.hasEntityPermission(adminSecEntity, adminSecOperation, userLogin))) { result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); - String errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.no_permission_to_operation", locale) + "."; + String errMsg = UtilProperties.getMessage(ServiceUtil.RESOURCE, "serviceUtil.no_permission_to_operation", locale) + "."; result.put(ModelService.ERROR_MESSAGE, errMsg); return partyId; } @@ -223,7 +229,7 @@ public final class ServiceUtil { } public static void getMessages(HttpServletRequest request, Map<String, ? extends Object> result, String defaultMessage, - String msgPrefix, String msgSuffix, String errorPrefix, String errorSuffix, String successPrefix, String successSuffix) { + String msgPrefix, String msgSuffix, String errorPrefix, String errorSuffix, String successPrefix, String successSuffix) { String errorMessage = ServiceUtil.makeErrorMessage(result, msgPrefix, msgSuffix, errorPrefix, errorSuffix); String successMessage = ServiceUtil.makeSuccessMessage(result, msgPrefix, msgSuffix, successPrefix, successSuffix); setMessages(request, errorMessage, successMessage, defaultMessage); @@ -251,7 +257,8 @@ public final class ServiceUtil { return errorMessage.toString(); } - public static String makeErrorMessage(Map<String, ? extends Object> result, String msgPrefix, String msgSuffix, String errorPrefix, String errorSuffix) { + public static String makeErrorMessage(Map<String, ? extends Object> result, String msgPrefix, String msgSuffix, + String errorPrefix, String errorSuffix) { if (result == null) { Debug.logWarning("A null result map was passed", MODULE); return null; @@ -298,7 +305,8 @@ public final class ServiceUtil { return null; } - public static String makeSuccessMessage(Map<String, ? extends Object> result, String msgPrefix, String msgSuffix, String successPrefix, String successSuffix) { + public static String makeSuccessMessage(Map<String, ? extends Object> result, String msgPrefix, String msgSuffix, + String successPrefix, String successSuffix) { if (result == null) { return ""; } @@ -473,6 +481,6 @@ public final class ServiceUtil { } public static String getResource() { - return resource; + return RESOURCE; } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/config/ServiceConfigUtil.java b/framework/service/src/main/java/org/apache/ofbiz/service/config/ServiceConfigUtil.java index 568ccaa..99f1399 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/config/ServiceConfigUtil.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/config/ServiceConfigUtil.java @@ -46,11 +46,12 @@ import org.w3c.dom.Element; public final class ServiceConfigUtil { private static final String MODULE = ServiceConfigUtil.class.getName(); - private static final String engine = "default"; + private static final String ENGINE = "default"; private static final String SERVICE_ENGINE_XML_FILENAME = "serviceengine.xml"; - // Keep the ServiceConfig instance in a cache - so the configuration can be reloaded at run-time. There will be only one ServiceConfig instance in the cache. - private static final UtilCache<String, ServiceConfig> serviceConfigCache = UtilCache.createUtilCache("service.ServiceConfig", 0, 0, false); - private static final List<ServiceConfigListener> configListeners = new CopyOnWriteArrayList<>(); + // Keep the ServiceConfig instance in a cache - so the configuration can be reloaded at run-time. + // There will be only one ServiceConfig instance in the cache. + private static final UtilCache<String, ServiceConfig> SERVICE_CONFIG_CACHE = UtilCache.createUtilCache("service.ServiceConfig", 0, 0, false); + private static final List<ServiceConfigListener> CONFIG_LISTENERS = new CopyOnWriteArrayList<>(); private ServiceConfigUtil() { } @@ -75,13 +76,13 @@ public final class ServiceConfigUtil { * @throws GenericConfigException */ public static ServiceConfig getServiceConfig() throws GenericConfigException { - ServiceConfig instance = serviceConfigCache.get("instance"); + ServiceConfig instance = SERVICE_CONFIG_CACHE.get("instance"); if (instance == null) { Element serviceConfigElement = getXmlDocument().getDocumentElement(); instance = ServiceConfig.create(serviceConfigElement); - serviceConfigCache.putIfAbsent("instance", instance); - instance = serviceConfigCache.get("instance"); - for (ServiceConfigListener listener : configListeners) { + SERVICE_CONFIG_CACHE.putIfAbsent("instance", instance); + instance = SERVICE_CONFIG_CACHE.get("instance"); + for (ServiceConfigListener listener : CONFIG_LISTENERS) { try { listener.onServiceConfigChange(instance); } catch (Exception e) { @@ -97,7 +98,7 @@ public final class ServiceConfigUtil { * @throws GenericConfigException */ public static ServiceEngine getServiceEngine() throws GenericConfigException { - return getServiceConfig().getServiceEngine(engine); + return getServiceConfig().getServiceEngine(ENGINE); } /** @@ -128,11 +129,11 @@ public final class ServiceConfigUtil { */ public static void registerServiceConfigListener(ServiceConfigListener listener) { Assert.notNull("listener", listener); - configListeners.add(listener); + CONFIG_LISTENERS.add(listener); } public static String getEngine() { - return engine; + return ENGINE; } public static String getServiceEngineXmlFileName() { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/EntityAutoEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/EntityAutoEngine.java index b403fe0..8046c37 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/EntityAutoEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/EntityAutoEngine.java @@ -51,7 +51,7 @@ public final class EntityAutoEngine extends GenericAsyncEngine { private static final String MODULE = EntityAutoEngine.class.getName(); private static final String RESOURCE = "ServiceErrorUiLabels"; - private static final List<String> availableInvokeActionNames = UtilMisc.toList("create", "update", "delete", "expire"); + private static final List<String> AVAIL_INVOKE_ACTION_NAMES = UtilMisc.toList("create", "update", "delete", "expire"); public EntityAutoEngine(ServiceDispatcher dispatcher) { super(dispatcher); @@ -76,7 +76,7 @@ public final class EntityAutoEngine extends GenericAsyncEngine { Map<String, Object> result = ServiceUtil.returnSuccess(); // check the package and method names - if (modelService.getInvoke() == null || !availableInvokeActionNames.contains(modelService.getInvoke())) { + if (modelService.getInvoke() == null || !AVAIL_INVOKE_ACTION_NAMES.contains(modelService.getInvoke())) { throw new GenericServiceException("In Service [" + modelService.getName() + "] the invoke value must be create, update, or delete for entity-auto engine"); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/jms/JmsListenerFactory.java b/framework/service/src/main/java/org/apache/ofbiz/service/jms/JmsListenerFactory.java index 7cc9d22..a8825ab 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/jms/JmsListenerFactory.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/jms/JmsListenerFactory.java @@ -46,24 +46,24 @@ public class JmsListenerFactory implements Runnable { public static final String TOPIC_LISTENER_CLASS = "org.apache.ofbiz.service.jms.JmsTopicListener"; public static final String QUEUE_LISTENER_CLASS = "org.apache.ofbiz.service.jms.JmsQueueListener"; - protected static Map<String, GenericMessageListener> listeners = new ConcurrentHashMap<>(); - protected static Map<String, Server> servers = new ConcurrentHashMap<>(); + private static Map<String, GenericMessageListener> listeners = new ConcurrentHashMap<>(); + private static Map<String, Server> servers = new ConcurrentHashMap<>(); - private static final AtomicReference<JmsListenerFactory> jlFactoryRef = new AtomicReference<>(null); + private static final AtomicReference<JmsListenerFactory> JL_FACTORY_REF = new AtomicReference<>(null); - protected Delegator delegator; - protected boolean firstPass = true; - protected int loadable = 0; - protected int connected = 0; - protected Thread thread; + private Delegator delegator; + private boolean firstPass = true; + private int loadable = 0; + private int connected = 0; + private Thread thread; public static JmsListenerFactory getInstance(Delegator delegator) { - JmsListenerFactory instance = jlFactoryRef.get(); + JmsListenerFactory instance = JL_FACTORY_REF.get(); if (instance == null) { instance = new JmsListenerFactory(delegator); - if (!jlFactoryRef.compareAndSet(null, instance)) { - instance = jlFactoryRef.get(); + if (!JL_FACTORY_REF.compareAndSet(null, instance)) { + instance = JL_FACTORY_REF.get(); } } return instance; @@ -122,8 +122,9 @@ public class JmsListenerFactory implements Runnable { GenericMessageListener listener = loadListener(serverKey.toString(), server); // store the listener w/ the key - if (serverKey.length() > 0 && listener != null) + if (serverKey.length() > 0 && listener != null) { listeners.put(serverKey.toString(), listener); + } } } catch (GenericServiceException gse) { Debug.logInfo("Cannot load message listener " + serverKey + " error: (" + gse.toString() + ").", MODULE); @@ -147,10 +148,11 @@ public class JmsListenerFactory implements Runnable { String className = server.getListenerClass(); if (UtilValidate.isEmpty(className)) { - if ("topic".equals(type)) + if ("topic".equals(type)) { className = JmsListenerFactory.TOPIC_LISTENER_CLASS; - else if ("queue".equals(type)) + } else if ("queue".equals(type)) { className = JmsListenerFactory.QUEUE_LISTENER_CLASS; + } } GenericMessageListener listener = listeners.get(serverKey); @@ -163,15 +165,17 @@ public class JmsListenerFactory implements Runnable { try { Class<?> c = cl.loadClass(className); - Constructor<GenericMessageListener> cn = UtilGenerics.cast(c.getConstructor(Delegator.class, String.class, String.class, String.class, String.class, String.class)); + Constructor<GenericMessageListener> cn = UtilGenerics.cast(c.getConstructor(Delegator.class, + String.class, String.class, String.class, String.class, String.class)); listener = cn.newInstance(delegator, serverName, jndiName, queueName, userName, password); } catch (RuntimeException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) { throw new GenericServiceException(e.getMessage(), e); } - if (listener != null) + if (listener != null) { listeners.put(serverKey, listener); + } loadable++; } } @@ -179,8 +183,9 @@ public class JmsListenerFactory implements Runnable { } if (listener != null && !listener.isConnected()) { listener.load(); - if (listener.isConnected()) + if (listener.isConnected()) { connected++; + } } return listener; } @@ -193,8 +198,9 @@ public class JmsListenerFactory implements Runnable { public void loadListener(String serverKey) throws GenericServiceException { Server server = servers.get(serverKey); - if (server == null) + if (server == null) { throw new GenericServiceException("No listener found with that serverKey."); + } loadListener(serverKey, server); } @@ -217,8 +223,9 @@ public class JmsListenerFactory implements Runnable { public void closeListener(String serverKey) throws GenericServiceException { GenericMessageListener listener = listeners.get(serverKey); - if (listener == null) + if (listener == null) { throw new GenericServiceException("No listener found with that serverKey."); + } listener.close(); } @@ -230,8 +237,9 @@ public class JmsListenerFactory implements Runnable { public void refreshListener(String serverKey) throws GenericServiceException { GenericMessageListener listener = listeners.get(serverKey); - if (listener == null) + if (listener == null) { throw new GenericServiceException("No listener found with that serverKey."); + } listener.refresh(); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/job/JobManager.java b/framework/service/src/main/java/org/apache/ofbiz/service/job/JobManager.java index 52b07b3..3016474 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/job/JobManager.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/job/JobManager.java @@ -69,8 +69,8 @@ import org.apache.ofbiz.service.config.model.RunFromPool; public final class JobManager { private static final String MODULE = JobManager.class.getName(); - public static final String instanceId = UtilProperties.getPropertyValue("general", "unique.instanceId", "ofbiz0"); - private static final ConcurrentHashMap<String, JobManager> registeredManagers = new ConcurrentHashMap<>(); + public static final String INSTANCE_ID = UtilProperties.getPropertyValue("general", "unique.instanceId", "ofbiz0"); + private static final ConcurrentHashMap<String, JobManager> REG_MANAGERS = new ConcurrentHashMap<>(); private static boolean isShutDown = false; private static void assertIsRunning() { @@ -81,18 +81,19 @@ public final class JobManager { /** * Returns a <code>JobManager</code> instance. - * @param delegator + * @param delegator the delegator * @param enablePoller Enables polling of the JobSandbox entity. + * @return the instance * @throws IllegalStateException if the Job Manager is shut down. */ public static JobManager getInstance(Delegator delegator, boolean enablePoller) { assertIsRunning(); Assert.notNull("delegator", delegator); - JobManager jm = registeredManagers.get(delegator.getDelegatorName()); + JobManager jm = REG_MANAGERS.get(delegator.getDelegatorName()); if (jm == null) { jm = new JobManager(delegator); - registeredManagers.putIfAbsent(delegator.getDelegatorName(), jm); - jm = registeredManagers.get(delegator.getDelegatorName()); + REG_MANAGERS.putIfAbsent(delegator.getDelegatorName(), jm); + jm = REG_MANAGERS.get(delegator.getDelegatorName()); if (enablePoller) { JobPoller.registerJobManager(jm); } @@ -144,11 +145,11 @@ public final class JobManager { EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeConditionDate("fromDate", "thruDate"), EntityCondition.makeCondition(UtilMisc.toList( - EntityCondition.makeCondition("instanceId", instanceId), + EntityCondition.makeCondition("instanceId", INSTANCE_ID), EntityCondition.makeCondition("instanceId", "_NA_")), EntityJoinOperator.OR)), EntityJoinOperator.AND); return delegator.findCountByCondition("JobManagerLock", condition, null, null) == 0; } catch (GenericEntityException e) { - Debug.logWarning(e, "Exception thrown while check lock on JobManager : " + instanceId, MODULE); + Debug.logWarning(e, "Exception thrown while check lock on JobManager : " + INSTANCE_ID, MODULE); return false; } } @@ -178,7 +179,8 @@ public final class JobManager { return Collections.emptyList(); } // basic query - List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), + List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", + EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("startDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null)); @@ -215,8 +217,10 @@ public final class JobManager { GenericValue jobValue = jobsIterator.next(); while (jobValue != null) { // Claim ownership of this value. Using storeByCondition to avoid a race condition. - List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null)); - int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", instanceId), EntityCondition.makeCondition(updateExpression)); + List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, + jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null)); + int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", INSTANCE_ID), + EntityCondition.makeCondition(updateExpression)); if (rowsUpdated == 1) { poll.add(new PersistedServiceJob(dctx, jobValue, null)); if (poll.size() == limit) { @@ -250,7 +254,7 @@ public final class JobManager { return Collections.emptyList(); } List<EntityCondition> purgeCondition = UtilMisc.toList( - EntityCondition.makeCondition("runByInstanceId", instanceId), + EntityCondition.makeCondition("runByInstanceId", INSTANCE_ID), EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null), @@ -297,7 +301,8 @@ public final class JobManager { EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "SERVICE_QUEUED"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "SERVICE_RUNNING")); EntityCondition statusCondition = EntityCondition.makeCondition(statusExprList, EntityOperator.OR); - EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), statusCondition)); + EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", + INSTANCE_ID), statusCondition)); try { crashed = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("startDateTime").queryList(); } catch (GenericEntityException e) { @@ -323,7 +328,8 @@ public final class JobManager { newJob.set("startDateTime", null); newJob.set("runByInstanceId", null); - // if Queued Job is crashed then its corresponding new Job should have TempExprId and recurrenceInfoId to continue further scheduling. + // if Queued Job is crashed then its corresponding new Job should have TempExprId and + // recurrenceInfoId to continue further scheduling. if ("SERVICE_QUEUED".equals(job.getString("statusId"))) { newJob.set("tempExprId", job.getString("tempExprId")); newJob.set("recurrenceInfoId", job.getString("recurrenceInfoId")); @@ -365,81 +371,61 @@ public final class JobManager { /** * Schedule a job to start at a specific time with specific recurrence info - * @param serviceName - * The name of the service to invoke - *@param context - * The context for the service - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param count - * The number of times to repeat + * @param serviceName The name of the service to invoke + * @param context The context for the service + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param count The number of times to repeat + * @throws JobManagerException the job manager exception */ - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count) throws JobManagerException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count) + throws JobManagerException { schedule(serviceName, context, startTime, frequency, interval, count, 0); } /** * Schedule a job to start at a specific time with specific recurrence info - * @param serviceName - * The name of the service to invoke - *@param context - * The context for the service - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param count - * The number of times to repeat - *@param endTime - * The time in milliseconds the service should expire + * @param serviceName The name of the service to invoke + * @param context The context for the service + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param count The number of times to repeat + * @param endTime The time in milliseconds the service should expire + * @throws JobManagerException the job manager exception */ - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime) throws JobManagerException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, + long endTime) throws JobManagerException { schedule(null, serviceName, context, startTime, frequency, interval, count, endTime); } /** * Schedule a job to start at a specific time with specific recurrence info - * @param serviceName - * The name of the service to invoke - *@param context - * The context for the service - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param endTime - * The time in milliseconds the service should expire + * @param serviceName The name of the service to invoke + * @param context The context for the service + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param endTime The time in milliseconds the service should expire + * @throws JobManagerException the job manager exception */ - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, long endTime) throws JobManagerException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, + long endTime) throws JobManagerException { schedule(serviceName, context, startTime, frequency, interval, -1, endTime); } /** * Schedule a job to start at a specific time with specific recurrence info - * @param poolName - * The name of the pool to run the service from - *@param serviceName - * The name of the service to invoke - *@param context - * The context for the service - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param count - * The number of times to repeat - *@param endTime - * The time in milliseconds the service should expire + * @param poolName The name of the pool to run the service from + * @param serviceName The name of the service to invoke + * @param context The context for the service + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param count The number of times to repeat + * @param endTime The time in milliseconds the service should expire + * @throws JobManagerException the job manager exception */ public void schedule(String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime) throws JobManagerException { @@ -448,14 +434,11 @@ public final class JobManager { /** * Schedule a job to start at a specific time with specific recurrence info - * @param poolName - * The name of the pool to run the service from - *@param serviceName - * The name of the service to invoke - *@param dataId - * The persisted context (RuntimeData.runtimeDataId) - *@param startTime - * The time in milliseconds the service should run + * @param poolName The name of the pool to run the service from + * @param serviceName The name of the service to invoke + * @param dataId The persisted context (RuntimeData.runtimeDataId) + * @param startTime The time in milliseconds the service should run + * @throws JobManagerException the job manager exception */ public void schedule(String poolName, String serviceName, String dataId, long startTime) throws JobManagerException { schedule(null, poolName, serviceName, dataId, startTime, -1, 0, 1, 0, -1); @@ -463,26 +446,17 @@ public final class JobManager { /** * Schedule a job to start at a specific time with specific recurrence info - * @param jobName - * The name of the job - *@param poolName - * The name of the pool to run the service from - *@param serviceName - * The name of the service to invoke - *@param context - * The context for the service - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param count - * The number of times to repeat - *@param endTime - * The time in milliseconds the service should expire - *@param maxRetry - * The max number of retries on failure (-1 for no max) + * @param jobName The name of the job + * @param poolName The name of the pool to run the service from + * @param serviceName The name of the service to invoke + * @param context The context for the service + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param count The number of times to repeat + * @param endTime The time in milliseconds the service should expire + * @param maxRetry The max number of retries on failure (-1 for no max) + * @throws JobManagerException the job manager exception */ public void schedule(String jobName, String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws JobManagerException { @@ -502,27 +476,17 @@ public final class JobManager { /** * Schedule a job to start at a specific time with specific recurrence info - * @param jobName - * The name of the job - *@param poolName - * The name of the pool to run the service from - *@param serviceName - * The name of the service to invoke - *@param dataId - * The persisted context (RuntimeData.runtimeDataId) - *@param startTime - * The time in milliseconds the service should run - *@param frequency - * The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) - *@param interval - * The interval of the frequency recurrence - *@param count - * The number of times to repeat - *@param endTime - * The time in milliseconds the service should expire - *@param maxRetry - * The max number of retries on failure (-1 for no max) - * @throws IllegalStateException if the Job Manager is shut down. + * @param jobName The name of the job + * @param poolName The name of the pool to run the service from + * @param serviceName The name of the service to invoke + * @param dataId The persisted context (RuntimeData.runtimeDataId) + * @param startTime The time in milliseconds the service should run + * @param frequency The frequency of the recurrence (HOURLY, DAILY, MONTHLY etc) + * @param interval The interval of the frequency recurrence + * @param count The number of times to repeat + * @param endTime The time in milliseconds the service should expire + * @param maxRetry The max number of retries on failure (-1 for no max) + * @throws JobManagerException the job manager exception */ public void schedule(String jobName, String poolName, String serviceName, String dataId, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws JobManagerException { @@ -541,7 +505,7 @@ public final class JobManager { if (UtilValidate.isEmpty(jobName)) { jobName = Long.toString((new Date().getTime())); } - Map<String, Object> jFields = UtilMisc.<String, Object> toMap("jobName", jobName, "runTime", new java.sql.Timestamp(startTime), + Map<String, Object> jFields = UtilMisc.<String, Object>toMap("jobName", jobName, "runTime", new java.sql.Timestamp(startTime), "serviceName", serviceName, "statusId", "SERVICE_PENDING", "recurrenceInfoId", infoId, "runtimeDataId", dataId, "priority", JobPriority.NORMAL); // set the pool ID diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/job/PersistedServiceJob.java b/framework/service/src/main/java/org/apache/ofbiz/service/job/PersistedServiceJob.java index 0a1c06a..2b489a4 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/job/PersistedServiceJob.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/job/PersistedServiceJob.java @@ -99,7 +99,7 @@ public class PersistedServiceJob extends GenericServiceJob { } catch (GenericEntityException e) { throw new InvalidJobException("Unable to refresh JobSandbox value", e); } - if (!JobManager.instanceId.equals(jobValue.getString("runByInstanceId"))) { + if (!JobManager.INSTANCE_ID.equals(jobValue.getString("runByInstanceId"))) { throw new InvalidJobException("Job has been accepted by a different instance"); } Timestamp cancelTime = jobValue.getTimestamp("cancelDateTime"); @@ -127,7 +127,7 @@ public class PersistedServiceJob extends GenericServiceJob { } catch (GenericEntityException e) { throw new InvalidJobException("Unable to refresh JobSandbox value", e); } - if (!JobManager.instanceId.equals(jobValue.getString("runByInstanceId"))) { + if (!JobManager.INSTANCE_ID.equals(jobValue.getString("runByInstanceId"))) { throw new InvalidJobException("Job has been accepted by a different instance"); } if (jobValue.getTimestamp("cancelDateTime") != null) { @@ -176,7 +176,8 @@ public class PersistedServiceJob extends GenericServiceJob { if (recurrence != null) { recurrence.incrementCurrentCount(); } - TimeZone timeZone = jobValue.get("recurrenceTimeZone") != null ? TimeZone.getTimeZone(jobValue.getString("recurrenceTimeZone")) : TimeZone.getDefault(); + TimeZone timeZone = jobValue.get("recurrenceTimeZone") != null ? TimeZone.getTimeZone(jobValue.getString("recurrenceTimeZone")) + : TimeZone.getDefault(); Calendar next = expr.next(Calendar.getInstance(timeZone)); if (next != null) { @@ -187,7 +188,7 @@ public class PersistedServiceJob extends GenericServiceJob { throw new InvalidJobException(e); } if (Debug.infoOn()) { - Debug.logInfo("Job [" + getJobName() + "] Id [" + getJobId() + "] -- Next runtime: " + new Date(nextRecurrence), MODULE); + Debug.logInfo("Job [" + getJobName() + "] Id [" + getJobId() + "] -- Next runtime: " + new Date(nextRecurrence), MODULE); } } @@ -297,7 +298,8 @@ public class PersistedServiceJob extends GenericServiceJob { if (UtilValidate.isNotEmpty(jobValue.getString("runtimeDataId"))) { GenericValue contextObj = jobValue.getRelatedOne("RuntimeData", false); if (contextObj != null) { - context = UtilGenerics.checkMap(XmlSerializer.deserialize(contextObj.getString("runtimeInfo"), delegator), String.class, Object.class); + context = UtilGenerics.checkMap(XmlSerializer.deserialize(contextObj.getString("runtimeInfo"), + delegator), String.class, Object.class); } } if (context == null) { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/mail/ServiceMcaUtil.java b/framework/service/src/main/java/org/apache/ofbiz/service/mail/ServiceMcaUtil.java index 4af9640..e104d8d 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/mail/ServiceMcaUtil.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/mail/ServiceMcaUtil.java @@ -36,12 +36,12 @@ import org.w3c.dom.Element; public final class ServiceMcaUtil { private static final String MODULE = ServiceMcaUtil.class.getName(); - private static final UtilCache<String, ServiceMcaRule> mcaCache = UtilCache.createUtilCache("service.ServiceMCAs", 0, 0, false); + private static final UtilCache<String, ServiceMcaRule> MCA_CACHE = UtilCache.createUtilCache("service.ServiceMCAs", 0, 0, false); private ServiceMcaUtil() { } public static void reloadConfig() { - mcaCache.clear(); + MCA_CACHE.clear(); readConfig(); } @@ -66,7 +66,7 @@ public final class ServiceMcaUtil { int numDefs = 0; for (Element e: UtilXml.childElementList(rootElement, "mca")) { String ruleName = e.getAttribute("mail-rule-name"); - mcaCache.put(ruleName, new ServiceMcaRule(e)); + MCA_CACHE.put(ruleName, new ServiceMcaRule(e)); numDefs++; } @@ -82,10 +82,10 @@ public final class ServiceMcaUtil { } public static Collection<ServiceMcaRule> getServiceMcaRules() { - if (mcaCache.isEmpty()) { + if (MCA_CACHE.isEmpty()) { readConfig(); } - return mcaCache.values(); + return MCA_CACHE.values(); } public static void evalRules(LocalDispatcher dispatcher, MimeMessageWrapper wrapper, GenericValue userLogin) throws GenericServiceException { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/semaphore/ServiceSemaphore.java b/framework/service/src/main/java/org/apache/ofbiz/service/semaphore/ServiceSemaphore.java index ad2f400..a3a5bb4 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/semaphore/ServiceSemaphore.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/semaphore/ServiceSemaphore.java @@ -149,7 +149,7 @@ public final class ServiceSemaphore { if (EntityQuery.use(delegator).from("ServiceSemaphore") .where("serviceName", model.getName()).queryCount() == 0) { semaphore = delegator.makeValue("ServiceSemaphore", "serviceName", model.getName(), - "lockedByInstanceId", JobManager.instanceId, "lockThread", threadName, "lockTime", lockTime); + "lockedByInstanceId", JobManager.INSTANCE_ID, "lockThread", threadName, "lockTime", lockTime); // use the special method below so we can reuse the unique tx functions // if semaphore successfully owned no need to wait anymore. diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTests.java b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTests.java index 7257f0b..5499469 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTests.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTests.java @@ -38,8 +38,12 @@ public class ServiceEngineTests extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test basic java invocation. + * @throws Exception the exception + */ public void testBasicJavaInvocation() throws Exception { - Map<String, Object> result = dispatcher.runSync("testScv", UtilMisc.toMap("message", "Unit Test")); + Map<String, Object> result = getDispatcher().runSync("testScv", UtilMisc.toMap("message", "Unit Test")); assertEquals("Service result success", ModelService.RESPOND_SUCCESS, result.get(ModelService.RESPONSE_MESSAGE)); } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEntityAutoTests.java b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEntityAutoTests.java index a13f96c..c46cc7c 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEntityAutoTests.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEntityAutoTests.java @@ -29,6 +29,7 @@ import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.service.GenericServiceException; +import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ServiceUtil; import org.apache.ofbiz.service.testtools.OFBizTestCase; @@ -37,6 +38,7 @@ public class ServiceEntityAutoTests extends OFBizTestCase { public ServiceEntityAutoTests(String name) { super(name); } + private final LocalDispatcher dispatcher = getDispatcher(); @Override protected void setUp() throws Exception { @@ -46,6 +48,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test entity auto create singl pk entity. + * @throws Exception the exception + */ public void testEntityAutoCreateSinglPkEntity() throws Exception { //test create with given pk Map<String, Object> testingPkPresentMap = new HashMap<>(); @@ -69,6 +75,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { assertTrue(ServiceUtil.isError(results)); } + /** + * Test entity auto create double pk entity. + * @throws Exception the exception + */ public void testEntityAutoCreateDoublePkEntity() throws Exception { delegator.create("Testing", "testingId", "TESTING_2"); @@ -99,6 +109,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { //assertEquals("", ServiceUtil.getErrorMessage(results)); } + /** + * Test entity auto create multi pk entity. + * @throws Exception the exception + */ public void testEntityAutoCreateMultiPkEntity() throws Exception { delegator.create("TestingNode", "testingNodeId", "NODE_1"); delegator.create("Testing", "testingId", "TESTING_3"); @@ -122,6 +136,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { assertTrue(ServiceUtil.isSuccess(results)); } + /** + * Test entity auto update entity. + * @throws Exception the exception + */ public void testEntityAutoUpdateEntity() throws Exception { delegator.create("Testing", "testingId", "TESTING_4", "testingName", "entity auto testing"); @@ -139,6 +157,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { assertEquals(UtilProperties.getMessage("ServiceErrorUiLabels", "ServiceValueNotFound", Locale.ENGLISH), ServiceUtil.getErrorMessage(results)); } + /** + * Test entity auto delete entity. + * @throws Exception the exception + */ public void testEntityAutoDeleteEntity() throws Exception { delegator.create("Testing", "testingId", "TESTING_5"); @@ -156,6 +178,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { assertEquals(UtilProperties.getMessage("ServiceErrorUiLabels", "ServiceValueNotFoundForRemove", Locale.ENGLISH), ServiceUtil.getErrorMessage(results)); } + /** + * Test entity auto expire entity. + * @throws Exception the exception + */ public void testEntityAutoExpireEntity() throws Exception { Timestamp now = UtilDateTime.nowTimestamp(); delegator.create("Testing", "testingId", "TESTING_6"); @@ -195,6 +221,10 @@ public class ServiceEntityAutoTests extends OFBizTestCase { } + /** + * Test entity auto entity status concept. + * @throws Exception the exception + */ public void testEntityAutoEntityStatusConcept() throws Exception { delegator.create("Testing", "testingId", "TESTING_7"); delegator.create("StatusType", "statusTypeId", "TESTINGSTATUS"); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServicePermissionTests.java b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServicePermissionTests.java index bdffa4c..7c214a0 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServicePermissionTests.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServicePermissionTests.java @@ -31,62 +31,90 @@ public class ServicePermissionTests extends OFBizTestCase { super(name); } + /** + * Test permission success. + * @throws Exception the exception + */ public void testPermissionSuccess() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1")); - Map<String, Object> results = dispatcher.runSync("testSimplePermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimplePermission", testingPermMap); assertTrue(ServiceUtil.isSuccess(results)); } + /** + * Test service permission success. + * @throws Exception the exception + */ public void testServicePermissionSuccess() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1"), "givePermission", "Y"); - Map<String, Object> results = dispatcher.runSync("testSimpleServicePermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleServicePermission", testingPermMap); assertTrue(ServiceUtil.isSuccess(results)); } + /** + * Test service permission error. + * @throws Exception the exception + */ public void testServicePermissionError() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1"), "givePermission", "N"); try { - Map<String, Object> results = dispatcher.runSync("testSimpleServicePermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleServicePermission", testingPermMap); assertFalse("The testGroupPermission don't raise service exception", ServiceUtil.isError(results)); } catch (ServiceAuthException e) { assertNotNull(e); } } + /** + * Test group permission success. + * @throws Exception the exception + */ public void testGroupPermissionSuccess() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1"), "givePermission", "Y"); - Map<String, Object> results = dispatcher.runSync("testSimpleGroupAndPermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleGroupAndPermission", testingPermMap); assertTrue(ServiceUtil.isSuccess(results)); testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1"), "givePermission", "N"); - results = dispatcher.runSync("testSimpleGroupOrPermission", testingPermMap); + results = getDispatcher().runSync("testSimpleGroupOrPermission", testingPermMap); assertTrue(ServiceUtil.isSuccess(results)); } + /** + * Test permission failed. + * @throws Exception the exception + */ public void testPermissionFailed() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser2")); try { - Map<String, Object> results = dispatcher.runSync("testSimplePermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimplePermission", testingPermMap); assertFalse("The service testSimplePermission don't raise service exception", ServiceUtil.isError(results)); } catch (ServiceAuthException e) { assertNotNull(e); } } + /** + * Test service permission failed. + * @throws Exception the exception + */ public void testServicePermissionFailed() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser2"), "givePermission", "N"); try { - Map<String, Object> results = dispatcher.runSync("testSimpleServicePermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleServicePermission", testingPermMap); assertFalse("The service testServicePermission don't raise service exception", ServiceUtil.isError(results)); } catch (ServiceAuthException e) { assertNotNull(e); } } + /** + * Test group permission failed. + * @throws Exception the exception + */ public void testGroupPermissionFailed() throws Exception { Map<String, Object> testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser2"), "givePermission", "Y"); try { - Map<String, Object> results = dispatcher.runSync("testSimpleGroupAndPermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleGroupAndPermission", testingPermMap); assertFalse("The testGroupPermission don't raise service exception", ServiceUtil.isError(results)); } catch (ServiceAuthException e) { assertNotNull(e); @@ -94,7 +122,7 @@ public class ServicePermissionTests extends OFBizTestCase { testingPermMap = UtilMisc.toMap("userLogin", getUserLogin("permUser1"), "givePermission", "N"); try { - Map<String, Object> results = dispatcher.runSync("testSimpleGroupOrPermission", testingPermMap); + Map<String, Object> results = getDispatcher().runSync("testSimpleGroupOrPermission", testingPermMap); assertFalse("The testGroupPermission don't raise service exception", ServiceUtil.isError(results)); } catch (ServiceAuthException e) { assertNotNull(e); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceSOAPTests.java b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceSOAPTests.java index 72a53d4..6dba0f8 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceSOAPTests.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceSOAPTests.java @@ -35,13 +35,21 @@ public class ServiceSOAPTests extends OFBizTestCase { super(name); } + /** + * Test soap simple service. + * @throws Exception the exception + */ public void testSOAPSimpleService() throws Exception { Map<String, Object> serviceContext = new HashMap<>(); serviceContext.put("defaultValue", Double.valueOf("123.4567")); serviceContext.put("message", "Test Message !!!"); - dispatcher.runSync("testSoapSimple", serviceContext); + getDispatcher().runSync("testSoapSimple", serviceContext); } + /** + * Test soap service. + * @throws Exception the exception + */ public void testSOAPService() throws Exception { Map<String, Object> serviceContext = new HashMap<>(); GenericValue testing = delegator.makeValue("Testing"); @@ -50,7 +58,7 @@ public class ServiceSOAPTests extends OFBizTestCase { testing.put("testingName", "Complex Type Test"); testing.put("createdStamp", UtilDateTime.nowTimestamp()); serviceContext.put("testing", testing); - Map<String, Object> results = dispatcher.runSync("testSoap", serviceContext); + Map<String, Object> results = getDispatcher().runSync("testSoap", serviceContext); List<GenericValue> testingNodes = UtilGenerics.cast(results.get("testingNodes")); assertNotNull(testingNodes); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/testtools/OFBizTestCase.java b/framework/service/src/main/java/org/apache/ofbiz/service/testtools/OFBizTestCase.java index ca60fb7..04a6171 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/testtools/OFBizTestCase.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/testtools/OFBizTestCase.java @@ -31,9 +31,13 @@ import java.util.Set; public class OFBizTestCase extends EntityTestCase { - protected LocalDispatcher dispatcher = null; - protected String MODULE = this.getClass().getName(); + private LocalDispatcher dispatcher = null; + private static final String MODULE = OFBizTestCase.class.getName(); + /** + * Gets dispatcher. + * @return the dispatcher + */ public LocalDispatcher getDispatcher() { return dispatcher; } @@ -42,11 +46,20 @@ public class OFBizTestCase extends EntityTestCase { super(name); } + /** + * Sets dispatcher. + * @param dispatcher the dispatcher + */ public void setDispatcher(LocalDispatcher dispatcher) { this.dispatcher = dispatcher; } - // Retrieves a particular login record. + /** + * Gets user login. + * @param userLoginId the user login id + * @return the user login + * @throws GenericEntityException the generic entity exception + */ protected GenericValue getUserLogin(String userLoginId) throws GenericEntityException { return EntityQuery.use(delegator) .from("UserLogin") @@ -54,35 +67,71 @@ public class OFBizTestCase extends EntityTestCase { .queryOne(); } - // Retrieves the default login record. + /** + * Gets user login. + * @return the user login + * @throws GenericEntityException the generic entity exception + */ protected GenericValue getUserLogin() throws GenericEntityException { return getUserLogin("system"); } + /** + * From entity query. + * @param entityName the entity name + * @return the entity query + */ protected EntityQuery from(String entityName) { return EntityQuery.use(delegator).from(entityName); } + /** + * From entity query. + * @param dynamicViewEntity the dynamic view entity + * @return the entity query + */ protected EntityQuery from(DynamicViewEntity dynamicViewEntity) { return EntityQuery.use(delegator).from(dynamicViewEntity); } + /** + * Select entity query. + * @param fields the fields + * @return the entity query + */ protected EntityQuery select(String... fields) { return EntityQuery.use(delegator).select(fields); } + /** + * Select entity query. + * @param fields the fields + * @return the entity query + */ protected EntityQuery select(Set<String> fields) { return EntityQuery.use(delegator).select(fields); } + /** + * Log info. + * @param msg the msg + */ protected void logInfo(String msg) { Debug.logInfo(msg, MODULE); } + /** + * Log error. + * @param msg the msg + */ protected void logError(String msg) { Debug.logError(msg, MODULE); } + /** + * Log warning. + * @param msg the msg + */ protected void logWarning(String msg) { Debug.logWarning(msg, MODULE); } diff --git a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/ServiceTest.java b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/ServiceTest.java index ff1f364..f6a7890 100644 --- a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/ServiceTest.java +++ b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/ServiceTest.java @@ -36,7 +36,7 @@ public class ServiceTest extends OFBizTestCase { private static final String MODULE = ServiceTest.class.getName(); - protected String serviceName; + private String serviceName; /** * Tests of Service @@ -59,7 +59,7 @@ public class ServiceTest extends OFBizTestCase { try { - Map<String, Object> serviceResult = dispatcher.runSync(serviceName, UtilMisc.toMap("test", this, "testResult", result)); + Map<String, Object> serviceResult = getDispatcher().runSync(serviceName, UtilMisc.toMap("test", this, "testResult", result)); // do something with the errorMessage String errorMessage = (String) serviceResult.get(ModelService.ERROR_MESSAGE); diff --git a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/SimpleMethodTest.java b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/SimpleMethodTest.java index 7361d49..2668bae 100644 --- a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/SimpleMethodTest.java +++ b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/SimpleMethodTest.java @@ -79,8 +79,8 @@ public class SimpleMethodTest extends OFBizTestCase { request.setAttribute("security", security); request.setAttribute("servletContext", servletContext); request.setAttribute("delegator", delegator); - request.setAttribute("dispatcher", dispatcher); - Map<String, Object> serviceResult = SimpleMethod.runSimpleService(methodLocation, methodName, dispatcher.getDispatchContext(), + request.setAttribute("dispatcher", getDispatcher()); + Map<String, Object> serviceResult = SimpleMethod.runSimpleService(methodLocation, methodName, getDispatcher().getDispatchContext(), UtilMisc.toMap("test", this, "testResult", result, "locale", Locale.getDefault(), "request", request, "response", response)); // do something with the errorMessage diff --git a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/TestRunContainer.java b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/TestRunContainer.java index 89f91da..6f097d1 100644 --- a/framework/testtools/src/main/java/org/apache/ofbiz/testtools/TestRunContainer.java +++ b/framework/testtools/src/main/java/org/apache/ofbiz/testtools/TestRunContainer.java @@ -50,7 +50,7 @@ import junit.framework.TestSuite; public class TestRunContainer implements Container { private static final String MODULE = TestRunContainer.class.getName(); - public static final String logDir = "runtime/logs/test-results/"; + public static final String LOG_DIR = "runtime/logs/test-results/"; private String name; private JunitSuiteWrapper jsWrapper; @@ -58,7 +58,7 @@ public class TestRunContainer implements Container { @Override public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException { this.name = name; - new File(logDir).mkdir(); + new File(LOG_DIR).mkdir(); // get the test properties passed by the user in the command line Map<String, String> testProps = ofbizCommands.stream() @@ -80,7 +80,7 @@ public class TestRunContainer implements Container { // prepare TestSuite suite = modelSuite.makeTestSuite(); JUnitTest test = new JUnitTest(suite.getName()); - JunitXmlListener xml = createJunitXmlListener(suite, logDir); + JunitXmlListener xml = createJunitXmlListener(suite, LOG_DIR); TestResult results = new TestResult(); results.addListener(new JunitListener()); results.addListener(xml); @@ -173,7 +173,7 @@ public class TestRunContainer implements Container { class JunitXmlListener extends XMLJUnitResultFormatter { - Map<String, Long> startTimes = new HashMap<>(); + private Map<String, Long> startTimes = new HashMap<>(); JunitXmlListener(OutputStream out) { this.setOutput(out); @@ -212,7 +212,7 @@ public class TestRunContainer implements Container { @Override public void startTest(Test test) { - Debug.logInfo("[JUNIT] : " + getTestName(test) + " starting...", MODULE); + Debug.logInfo("[JUNIT] : " + getTestName(test) + " starting...", MODULE); } private String getTestName(Test test) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ExternalLoginKeysManager.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ExternalLoginKeysManager.java index d06f02c..accf448 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ExternalLoginKeysManager.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ExternalLoginKeysManager.java @@ -42,7 +42,7 @@ public class ExternalLoginKeysManager { private static final String MODULE = ExternalLoginKeysManager.class.getName(); private static final String EXTERNAL_LOGIN_KEY_ATTR = "externalLoginKey"; // This Map is keyed by the randomly generated externalLoginKey and the value is a UserLogin GenericValue object - private static final Map<String, GenericValue> externalLoginKeys = new ConcurrentHashMap<>(); + private static final Map<String, GenericValue> EXTERNAL_LOGIN_KEYS = new ConcurrentHashMap<>(); // This variable is set to empty so we know need to read from the properties file. private static String isExternalLoginKeyEnabled = ""; @@ -66,7 +66,7 @@ public class ExternalLoginKeysManager { if (sesExtKey != null) { if (isAjax(request)) return sesExtKey; - externalLoginKeys.remove(sesExtKey); + EXTERNAL_LOGIN_KEYS.remove(sesExtKey); } GenericValue userLogin = (GenericValue) request.getAttribute("userLogin"); @@ -74,14 +74,14 @@ public class ExternalLoginKeysManager { if (userLogin == null) return ""; //no key made yet for this request, create one - while (externalKey == null || externalLoginKeys.containsKey(externalKey)) { + while (externalKey == null || EXTERNAL_LOGIN_KEYS.containsKey(externalKey)) { UUID uuid = UUID.randomUUID(); externalKey = "EL" + uuid.toString(); } request.setAttribute(EXTERNAL_LOGIN_KEY_ATTR, externalKey); session.setAttribute(EXTERNAL_LOGIN_KEY_ATTR, externalKey); - externalLoginKeys.put(externalKey, userLogin); + EXTERNAL_LOGIN_KEYS.put(externalKey, userLogin); return externalKey; } } @@ -93,7 +93,7 @@ public class ExternalLoginKeysManager { static void cleanupExternalLoginKey(HttpSession session) { String sesExtKey = (String) session.getAttribute(EXTERNAL_LOGIN_KEY_ATTR); if (sesExtKey != null) { - externalLoginKeys.remove(sesExtKey); + EXTERNAL_LOGIN_KEYS.remove(sesExtKey); } } @@ -110,7 +110,7 @@ public class ExternalLoginKeysManager { String externalKey = request.getParameter(EXTERNAL_LOGIN_KEY_ATTR); if (externalKey == null) return "success"; - GenericValue userLogin = externalLoginKeys.get(externalKey); + GenericValue userLogin = EXTERNAL_LOGIN_KEYS.get(externalKey); if (userLogin != null) { //to check it's the right tenant //in case username and password are the same in different tenants 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 e4cfefc..ee5c26b 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 @@ -341,13 +341,17 @@ public final class LoginWorker { || (password == null && token == null) || "error".equals(login(request, response))) { - // make sure this attribute is not in the request; this avoids infinite recursion when a login by less stringent criteria (like not checkout the hasLoggedOut field) passes; this is not a normal circumstance but can happen with custom code or in funny error situations when the userLogin service gets the userLogin object but runs into another problem and fails to return an error + // make sure this attribute is not in the request; this avoids infinite recursion when a login by less stringent criteria + // (like not checkout the hasLoggedOut field) passes; this is not a normal circumstance but can happen with custom code or in + // funny error situations when the userLogin service gets the userLogin object but runs into another problem and fails to + // return an error request.removeAttribute("_LOGIN_PASSED_"); // keep the previous request name in the session session.setAttribute("_PREVIOUS_REQUEST_", request.getPathInfo()); - // NOTE: not using the old _PREVIOUS_PARAMS_ attribute at all because it was a security hole as it was used to put data in the URL (never encrypted) that was originally in a form field that may have been encrypted + // NOTE: not using the old _PREVIOUS_PARAMS_ attribute at all because it was a security hole as it was used to put data in + // the URL (never encrypted) that was originally in a form field that may have been encrypted // keep 2 maps: one for URL parameters and one for form parameters Map<String, Object> urlParams = UtilHttp.getUrlOnlyParameterMap(request); if (UtilValidate.isNotEmpty(urlParams)) { @@ -365,7 +369,8 @@ public final class LoginWorker { //Allow loggingOut when impersonated boolean isLoggingOut = "logout".equals(RequestHandler.getRequestUri(request.getPathInfo())); //Check if the user has an impersonation in process - boolean authoriseLoginDuringImpersonate = EntityUtilProperties.propertyValueEquals("security", "security.login.authorised.during.impersonate", "true"); + boolean authoriseLoginDuringImpersonate = EntityUtilProperties.propertyValueEquals("security", + "security.login.authorised.during.impersonate", "true"); if (!isLoggingOut && !authoriseLoginDuringImpersonate && checkImpersonationInProcess(request, response) != null) { //remove error message that will be displayed in impersonated status screen request.removeAttribute("_ERROR_MESSAGE_LIST_"); @@ -414,7 +419,8 @@ public final class LoginWorker { if (password == null) password = (String) session.getAttribute("PASSWORD"); if (token == null) token = (String) session.getAttribute("TOKEN"); - // allow a username and/or password in a request attribute to override the request parameter or the session attribute; this way a preprocessor can play with these a bit... + // allow a username and/or password in a request attribute to override the request parameter or the session attribute; + // this way a preprocessor can play with these a bit... if (UtilValidate.isNotEmpty(request.getAttribute("USERNAME"))) { username = (String) request.getAttribute("USERNAME"); } @@ -443,13 +449,15 @@ public final class LoginWorker { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); ServletContext servletContext = session.getServletContext(); - // if a tenantId was passed in, see if the userLoginId is associated with that tenantId (can use any delegator for this, entity is not tenant-specific) + // if a tenantId was passed in, see if the userLoginId is associated with that tenantId + // (can use any delegator for this, entity is not tenant-specific) String tenantId = request.getParameter("userTenantId"); if (UtilValidate.isEmpty(tenantId)) { tenantId = (String) request.getAttribute("userTenantId"); } if (UtilValidate.isNotEmpty(tenantId)) { - // see if we need to activate a tenant delegator, only do if the current delegatorName has a hash symbol in it, and if the passed in tenantId doesn't match the one in the delegatorName + // see if we need to activate a tenant delegator, only do if the current delegatorName has a hash symbol in it, + // and if the passed in tenantId doesn't match the one in the delegatorName String oldDelegatorName = delegator.getDelegatorName(); int delegatorNameHashIndex = oldDelegatorName.indexOf('#'); String currentDelegatorTenantId = null; @@ -469,7 +477,8 @@ public final class LoginWorker { } catch (NullPointerException e) { Debug.logError(e, "Error getting tenant delegator", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", "Tenant [" + tenantId + "] not found..."); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -490,7 +499,8 @@ public final class LoginWorker { } catch (NullPointerException e) { Debug.logError(e, "Error getting default delegator", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", "Error getting default delegator"); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -511,7 +521,8 @@ public final class LoginWorker { } catch (GenericServiceException e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -534,7 +545,8 @@ public final class LoginWorker { } catch (GenericServiceException e) { Debug.logError(e, "Error calling updatePassword service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "requirePasswordChange"; } @@ -542,7 +554,8 @@ public final class LoginWorker { String errorMessage = (String) resultPasswordChange.get(ModelService.ERROR_MESSAGE); if (UtilValidate.isNotEmpty(errorMessage)) { Map<String, String> messageMap = UtilMisc.toMap("errorMessage", errorMessage); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } request.setAttribute("_ERROR_MESSAGE_LIST_", resultPasswordChange.get(ModelService.ERROR_MESSAGE_LIST)); @@ -553,7 +566,8 @@ public final class LoginWorker { } catch (GenericEntityException e) { Debug.logError(e, "Error refreshing userLogin value", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "requirePasswordChange"; } @@ -582,7 +596,8 @@ public final class LoginWorker { javaScriptEnabled = "Y"; } try { - result = dispatcher.runSync("setUserPreference", UtilMisc.toMap("userPrefTypeId", "javaScriptEnabled", "userPrefGroupTypeId", "GLOBAL_PREFERENCES", "userPrefValue", javaScriptEnabled, "userLogin", userLogin)); + result = dispatcher.runSync("setUserPreference", UtilMisc.toMap("userPrefTypeId", "javaScriptEnabled", "userPrefGroupTypeId", + "GLOBAL_PREFERENCES", "userPrefValue", javaScriptEnabled, "userLogin", userLogin)); } catch (GenericServiceException e) { Debug.logError(e, "Error setting user preference", MODULE); } @@ -590,7 +605,8 @@ public final class LoginWorker { return doMainLogin(request, response, userLogin, userLoginSession); } else { Map<String, String> messageMap = UtilMisc.toMap("errorMessage", (String) result.get(ModelService.ERROR_MESSAGE)); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return requirePasswordChange ? "requirePasswordChange" : "error"; } @@ -638,15 +654,15 @@ public final class LoginWorker { errMsgList.add(UtilProperties.getMessage(RESOURCE, "loginevents.unable_to_login_this_application", UtilHttp.getLocale(request))); } } catch (GenericEntityException e) { - String errMsg ="Error impersonating the userLoginId" + userLoginIdToImpersonate; + String errMsg = "Error impersonating the userLoginId" + userLoginIdToImpersonate; Debug.logError(e, errMsg, MODULE); errMsgList.add(errMsg); request.setAttribute("_ERROR_MESSAGE_LIST_", errMsgList); - return "error"; + return "error"; } if (!errMsgList.isEmpty()) { request.setAttribute("_ERROR_MESSAGE_LIST_", errMsgList); - return "error"; + return "error"; } ServletContext servletContext = session.getServletContext(); @@ -695,7 +711,8 @@ public final class LoginWorker { return doMainLogin(request, response, userLogin, userLoginSession); } else { Map<String, String> messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE)); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -748,7 +765,8 @@ public final class LoginWorker { return doMainLogin(request, response, originUserLogin, null); } - protected static void setWebContextObjects(HttpServletRequest request, HttpServletResponse response, Delegator delegator, LocalDispatcher dispatcher) { + protected static void setWebContextObjects(HttpServletRequest request, HttpServletResponse response, Delegator delegator, + LocalDispatcher dispatcher) { HttpSession session = request.getSession(); // NOTE: we do NOT want to set this in the servletContext, only in the request and session // We also need to setup the security objects since they are dependent on the delegator @@ -774,9 +792,11 @@ public final class LoginWorker { VisitHandler.getVisit(session); } - public static String doMainLogin(HttpServletRequest request, HttpServletResponse response, GenericValue userLogin, Map<String, Object> userLoginSession) { + public static String doMainLogin(HttpServletRequest request, HttpServletResponse response, GenericValue userLogin, + Map<String, Object> userLoginSession) { HttpSession session = request.getSession(); - boolean authoriseLoginDuringImpersonate = EntityUtilProperties.propertyValueEquals("security", "security.login.authorised.during.impersonate", "true"); + boolean authoriseLoginDuringImpersonate = EntityUtilProperties.propertyValueEquals("security", + "security.login.authorised.during.impersonate", "true"); if (!authoriseLoginDuringImpersonate && checkImpersonationInProcess(request, response) != null) { return "error"; } @@ -814,7 +834,8 @@ public final class LoginWorker { String javaScriptEnabled = null; try { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); - Map<String, Object> result = dispatcher.runSync("getUserPreference", UtilMisc.toMap("userPrefTypeId", "javaScriptEnabled", "userPrefGroupTypeId", "GLOBAL_PREFERENCES", "userLogin", userLogin)); + Map<String, Object> result = dispatcher.runSync("getUserPreference", UtilMisc.toMap("userPrefTypeId", + "javaScriptEnabled", "userPrefGroupTypeId", "GLOBAL_PREFERENCES", "userLogin", userLogin)); javaScriptEnabled = (String) result.get("userPrefValue"); } catch (GenericServiceException e) { Debug.logError(e, "Error getting user preference", MODULE); @@ -884,7 +905,9 @@ public final class LoginWorker { // also make sure the delegatorName is preserved, especially so that a new Visit can be created String delegatorName = (String) session.getAttribute("delegatorName"); // also save the shopping cart if we have one - // DON'T save the cart, causes too many problems: security issues with things done in cart to easy to miss, especially bad on public systems; was put in here because of the "not me" link for auto-login stuff, but that is a small problem compared to what it causes + // DON'T save the cart, causes too many problems: security issues with things done in cart to easy to miss, + // especially bad on public systems; was put in here because of the "not me" link for auto-login stuff, + // but that is a small problem compared to what it causes //ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart"); // clean up some request attributes to which may no longer be valid now that user has logged out @@ -922,7 +945,8 @@ public final class LoginWorker { setWebContextObjects(request, response, delegator, dispatcher); } - // DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", new WebShoppingCart(shoppingCart, session)); + // DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", + // new WebShoppingCart(shoppingCart, session)); } // Set an autologin cookie for the webapp if it requests it @@ -1142,7 +1166,8 @@ public final class LoginWorker { // preprocessor method to login a user from HttpServletRequest.getRemoteUser() (configured in security.properties) public static String checkServletRequestRemoteUserLogin(HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); - Boolean allowRemoteUserLogin = "true".equals(EntityUtilProperties.getPropertyValue("security", "security.login.http.servlet.remoteuserlogin.allow", "false", delegator)); + Boolean allowRemoteUserLogin = "true".equals(EntityUtilProperties.getPropertyValue("security", + "security.login.http.servlet.remoteuserlogin.allow", "false", delegator)); // make sure logging users via remote user is allowed in security.properties; if not just return if (allowRemoteUserLogin) { @@ -1364,7 +1389,8 @@ public final class LoginWorker { * @return A <code>Collection</code> <code>WebappInfo</code> instances that the specified * user is authorized to access */ - public static Collection<ComponentConfig.WebappInfo> getAppBarWebInfos(Security security, GenericValue userLogin, String serverName, String menuName) { + public static Collection<ComponentConfig.WebappInfo> getAppBarWebInfos(Security security, GenericValue userLogin, String serverName, + String menuName) { Collection<ComponentConfig.WebappInfo> allInfos = WEBAPPS.getAppBarWebInfos(serverName, menuName); Collection<ComponentConfig.WebappInfo> allowedInfos = new ArrayList<>(allInfos.size()); for (ComponentConfig.WebappInfo info : allInfos) { @@ -1420,12 +1446,14 @@ public final class LoginWorker { if (now.after(startNotificationFromDate)) { if (now.after(passwordExpirationDate)) { Map<String, String> messageMap = UtilMisc.toMap("passwordExpirationDate", passwordExpirationDate.toString()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.password_expired_message", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.password_expired_message", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "requirePasswordChange"; } else { Map<String, String> messageMap = UtilMisc.toMap("passwordExpirationDate", passwordExpirationDate.toString()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.password_expiration_alert", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.password_expiration_alert", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_EVENT_MESSAGE_", errMsg); return "success"; } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/SameSiteFilter.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/SameSiteFilter.java index 9bfdd7b..2ca1ac2 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/SameSiteFilter.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/SameSiteFilter.java @@ -33,7 +33,8 @@ import org.apache.ofbiz.entity.util.EntityUtilProperties; public class SameSiteFilter implements javax.servlet.Filter { - private static final String SameSiteCookieAttribute = EntityUtilProperties.getPropertyValueFromDelegatorName("security.properties", "SameSiteCookieAttribute", "strict", "default"); + private static final String SAME_SITE_COOKIE_ATTRIBUTE = + EntityUtilProperties.getPropertyValueFromDelegatorName("security.properties", "SameSiteCookieAttribute", "strict", "default"); @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -50,11 +51,11 @@ public class SameSiteFilter implements javax.servlet.Filter { boolean firstHeader = true; for (String header : headers) { // there can be multiple Set-Cookie attributes if (firstHeader) { - response.setHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=" + SameSiteCookieAttribute)); + response.setHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=" + SAME_SITE_COOKIE_ATTRIBUTE)); firstHeader = false; continue; } - response.addHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=" + SameSiteCookieAttribute)); + response.addHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s", header, "SameSite=" + SAME_SITE_COOKIE_ATTRIBUTE)); } } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RequestBodyMapHandlerFactory.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RequestBodyMapHandlerFactory.java index 2877963..f73261c 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RequestBodyMapHandlerFactory.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RequestBodyMapHandlerFactory.java @@ -26,9 +26,9 @@ import javax.servlet.ServletRequest; /** Factory class that provides the proper <code>RequestBodyMapHandler</code> based on the content type of the <code>ServletRequest</code> */ public class RequestBodyMapHandlerFactory { - private static final Map<String, RequestBodyMapHandler> requestBodyMapHandlers = new HashMap<>(); + private static final Map<String, RequestBodyMapHandler> REQ_BODY_MAP_HANDLERS = new HashMap<>(); static { - requestBodyMapHandlers.put("application/json", new JSONRequestBodyMapHandler()); + REQ_BODY_MAP_HANDLERS.put("application/json", new JSONRequestBodyMapHandler()); } public static RequestBodyMapHandler getRequestBodyMapHandler(ServletRequest request) { @@ -36,7 +36,7 @@ public class RequestBodyMapHandlerFactory { if (contentType != null && contentType.indexOf(";") != -1) { contentType = contentType.substring(0, contentType.indexOf(";")); } - return requestBodyMapHandlers.get(contentType); + return REQ_BODY_MAP_HANDLERS.get(contentType); } public static Map<String, Object> extractMapFromRequestBody(ServletRequest request) throws IOException { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RomeEventHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RomeEventHandler.java index 9f00bf0..d7ddc95 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RomeEventHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/RomeEventHandler.java @@ -39,11 +39,11 @@ import com.sun.syndication.io.WireFeedOutput; public class RomeEventHandler implements EventHandler { private static final String MODULE = RomeEventHandler.class.getName(); - public static final String mime = "application/xml; charset=UTF-8"; - public static final String defaultFeedType = "rss_2.0"; + private static final String MIME = "application/xml; charset=UTF-8"; + private static final String DEFAULT_FEED_TYPE = "rss_2.0"; - protected EventHandler service; - protected WireFeedOutput out; + private EventHandler service; + private WireFeedOutput out; @Override public void init(ServletContext context) throws EventHandlerException { @@ -71,7 +71,7 @@ public class RomeEventHandler implements EventHandler { String feedType = request.getParameter("feedType"); if (feedType == null) { - request.setAttribute("feedType", defaultFeedType); + request.setAttribute("feedType", DEFAULT_FEED_TYPE); } // invoke the feed generator service (implements rssFeedInterface) @@ -79,7 +79,7 @@ public class RomeEventHandler implements EventHandler { // pull out the RSS feed from the request attributes WireFeed wireFeed = (WireFeed) request.getAttribute("wireFeed"); - response.setContentType(mime); + response.setContentType(MIME); try { out.output(wireFeed, response.getWriter()); } catch (IOException e) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ScriptEventHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ScriptEventHandler.java index 9a89345..8188536 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ScriptEventHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ScriptEventHandler.java @@ -59,7 +59,7 @@ import org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap; public final class ScriptEventHandler implements EventHandler { private static final String MODULE = ScriptEventHandler.class.getName(); - private static final Set<String> protectedKeys = createProtectedKeys(); + private static final Set<String> PROTECTED_KEYS = createProtectedKeys(); private static Set<String> createProtectedKeys() { Set<String> newSet = new HashSet<>(); @@ -96,10 +96,11 @@ public final class ScriptEventHandler implements EventHandler { context.put("locale", UtilHttp.getLocale(request)); context.put("timeZone", UtilHttp.getTimeZone(request)); context.put("userLogin", session.getAttribute("userLogin")); - context.put(ScriptUtil.PARAMETERS_KEY, UtilHttp.getCombinedMap(request, UtilMisc.toSet("delegator", "dispatcher", "security", "locale", "timeZone", "userLogin"))); + context.put(ScriptUtil.PARAMETERS_KEY, UtilHttp.getCombinedMap(request, + UtilMisc.toSet("delegator", "dispatcher", "security", "locale", "timeZone", "userLogin"))); Object result = null; try { - ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys); + ScriptContext scriptContext = ScriptUtil.createScriptContext(context, PROTECTED_KEYS); result = ScriptUtil.executeScript(event.getPath(), event.getInvoke(), scriptContext, null); if (result == null) { result = scriptContext.getAttribute(ScriptUtil.RESULT_KEY); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/FreeMarkerViewHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/FreeMarkerViewHandler.java index ed99e9e..5b26294 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/FreeMarkerViewHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/FreeMarkerViewHandler.java @@ -45,7 +45,7 @@ import freemarker.template.TemplateException; public class FreeMarkerViewHandler extends AbstractViewHandler { private static final String MODULE = FreeMarkerViewHandler.class.getName(); - protected Configuration config = (Configuration) FreeMarkerWorker.getDefaultOfbizConfig().clone(); + private Configuration config = (Configuration) FreeMarkerWorker.getDefaultOfbizConfig().clone(); @Override public void init(ServletContext context) throws ViewHandlerException { @@ -56,8 +56,9 @@ public class FreeMarkerViewHandler extends AbstractViewHandler { @Override public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException { - if (UtilValidate.isEmpty(page)) + if (UtilValidate.isEmpty(page)) { throw new ViewHandlerException("Invalid template source"); + } // make the root context (data model) for freemarker MapStack<String> context = MapStack.create(); @@ -116,8 +117,8 @@ public class FreeMarkerViewHandler extends AbstractViewHandler { root.put("requestParameters", requestParameters); // add the TabLibFactory - TaglibFactory JspTaglibs = new TaglibFactory(servletContext); - root.put("JspTaglibs", JspTaglibs); + TaglibFactory jspTaglibs = new TaglibFactory(servletContext); + root.put("JspTaglibs", jspTaglibs); } } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/JsLanguageFilesMappingTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/JsLanguageFilesMappingTransform.java index 30e4893..af7e7fd 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/JsLanguageFilesMappingTransform.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/JsLanguageFilesMappingTransform.java @@ -34,19 +34,19 @@ public class JsLanguageFilesMappingTransform implements TemplateTransformModel { String localeString = UtilHttp.getLocale(request).toString(); switch (libraryName) { case "datejs": - out.write(JsLanguageFilesMapping.datejs.getFilePath(localeString)); + out.write(JsLanguageFilesMapping.DateJs.getFilePath(localeString)); break; case "dateTime": - out.write(JsLanguageFilesMapping.dateTime.getFilePath(localeString)); + out.write(JsLanguageFilesMapping.DateTime.getFilePath(localeString)); break; case "jquery": - out.write(JsLanguageFilesMapping.jquery.getFilePath(localeString)); + out.write(JsLanguageFilesMapping.JQuery.getFilePath(localeString)); break; case "select2": - out.write(JsLanguageFilesMapping.select2.getFilePath(localeString)); + out.write(JsLanguageFilesMapping.Select2.getFilePath(localeString)); break; case "validation": - out.write(JsLanguageFilesMapping.validation.getFilePath(localeString)); + out.write(JsLanguageFilesMapping.Validation.getFilePath(localeString)); break; default: } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/ServerHitBin.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/ServerHitBin.java index 3b3b9b8..30a209f 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/ServerHitBin.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/ServerHitBin.java @@ -226,9 +226,9 @@ public class ServerHitBin { serverHitBin.set("minTimeMillis", bin.getMinTime()); serverHitBin.set("maxTimeMillis", bin.getMaxTime()); // get localhost ip address and hostname to store - if (VisitHandler.address != null) { - serverHitBin.set("serverIpAddress", VisitHandler.address.getHostAddress()); - serverHitBin.set("serverHostName", VisitHandler.address.getHostName()); + if (VisitHandler.ADDRESS != null) { + serverHitBin.set("serverIpAddress", VisitHandler.ADDRESS.getHostAddress()); + serverHitBin.set("serverHostName", VisitHandler.ADDRESS.getHostName()); } try { delegator.createSetNextSeqId(serverHitBin); @@ -530,9 +530,9 @@ public class ServerHitBin { serverHit.set("referrerUrl", referrerUrl); // get localhost ip address and hostname to store - if (VisitHandler.address != null) { - serverHit.set("serverIpAddress", VisitHandler.address.getHostAddress()); - serverHit.set("serverHostName", VisitHandler.address.getHostName()); + if (VisitHandler.ADDRESS != null) { + serverHit.set("serverIpAddress", VisitHandler.ADDRESS.getHostAddress()); + serverHit.set("serverHostName", VisitHandler.ADDRESS.getHostName()); } serverHit.create(); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/VisitHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/VisitHandler.java index 497962c..d5a1c0d 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/VisitHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/stats/VisitHandler.java @@ -45,17 +45,17 @@ public class VisitHandler { // Debug MODULE name private static final String MODULE = VisitHandler.class.getName(); - public static final String visitorCookieName = "OFBiz.Visitor"; + public static final String VISITOR_COOKIE_NAME = "OFBiz.Visitor"; - protected static final InetAddress address; + protected static final InetAddress ADDRESS; static { InetAddress tmpAddress = null; try { tmpAddress = InetAddress.getLocalHost(); } catch (java.net.UnknownHostException e) { - Debug.logError("Unable to get server's internet address: " + e.toString(), MODULE); + Debug.logError("Unable to get server's internet ADDRESS: " + e.toString(), MODULE); } - address = tmpAddress; + ADDRESS = tmpAddress; } public static void setUserLogin(HttpSession session, GenericValue userLogin, boolean userCreated) { @@ -128,7 +128,8 @@ public class VisitHandler { } if (delegator == null) { - Debug.logError("Could not find delegator with delegatorName [" + delegatorName + "] in session, or a delegator attribute in the ServletContext, not creating Visit entity", MODULE); + Debug.logError("Could not find delegator with delegatorName [" + delegatorName + + "] in session, or a delegator attribute in the ServletContext, not creating Visit entity", MODULE); } else { String webappName = (String) session.getAttribute("_WEBAPP_NAME_"); Locale initialLocaleObj = (Locale) session.getAttribute("_CLIENT_LOCALE_"); @@ -139,7 +140,8 @@ public class VisitHandler { String initialLocale = initialLocaleObj != null ? initialLocaleObj.toString() : ""; if (UtilValidate.isEmpty(webappName)) { - Debug.logInfo(new Exception(), "The webappName was empty, somehow the initial request settings were missing.", MODULE); + Debug.logInfo(new Exception(), "The webappName was empty, somehow the initial request settings were missing.", + MODULE); } visit = delegator.makeValue("Visit"); @@ -149,7 +151,10 @@ public class VisitHandler { visit.set("initialLocale", initialLocale); visit.set("initialRequest", initialRequest); visit.set("initialReferrer", initialReferrer); - if (initialUserAgent != null) visit.set("initialUserAgent", initialUserAgent.length() > 250 ? initialUserAgent.substring(0, 250) : initialUserAgent); + if (initialUserAgent != null) { + visit.set("initialUserAgent", initialUserAgent.length() > 250 ? initialUserAgent.substring(0, 250) + : initialUserAgent); + } visit.set("webappName", webappName); if (UtilProperties.propertyValueEquals("serverstats", "stats.proxy.enabled", "true")) { visit.set("clientIpAddress", session.getAttribute("_CLIENT_FORWARDED_FOR_")); @@ -175,10 +180,10 @@ public class VisitHandler { Debug.logWarning("Problem checking the visitorId: " + e.toString(), MODULE); } } - // get localhost ip address and hostname to store - if (address != null) { - visit.set("serverIpAddress", address.getHostAddress()); - visit.set("serverHostName", address.getHostName()); + // get localhost ip ADDRESS and hostname to store + if (ADDRESS != null) { + visit.set("serverIpAddress", ADDRESS.getHostAddress()); + visit.set("serverHostName", ADDRESS.getHostName()); } try { visit = delegator.createSetNextSeqId(visit); @@ -215,7 +220,8 @@ public class VisitHandler { } if (delegator == null) { - Debug.logError("Could not find delegator in request or with delegatorName [" + delegatorName + "] in session, not creating/getting Visitor entity", MODULE); + Debug.logError("Could not find delegator in request or with delegatorName [" + delegatorName + + "] in session, not creating/getting Visitor entity", MODULE); } else { // first try to get the current ID from the visitor cookie String cookieVisitorId = null; @@ -225,7 +231,7 @@ public class VisitHandler { } if (cookies != null) { for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equals(visitorCookieName)) { + if (cookies[i].getName().equals(VISITOR_COOKIE_NAME)) { cookieVisitorId = cookies[i].getValue(); break; } @@ -254,7 +260,8 @@ public class VisitHandler { visitor = delegator.createSetNextSeqId(visitor); if (Debug.infoOn()) { String visitorId = visitor != null ? visitor.getString("visitorId") : "empty visitor"; - Debug.logInfo("The visitorId [" + cookieVisitorId + "] found in cookie was invalid, creating new Visitor with ID [" + visitorId + "]", MODULE); + Debug.logInfo("The visitorId [" + cookieVisitorId + + "] found in cookie was invalid, creating new Visitor with ID [" + visitorId + "]", MODULE); } } } catch (GenericEntityException e) { @@ -269,7 +276,7 @@ public class VisitHandler { session.setAttribute("visitor", visitor); // create the cookie and send it back, this may be done over and over, in effect frequently refreshing the cookie - Cookie visitorCookie = new Cookie(visitorCookieName, visitor.getString("visitorId")); + Cookie visitorCookie = new Cookie(VISITOR_COOKIE_NAME, visitor.getString("visitorId")); visitorCookie.setMaxAge(60 * 60 * 24 * 365); visitorCookie.setPath("/"); visitorCookie.setSecure(true); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetFactory.java index 9185d36..07744b6 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/WidgetFactory.java @@ -42,7 +42,7 @@ import org.w3c.dom.Element; public class WidgetFactory { private static final String MODULE = WidgetFactory.class.getName(); - protected static final Map<String, Constructor<? extends ModelScreenWidget>> screenWidgets = new ConcurrentHashMap<>(); + protected static final Map<String, Constructor<? extends ModelScreenWidget>> SCREEN_WIDGETS = new ConcurrentHashMap<>(); static { loadStandardWidgets(); @@ -70,7 +70,7 @@ public class WidgetFactory { public static ModelScreenWidget getModelScreenWidget(ModelScreen modelScreen, Element element) { Assert.notNull("modelScreen", modelScreen, "element", element); String tagName = UtilXml.getTagNameIgnorePrefix(element); - Constructor<? extends ModelScreenWidget> widgetConst = screenWidgets.get(tagName); + Constructor<? extends ModelScreenWidget> widgetConst = SCREEN_WIDGETS.get(tagName); if (widgetConst == null) { throw new IllegalArgumentException("ModelScreenWidget class not found for element " + tagName); } @@ -123,9 +123,10 @@ public class WidgetFactory { * @throws SecurityException * @throws NoSuchMethodException */ - public static void registerScreenWidget(String tagName, Class<? extends ModelScreenWidget> widgetClass) throws SecurityException, NoSuchMethodException { + public static void registerScreenWidget(String tagName, Class<? extends ModelScreenWidget> widgetClass) + throws SecurityException, NoSuchMethodException { Assert.notNull("tagName", tagName, "widgetClass", widgetClass); - screenWidgets.put(tagName, widgetClass.getConstructor(ModelScreen.class, Element.class)); + SCREEN_WIDGETS.put(tagName, widgetClass.getConstructor(ModelScreen.class, Element.class)); if (Debug.verboseOn()) { Debug.logVerbose("Registered " + widgetClass.getName() + " with tag name " + tagName, MODULE); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/FormFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/FormFactory.java index 2902573..b129107 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/FormFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/FormFactory.java @@ -46,8 +46,10 @@ import org.xml.sax.SAXException; public class FormFactory { private static final String MODULE = FormFactory.class.getName(); - private static final UtilCache<String, ModelForm> formLocationCache = UtilCache.createUtilCache("widget.form.locationResource", 0, 0, false); - private static final UtilCache<String, ModelForm> formWebappCache = UtilCache.createUtilCache("widget.form.webappResource", 0, 0, false); + private static final UtilCache<String, ModelForm> FORM_LOCATION_CACHE = + UtilCache.createUtilCache("widget.form.locationResource", 0, 0, false); + private static final UtilCache<String, ModelForm> FORM_WEBAPP_CACHE = + UtilCache.createUtilCache("widget.form.webappResource", 0, 0, false); public static Map<String, ModelForm> getFormsFromLocation(String resourceName, ModelReader entityModelReader, VisualTheme visualTheme, DispatchContext dispatchContext) @@ -63,7 +65,7 @@ public class FormFactory { StringBuilder sb = new StringBuilder(dispatchContext.getDelegator().getDelegatorName()); sb.append(":").append(resourceName).append("#").append(formName).append(visualTheme.getVisualThemeId()); String cacheKey = sb.toString(); - ModelForm modelForm = formLocationCache.get(cacheKey); + ModelForm modelForm = FORM_LOCATION_CACHE.get(cacheKey); if (modelForm == null) { URL formFileUrl = FlexibleLocation.resolveLocation(resourceName); Document formFileDoc = UtilXml.readXmlDocument(formFileUrl, true, true); @@ -71,7 +73,7 @@ public class FormFactory { throw new IllegalArgumentException("Could not find resource [" + resourceName + "]"); } modelForm = createModelForm(formFileDoc, entityModelReader, visualTheme, dispatchContext, resourceName, formName); - modelForm = formLocationCache.putIfAbsentAndGet(cacheKey, modelForm); + modelForm = FORM_LOCATION_CACHE.putIfAbsentAndGet(cacheKey, modelForm); } if (modelForm == null) { throw new IllegalArgumentException("Could not find form with name [" + formName + "] in class resource [" + resourceName + "]"); @@ -91,18 +93,20 @@ public class FormFactory { .append("::") .append(visualTheme.getVisualThemeId()) .toString(); - ModelForm modelForm = formWebappCache.get(cacheKey); + ModelForm modelForm = FORM_WEBAPP_CACHE.get(cacheKey); if (modelForm == null) { Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); URL formFileUrl = request.getServletContext().getResource(resourceName); Document formFileDoc = UtilXml.readXmlDocument(formFileUrl, true, true); Element formElement = UtilXml.firstChildElement(formFileDoc.getDocumentElement(), "form", "name", formName); - modelForm = createModelForm(formElement, delegator.getModelReader(), visualTheme, dispatcher.getDispatchContext(), resourceName, formName); - modelForm = formWebappCache.putIfAbsentAndGet(cacheKey, modelForm); + modelForm = createModelForm(formElement, delegator.getModelReader(), visualTheme, dispatcher.getDispatchContext(), + resourceName, formName); + modelForm = FORM_WEBAPP_CACHE.putIfAbsentAndGet(cacheKey, modelForm); } if (modelForm == null) { - throw new IllegalArgumentException("Could not find form with name [" + formName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); + throw new IllegalArgumentException("Could not find form with name [" + formName + "] in webapp resource [" + resourceName + + "] in the webapp [" + webappName + "]"); } return modelForm; } @@ -124,10 +128,10 @@ public class FormFactory { .append(formName) .append(visualTheme.getVisualThemeId()) .toString(); - ModelForm modelForm = formLocationCache.get(cacheKey); + ModelForm modelForm = FORM_LOCATION_CACHE.get(cacheKey); if (modelForm == null) { modelForm = createModelForm(formElement, entityModelReader, visualTheme, dispatchContext, formLocation, formName); - modelForm = formLocationCache.putIfAbsentAndGet(cacheKey, modelForm); + modelForm = FORM_LOCATION_CACHE.putIfAbsentAndGet(cacheKey, modelForm); } modelFormMap.put(formName, modelForm); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/GridFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/GridFactory.java index a4a92e3..7187593 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/GridFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/GridFactory.java @@ -48,8 +48,10 @@ import org.xml.sax.SAXException; public class GridFactory { private static final String MODULE = GridFactory.class.getName(); - private static final UtilCache<String, ModelGrid> gridLocationCache = UtilCache.createUtilCache("widget.grid.locationResource", 0, 0, false); - private static final UtilCache<String, ModelGrid> gridWebappCache = UtilCache.createUtilCache("widget.grid.webappResource", 0, 0, false); + private static final UtilCache<String, ModelGrid> GRID_LOCATION_CACHE = + UtilCache.createUtilCache("widget.grid.locationResource", 0, 0, false); + private static final UtilCache<String, ModelGrid> GRID_WEBAPP_CACHE = + UtilCache.createUtilCache("widget.grid.webappResource", 0, 0, false); public static Map<String, ModelGrid> getGridsFromLocation(String resourceName, ModelReader entityModelReader, VisualTheme visualTheme, DispatchContext dispatchContext) @@ -65,7 +67,7 @@ public class GridFactory { StringBuilder sb = new StringBuilder(dispatchContext.getDelegator().getDelegatorName()); sb.append(":").append(resourceName).append("#").append(gridName).append(visualTheme.getVisualThemeId()); String cacheKey = sb.toString(); - ModelGrid modelGrid = gridLocationCache.get(cacheKey); + ModelGrid modelGrid = GRID_LOCATION_CACHE.get(cacheKey); if (modelGrid == null) { URL gridFileUrl = FlexibleLocation.resolveLocation(resourceName); Document gridFileDoc = UtilXml.readXmlDocument(gridFileUrl, true, true); @@ -74,7 +76,7 @@ public class GridFactory { } modelGrid = createModelGrid(gridFileDoc, entityModelReader, visualTheme, dispatchContext, resourceName, gridName); - modelGrid = gridLocationCache.putIfAbsentAndGet(cacheKey, modelGrid); + modelGrid = GRID_LOCATION_CACHE.putIfAbsentAndGet(cacheKey, modelGrid); } if (modelGrid == null) { throw new IllegalArgumentException("Could not find grid with name [" + gridName + "] in class resource [" + resourceName + "]"); @@ -94,7 +96,7 @@ public class GridFactory { .append("::") .append(visualTheme.getVisualThemeId()) .toString(); - ModelGrid modelGrid = gridWebappCache.get(cacheKey); + ModelGrid modelGrid = GRID_WEBAPP_CACHE.get(cacheKey); if (modelGrid == null) { ServletContext servletContext = request.getServletContext(); Delegator delegator = (Delegator) request.getAttribute("delegator"); @@ -104,10 +106,11 @@ public class GridFactory { Element gridElement = UtilXml.firstChildElement(gridFileDoc.getDocumentElement(), "grid", "name", gridName); modelGrid = createModelGrid(gridElement, delegator.getModelReader(), visualTheme, dispatcher.getDispatchContext(), resourceName, gridName); - modelGrid = gridWebappCache.putIfAbsentAndGet(cacheKey, modelGrid); + modelGrid = GRID_WEBAPP_CACHE.putIfAbsentAndGet(cacheKey, modelGrid); } if (modelGrid == null) { - throw new IllegalArgumentException("Could not find grid with name [" + gridName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); + throw new IllegalArgumentException("Could not find grid with name [" + gridName + "] in webapp resource [" + resourceName + + "] in the webapp [" + webappName + "]"); } return modelGrid; } @@ -129,11 +132,11 @@ public class GridFactory { .append(gridName) .append(visualTheme.getVisualThemeId()) .toString(); - ModelGrid modelGrid = gridLocationCache.get(cacheKey); + ModelGrid modelGrid = GRID_LOCATION_CACHE.get(cacheKey); if (modelGrid == null) { modelGrid = createModelGrid(gridElement, entityModelReader, visualTheme, dispatchContext, gridLocation, gridName); - modelGrid = gridLocationCache.putIfAbsentAndGet(cacheKey, modelGrid); + modelGrid = GRID_LOCATION_CACHE.putIfAbsentAndGet(cacheKey, modelGrid); } modelGridMap.put(gridName, modelGrid); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/HtmlWidget.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/HtmlWidget.java index 77a2153..891710b 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/HtmlWidget.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/HtmlWidget.java @@ -64,9 +64,9 @@ import java.util.Stack; public class HtmlWidget extends ModelScreenWidget { private static final String MODULE = HtmlWidget.class.getName(); - private static final UtilCache<String, Template> specialTemplateCache = + private static final UtilCache<String, Template> SPECIAL_TEMPLATE_CACHE = UtilCache.createUtilCache("widget.screen.template.ftl.general", 0, 0, false); - protected static final Configuration specialConfig = FreeMarkerWorker.makeConfiguration(new ExtendedWrapper(FreeMarkerWorker.VERSION)); + protected static final Configuration SPECIAL_CONFIG = FreeMarkerWorker.makeConfiguration(new ExtendedWrapper(FreeMarkerWorker.VERSION)); // not sure if this is the best way to get FTL to use my fancy MapModel derivative, but should work at least... public static class ExtendedWrapper extends BeansWrapper { @@ -136,6 +136,10 @@ public class HtmlWidget extends ModelScreenWidget { } } + /** + * Gets sub widgets. + * @return the sub widgets + */ public List<ModelScreenWidget> getSubWidgets() { return subWidgets; } @@ -166,7 +170,7 @@ public class HtmlWidget extends ModelScreenWidget { if (location.endsWith(".fo.ftl")) { // FOP can't render correctly escaped characters template = FreeMarkerWorker.getTemplate(location); } else { - template = FreeMarkerWorker.getTemplate(location, specialTemplateCache, specialConfig); + template = FreeMarkerWorker.getTemplate(location, SPECIAL_TEMPLATE_CACHE, SPECIAL_CONFIG); } FreeMarkerWorker.renderTemplate(template, context, writer); @@ -266,7 +270,7 @@ public class HtmlWidget extends ModelScreenWidget { } public static class HtmlTemplate extends ModelScreenWidget { - protected FlexibleStringExpander locationExdr; + private FlexibleStringExpander locationExdr; private boolean multiBlock; public HtmlTemplate(ModelScreen modelScreen, Element htmlTemplateElement) { @@ -275,10 +279,19 @@ public class HtmlWidget extends ModelScreenWidget { this.multiBlock = !"false".equals(htmlTemplateElement.getAttribute("multi-block")); } + /** + * Gets location. + * @param context the context + * @return the location + */ public String getLocation(Map<String, Object> context) { return locationExdr.expandString(context); } + /** + * Is multi block boolean. + * @return the boolean + */ public boolean isMultiBlock() { return this.multiBlock; } @@ -298,14 +311,18 @@ public class HtmlWidget extends ModelScreenWidget { visitor.visit(this); } + /** + * Gets location exdr. + * @return the location exdr + */ public FlexibleStringExpander getLocationExdr() { return locationExdr; } } public static class HtmlTemplateDecorator extends ModelScreenWidget { - protected FlexibleStringExpander locationExdr; - protected Map<String, ModelScreenWidget> sectionMap = new HashMap<>(); + private FlexibleStringExpander locationExdr; + private Map<String, ModelScreenWidget> sectionMap = new HashMap<>(); public HtmlTemplateDecorator(ModelScreen modelScreen, Element htmlTemplateDecoratorElement) { super(modelScreen, htmlTemplateDecoratorElement); @@ -349,17 +366,25 @@ public class HtmlWidget extends ModelScreenWidget { visitor.visit(this); } + /** + * Gets location exdr. + * @return the location exdr + */ public FlexibleStringExpander getLocationExdr() { return locationExdr; } + /** + * Gets section map. + * @return the section map + */ public Map<String, ModelScreenWidget> getSectionMap() { return sectionMap; } } public static class HtmlTemplateDecoratorSection extends ModelScreenWidget { - protected List<ModelScreenWidget> subWidgets; + private List<ModelScreenWidget> subWidgets; public HtmlTemplateDecoratorSection(ModelScreen modelScreen, Element htmlTemplateDecoratorSectionElement) { super(modelScreen, htmlTemplateDecoratorSectionElement); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/MenuFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/MenuFactory.java index a98c726..5f9ada6 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/MenuFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/MenuFactory.java @@ -45,8 +45,10 @@ public class MenuFactory { private static final String MODULE = MenuFactory.class.getName(); - public static final UtilCache<String, Map<String, ModelMenu>> menuWebappCache = UtilCache.createUtilCache("widget.menu.webappResource", 0, 0, false); - public static final UtilCache<String, Map<String, ModelMenu>> menuLocationCache = UtilCache.createUtilCache("widget.menu.locationResource", 0, 0, false); + public static final UtilCache<String, Map<String, ModelMenu>> MENU_WEBAPP_CACHE = + UtilCache.createUtilCache("widget.menu.webappResource", 0, 0, false); + public static final UtilCache<String, Map<String, ModelMenu>> MENU_LOCATION_CACHE = + UtilCache.createUtilCache("widget.menu.locationResource", 0, 0, false); public static ModelMenu getMenuFromWebappContext(String resourceName, String menuName, HttpServletRequest request) throws IOException, SAXException, ParserConfigurationException { @@ -59,24 +61,26 @@ public class MenuFactory { cacheKey += "::" + visualTheme.getVisualThemeId(); } - Map<String, ModelMenu> modelMenuMap = menuWebappCache.get(cacheKey); + Map<String, ModelMenu> modelMenuMap = MENU_WEBAPP_CACHE.get(cacheKey); if (modelMenuMap == null) { ServletContext servletContext = request.getServletContext(); URL menuFileUrl = servletContext.getResource(resourceName); Document menuFileDoc = UtilXml.readXmlDocument(menuFileUrl, true, true); modelMenuMap = readMenuDocument(menuFileDoc, location, visualTheme); - menuWebappCache.putIfAbsent(cacheKey, modelMenuMap); - modelMenuMap = menuWebappCache.get(cacheKey); + MENU_WEBAPP_CACHE.putIfAbsent(cacheKey, modelMenuMap); + modelMenuMap = MENU_WEBAPP_CACHE.get(cacheKey); } if (UtilValidate.isEmpty(modelMenuMap)) { - throw new IllegalArgumentException("Could not find menu file in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); + throw new IllegalArgumentException("Could not find menu file in webapp resource [" + resourceName + "] in the webapp [" + + webappName + "]"); } ModelMenu modelMenu = modelMenuMap.get(menuName); if (modelMenu == null) { - throw new IllegalArgumentException("Could not find menu with name [" + menuName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); + throw new IllegalArgumentException("Could not find menu with name [" + menuName + "] in webapp resource [" + resourceName + + "] in the webapp [" + webappName + "]"); } return modelMenu; } @@ -93,19 +97,20 @@ public class MenuFactory { ModelMenu modelMenu = new ModelMenu(menuElement, menuLocation, visualTheme); modelMenuMap.put(modelMenu.getName(), modelMenu); } - } + } return modelMenuMap; } - public static ModelMenu getMenuFromLocation(String resourceName, String menuName, VisualTheme visualTheme) throws IOException, SAXException, ParserConfigurationException { + public static ModelMenu getMenuFromLocation(String resourceName, String menuName, VisualTheme visualTheme) + throws IOException, SAXException, ParserConfigurationException { String keyName = resourceName + "::" + visualTheme.getVisualThemeId(); - Map<String, ModelMenu> modelMenuMap = menuLocationCache.get(keyName); + Map<String, ModelMenu> modelMenuMap = MENU_LOCATION_CACHE.get(keyName); if (modelMenuMap == null) { URL menuFileUrl = FlexibleLocation.resolveLocation(resourceName); Document menuFileDoc = UtilXml.readXmlDocument(menuFileUrl, true, true); modelMenuMap = readMenuDocument(menuFileDoc, resourceName, visualTheme); - menuLocationCache.putIfAbsent(keyName, modelMenuMap); - modelMenuMap = menuLocationCache.get(keyName); + MENU_LOCATION_CACHE.putIfAbsent(keyName, modelMenuMap); + modelMenuMap = MENU_LOCATION_CACHE.get(keyName); } if (UtilValidate.isEmpty(modelMenuMap)) { @@ -118,4 +123,4 @@ public class MenuFactory { } return modelMenu; } -} \ No newline at end of file +} diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelForm.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelForm.java index 484723e..632b947 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelForm.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelForm.java @@ -1623,10 +1623,18 @@ public abstract class ModelForm extends ModelWidget { return value; } + /** + * Gets sort field parameter name. + * @return the sort field parameter name + */ public String getSortFieldParameterName() { return this.sortFieldParameterName; } + /** + * Gets sort order fields. + * @return the sort order fields + */ public List<SortField> getSortOrderFields() { return sortOrderFields; } @@ -1659,6 +1667,10 @@ public abstract class ModelForm extends ModelWidget { return styles; } + /** + * Gets target. + * @return the target + */ public String getTarget() { return target != null ? target.getOriginal() : null; } @@ -2061,7 +2073,7 @@ public abstract class ModelForm extends ModelWidget { public static class FieldGroup implements FieldGroupBase { private static AtomicInteger baseSeqNo = new AtomicInteger(0); - private static final String baseId = "_G"; + private static final String BASE_ID = "_G"; private final String id; private final String style; private final String title; @@ -2080,7 +2092,7 @@ public abstract class ModelForm extends ModelWidget { if (sortOrderElement != null) { id = sortOrderElement.getAttribute("id"); if (id.isEmpty()) { - String lastGroupId = baseId + baseSeqNo.getAndIncrement() + "_"; + String lastGroupId = BASE_ID + baseSeqNo.getAndIncrement() + "_"; id = lastGroupId; } style = sortOrderElement.getAttribute("style"); @@ -2096,7 +2108,7 @@ public abstract class ModelForm extends ModelWidget { fieldGroupMap.put(sortFieldElement.getAttribute("name"), this); } } else { - String lastGroupId = baseId + baseSeqNo.getAndIncrement() + "_"; + String lastGroupId = BASE_ID + baseSeqNo.getAndIncrement() + "_"; id = lastGroupId; } this.id = id; @@ -2229,10 +2241,18 @@ public abstract class ModelForm extends ModelWidget { } } + /** + * Gets field name. + * @return the field name + */ public String getFieldName() { return this.fieldName; } + /** + * Gets position. + * @return the position + */ public Integer getPosition() { return this.position; } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormFieldBuilder.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormFieldBuilder.java index 7b3da5b..d01a8e6 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormFieldBuilder.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormFieldBuilder.java @@ -114,17 +114,17 @@ public class ModelFormFieldBuilder { private String parentFormName = ""; private String tabindex = ""; private String conditionGroup = ""; - private boolean disabled= false; + private boolean disabled = false; - protected static final List<String> numericFieldTypes = Collections.unmodifiableList(UtilMisc.toList( + protected static final List<String> NUMERIC_FIELD_TYPES = Collections.unmodifiableList(UtilMisc.toList( "floating-point", "numeric", "fixed-point", "currency-amount", "currency-precise")); - protected static final List<String> textFieldTypes = Collections.unmodifiableList(UtilMisc.toList( + protected static final List<String> TEXT_FIELD_TYPES = Collections.unmodifiableList(UtilMisc.toList( "id", "id-long", "id-vlong", "very-short", "name", "short-varchar", "value", "comment", "description", "long-varchar", "url", "email")); - protected static final Map<String, Integer> textSizeByFieldTypes = Collections.unmodifiableMap(UtilMisc.toMap( + protected static final Map<String, Integer> TEXT_SIZE_BY_FIELD_TYPES = Collections.unmodifiableMap(UtilMisc.toMap( "id", 20, "id-long", 40, "id-vlong", 60, @@ -137,7 +137,7 @@ public class ModelFormFieldBuilder { "long-varchar", 60, "url", 60, "email", 60)); - protected static final Map<String, Integer> textMaxSizeByFieldTypes = Collections.unmodifiableMap(UtilMisc.toMap( + protected static final Map<String, Integer> TEXT_MAX_SIZE_BY_FIELD_TYPES = Collections.unmodifiableMap(UtilMisc.toMap( "id", 20, "id-long", 60, "id-vlong", 250, @@ -150,7 +150,7 @@ public class ModelFormFieldBuilder { "long-varchar", 250, "url", 250, "email", 250)); - protected static final List<String> dateFieldTypes = Collections.unmodifiableList(UtilMisc.toList( + protected static final List<String> DATA_FIELD_TYPES = Collections.unmodifiableList(UtilMisc.toList( "date-time", "date", "time")); public ModelFormFieldBuilder() { @@ -741,6 +741,13 @@ public class ModelFormFieldBuilder { return false; } + /** + * Induce field info from entity field boolean. + * @param modelEntity the model entity + * @param modelField the model field + * @param defaultFieldType the default field type + * @return the boolean + */ public boolean induceFieldInfoFromEntityField(ModelEntity modelEntity, ModelField modelField, String defaultFieldType) { if (modelEntity == null || modelField == null) { return false; @@ -757,14 +764,14 @@ public class ModelFormFieldBuilder { ModelFormField.DropDownField dropDownField = new ModelFormField.DropDownField(FieldInfo.SOURCE_AUTO_ENTITY, optionSources); this.setFieldInfo(dropDownField); - } else if (textFieldTypes.contains(fieldType)) { + } else if (TEXT_FIELD_TYPES.contains(fieldType)) { ModelFormField.TextFindField textField = new ModelFormField.TextFindField(FieldInfo.SOURCE_AUTO_ENTITY, - textSizeByFieldTypes.get(fieldType), textMaxSizeByFieldTypes.get(fieldType), null); + TEXT_SIZE_BY_FIELD_TYPES.get(fieldType), TEXT_MAX_SIZE_BY_FIELD_TYPES.get(fieldType), null); this.setFieldInfo(textField); - } else if (numericFieldTypes.contains(fieldType)) { + } else if (NUMERIC_FIELD_TYPES.contains(fieldType)) { ModelFormField.RangeFindField textField = new ModelFormField.RangeFindField(FieldInfo.SOURCE_AUTO_ENTITY, 6, null); this.setFieldInfo(textField); - } else if (dateFieldTypes.contains(fieldType)) { + } else if (DATA_FIELD_TYPES.contains(fieldType)) { String type = fieldType; if ("date-time".equals(fieldType)) { type = "timestamp"; @@ -792,14 +799,14 @@ public class ModelFormFieldBuilder { } else if ("very-long".equals(fieldType)) { ModelFormField.TextareaField textareaField = new ModelFormField.TextareaField(FieldInfo.SOURCE_AUTO_ENTITY, null); this.setFieldInfo(textareaField); - } else if (textFieldTypes.contains(fieldType)) { + } else if (TEXT_FIELD_TYPES.contains(fieldType)) { ModelFormField.TextField textField = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_ENTITY, - textSizeByFieldTypes.get(fieldType), textMaxSizeByFieldTypes.get(fieldType), null); + TEXT_SIZE_BY_FIELD_TYPES.get(fieldType), TEXT_MAX_SIZE_BY_FIELD_TYPES.get(fieldType), null); this.setFieldInfo(textField); - } else if (numericFieldTypes.contains(fieldType)) { + } else if (NUMERIC_FIELD_TYPES.contains(fieldType)) { ModelFormField.TextField textField = new ModelFormField.TextField(FieldInfo.SOURCE_AUTO_ENTITY, 6, null, null); this.setFieldInfo(textField); - } else if (dateFieldTypes.contains(fieldType)) { + } else if (DATA_FIELD_TYPES.contains(fieldType)) { String type = fieldType; if ("date-time".equals(fieldType)) { type = "timestamp"; diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelWidget.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelWidget.java index 0c7660a..3d1dcec 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelWidget.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelWidget.java @@ -38,7 +38,7 @@ public abstract class ModelWidget implements Serializable { * The parameter name used to control widget boundary comments. Currently * set to "widgetVerbose". */ - public static final String enableBoundaryCommentsParam = "widgetVerbose"; + public static final String ENABLE_BOUNDARY_COMMENTS_PARAM = "widgetVerbose"; private final String name; private final String systemId; @@ -135,13 +135,13 @@ public abstract class ModelWidget implements Serializable { public static boolean widgetBoundaryCommentsEnabled(Map<String, ? extends Object> context) { boolean result = "true".equals(UtilProperties.getPropertyValue("widget", "widget.verbose")); if (result && context != null) { - String str = (String) context.get(enableBoundaryCommentsParam); + String str = (String) context.get(ENABLE_BOUNDARY_COMMENTS_PARAM); if (str != null) { result = "true".equals(str); } else { Map<String, ? extends Object> parameters = UtilGenerics.cast(context.get("parameters")); if (parameters != null) { - str = (String) parameters.get(enableBoundaryCommentsParam); + str = (String) parameters.get(ENABLE_BOUNDARY_COMMENTS_PARAM); if (str != null) { result = "true".equals(str); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ScreenFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ScreenFactory.java index 960f71e..74bf41d 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ScreenFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ScreenFactory.java @@ -48,8 +48,10 @@ public class ScreenFactory { private static final String MODULE = ScreenFactory.class.getName(); - public static final UtilCache<String, Map<String, ModelScreen>> screenLocationCache = UtilCache.createUtilCache("widget.screen.locationResource", 0, 0, false); - public static final UtilCache<String, Map<String, ModelScreen>> screenWebappCache = UtilCache.createUtilCache("widget.screen.webappResource", 0, 0, false); + public static final UtilCache<String, Map<String, ModelScreen>> SCREEN_LOCATION_CACHE = + UtilCache.createUtilCache("widget.screen.locationResource", 0, 0, false); + public static final UtilCache<String, Map<String, ModelScreen>> SCREEN_WEBAPP_CACHE = + UtilCache.createUtilCache("widget.screen.webappResource", 0, 0, false); public static boolean isCombinedName(String combinedName) { int numSignIndex = combinedName.lastIndexOf("#"); @@ -66,10 +68,12 @@ public class ScreenFactory { // split out the name on the last "#" int numSignIndex = combinedName.lastIndexOf("#"); if (numSignIndex == -1) { - throw new IllegalArgumentException("Error in screen location/name: no \"#\" found to separate the location from the name; correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); + throw new IllegalArgumentException("Error in screen location/name: no \"#\" found to separate the location from the name;" + + "correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); } if (numSignIndex + 1 >= combinedName.length()) { - throw new IllegalArgumentException("Error in screen location/name: the \"#\" was at the end with no screen name after it; correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); + throw new IllegalArgumentException("Error in screen location/name: the \"#\" was at the end with no screen name after it;" + + "correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); } String resourceName = combinedName.substring(0, numSignIndex); return resourceName; @@ -79,10 +83,12 @@ public class ScreenFactory { // split out the name on the last "#" int numSignIndex = combinedName.lastIndexOf("#"); if (numSignIndex == -1) { - throw new IllegalArgumentException("Error in screen location/name: no \"#\" found to separate the location from the name; correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); + throw new IllegalArgumentException("Error in screen location/name: no \"#\" found to separate the location from the name;" + + "correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); } if (numSignIndex + 1 >= combinedName.length()) { - throw new IllegalArgumentException("Error in screen location/name: the \"#\" was at the end with no screen name after it; correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); + throw new IllegalArgumentException("Error in screen location/name: the \"#\" was at the end with no screen name after it;" + + "correct example: component://product/screen/product/ProductScreens.xml#EditProduct"); } String screenName = combinedName.substring(numSignIndex + 1); return screenName; @@ -107,10 +113,10 @@ public class ScreenFactory { public static Map<String, ModelScreen> getScreensFromLocation(String resourceName) throws IOException, SAXException, ParserConfigurationException { - Map<String, ModelScreen> modelScreenMap = screenLocationCache.get(resourceName); + Map<String, ModelScreen> modelScreenMap = SCREEN_LOCATION_CACHE.get(resourceName); if (modelScreenMap == null) { synchronized (ScreenFactory.class) { - modelScreenMap = screenLocationCache.get(resourceName); + modelScreenMap = SCREEN_LOCATION_CACHE.get(resourceName); if (modelScreenMap == null) { long startTime = System.currentTimeMillis(); URL screenFileUrl = null; @@ -120,9 +126,10 @@ public class ScreenFactory { } Document screenFileDoc = UtilXml.readXmlDocument(screenFileUrl, true, true); modelScreenMap = readScreenDocument(screenFileDoc, resourceName); - screenLocationCache.put(resourceName, modelScreenMap); + SCREEN_LOCATION_CACHE.put(resourceName, modelScreenMap); double totalSeconds = (System.currentTimeMillis() - startTime) / 1000.0; - Debug.logInfo("Got " + modelScreenMap.size() + " screens in " + totalSeconds + "s from: " + screenFileUrl.toExternalForm(), MODULE); + Debug.logInfo("Got " + modelScreenMap.size() + " screens in " + totalSeconds + "s from: " + + screenFileUrl.toExternalForm(), MODULE); } } } @@ -139,24 +146,25 @@ public class ScreenFactory { String cacheKey = webappName + "::" + resourceName; - Map<String, ModelScreen> modelScreenMap = screenWebappCache.get(cacheKey); + Map<String, ModelScreen> modelScreenMap = SCREEN_WEBAPP_CACHE.get(cacheKey); if (modelScreenMap == null) { synchronized (ScreenFactory.class) { - modelScreenMap = screenWebappCache.get(cacheKey); + modelScreenMap = SCREEN_WEBAPP_CACHE.get(cacheKey); if (modelScreenMap == null) { ServletContext servletContext = request.getServletContext(); URL screenFileUrl = servletContext.getResource(resourceName); Document screenFileDoc = UtilXml.readXmlDocument(screenFileUrl, true, true); modelScreenMap = readScreenDocument(screenFileDoc, resourceName); - screenWebappCache.put(cacheKey, modelScreenMap); + SCREEN_WEBAPP_CACHE.put(cacheKey, modelScreenMap); } } } ModelScreen modelScreen = modelScreenMap.get(screenName); if (modelScreen == null) { - throw new IllegalArgumentException("Could not find screen with name [" + screenName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); + throw new IllegalArgumentException("Could not find screen with name [" + screenName + "] in webapp resource [" + resourceName + + "] in the webapp [" + webappName + "]"); } return modelScreen; } @@ -178,7 +186,8 @@ public class ScreenFactory { return modelScreenMap; } - public static void renderReferencedScreen(String name, String location, ModelScreenWidget parentWidget, Appendable writer, Map<String, Object> context, ScreenStringRenderer screenStringRenderer) throws GeneralException { + public static void renderReferencedScreen(String name, String location, ModelScreenWidget parentWidget, Appendable writer, + Map<String, Object> context, ScreenStringRenderer screenStringRenderer) throws GeneralException { // check to see if the name is a composite name separated by a #, if so split it up and get it by the full loc#name if (ScreenFactory.isCombinedName(name)) { String combinedName = name; @@ -198,7 +207,8 @@ public class ScreenFactory { } else { modelScreen = parentWidget.getModelScreen().getModelScreenMap().get(name); if (modelScreen == null) { - throw new IllegalArgumentException("Could not find screen with name [" + name + "] in the same file as the screen with name [" + parentWidget.getModelScreen().getName() + "]"); + throw new IllegalArgumentException("Could not find screen with name [" + name + "] in the same file as the screen with name [" + + parentWidget.getModelScreen().getName() + "]"); } } modelScreen.renderScreenString(writer, context, screenStringRenderer); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ThemeFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ThemeFactory.java index 8a8d143..20720b7 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ThemeFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ThemeFactory.java @@ -56,8 +56,10 @@ public class ThemeFactory { private static final String MODULE = ThemeFactory.class.getName(); - private static final UtilCache<String, ModelTheme> themeLocationCache = UtilCache.createUtilCache("widget.theme.locationResource", 0, 0, false); - private static final UtilCache<String, VisualTheme> themeVisualThemeIdCache = UtilCache.createUtilCache("widget.theme.idAndVisualTheme", 0, 0, false); + private static final UtilCache<String, ModelTheme> THEME_LOCATION_CACHE = + UtilCache.createUtilCache("widget.theme.locationResource", 0, 0, false); + private static final UtilCache<String, VisualTheme> THEME_VISUAL_THEME_ID_CACHE = + UtilCache.createUtilCache("widget.theme.idAndVisualTheme", 0, 0, false); /** * From a w3c Document return the modelTheme instantiated @@ -90,7 +92,7 @@ public class ThemeFactory { ModelTheme modelTheme = getModelThemeFromLocation(xmlTheme.toURI().toURL().toString()); if (modelTheme != null) { for (String containsVisualThemeId : modelTheme.getVisualThemeIds()) { - themeVisualThemeIdCache.put(containsVisualThemeId, modelTheme.getVisualTheme(containsVisualThemeId)); + THEME_VISUAL_THEME_ID_CACHE.put(containsVisualThemeId, modelTheme.getVisualTheme(containsVisualThemeId)); } } } @@ -109,17 +111,17 @@ public class ThemeFactory { if (visualThemeId == null) { return null; } - VisualTheme visualTheme = themeVisualThemeIdCache.get(visualThemeId); + VisualTheme visualTheme = THEME_VISUAL_THEME_ID_CACHE.get(visualThemeId); if (visualTheme == null) { synchronized (ThemeFactory.class) { - visualTheme = themeVisualThemeIdCache.get(visualThemeId); + visualTheme = THEME_VISUAL_THEME_ID_CACHE.get(visualThemeId); if (visualTheme == null) { pullModelThemesFromXmlToCache(); } - visualTheme = themeVisualThemeIdCache.get(visualThemeId); + visualTheme = THEME_VISUAL_THEME_ID_CACHE.get(visualThemeId); if (visualTheme == null) { Debug.logError("Impossible to resolve the modelTheme for the visualThemeId " + visualThemeId + ", Common is returned", MODULE); - return themeVisualThemeIdCache.get("COMMON"); + return THEME_VISUAL_THEME_ID_CACHE.get("COMMON"); } } @@ -134,11 +136,11 @@ public class ThemeFactory { * @return */ public static ModelTheme getModelThemeFromLocation(String resourceName) { - ModelTheme modelTheme = themeLocationCache.get(resourceName); + ModelTheme modelTheme = THEME_LOCATION_CACHE.get(resourceName); if (modelTheme == null) { synchronized (ThemeFactory.class) { try { - modelTheme = themeLocationCache.get(resourceName); + modelTheme = THEME_LOCATION_CACHE.get(resourceName); if (modelTheme == null) { URL themeFileUrl = null; themeFileUrl = FlexibleLocation.resolveLocation(resourceName); @@ -147,7 +149,7 @@ public class ThemeFactory { } Document themeFileDoc = UtilXml.readXmlDocument(themeFileUrl, true, true); modelTheme = readThemeDocument(themeFileDoc); - themeLocationCache.put(resourceName, modelTheme); + THEME_LOCATION_CACHE.put(resourceName, modelTheme); } } catch (IOException | ParserConfigurationException | SAXException e) { Debug.logError("Impossible to resolve the theme from the resourceName " + resourceName, MODULE); @@ -164,11 +166,10 @@ public class ThemeFactory { * @return * @throws GenericEntityException */ - public static List<VisualTheme> getAvailableThemes(Delegator delegator, String visualThemeSetId) - throws GenericEntityException { - if (themeVisualThemeIdCache.isEmpty()) { + public static List<VisualTheme> getAvailableThemes(Delegator delegator, String visualThemeSetId) throws GenericEntityException { + if (THEME_VISUAL_THEME_ID_CACHE.isEmpty()) { synchronized (ThemeFactory.class) { - if (themeVisualThemeIdCache.isEmpty()) { + if (THEME_VISUAL_THEME_ID_CACHE.isEmpty()) { pullModelThemesFromXmlToCache(); } } @@ -178,7 +179,7 @@ public class ThemeFactory { EntityCondition.makeCondition("visualThemeSetId", visualThemeSetId), null, UtilMisc.toList("visualThemeId"), null, true); List<String> visualThemeIds = EntityUtil.getFieldListFromEntityList(visualThemesInDataBase, "visualThemeId", true); for (String visualThemeId : visualThemeIds) { - visualThemesMap.put(visualThemeId, themeVisualThemeIdCache.get(visualThemeId)); + visualThemesMap.put(visualThemeId, THEME_VISUAL_THEME_ID_CACHE.get(visualThemeId)); } return new ArrayList<>(visualThemesMap.values()); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/TreeFactory.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/TreeFactory.java index 5bc5e0e..babc755 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/TreeFactory.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/TreeFactory.java @@ -42,16 +42,17 @@ public class TreeFactory { private static final String MODULE = TreeFactory.class.getName(); - public static final UtilCache<String, Map<String, ModelTree>> treeLocationCache = UtilCache.createUtilCache("widget.tree.locationResource", 0, 0, false); + public static final UtilCache<String, Map<String, ModelTree>> TREE_LOCATION_CACHE = + UtilCache.createUtilCache("widget.tree.locationResource", 0, 0, false); public static ModelTree getTreeFromLocation(String resourceName, String treeName, Delegator delegator, LocalDispatcher dispatcher) throws IOException, SAXException, ParserConfigurationException { - Map<String, ModelTree> modelTreeMap = treeLocationCache.get(resourceName); + Map<String, ModelTree> modelTreeMap = TREE_LOCATION_CACHE.get(resourceName); if (modelTreeMap == null) { URL treeFileUrl = FlexibleLocation.resolveLocation(resourceName); Document treeFileDoc = UtilXml.readXmlDocument(treeFileUrl, true, true); modelTreeMap = readTreeDocument(treeFileDoc, delegator, dispatcher, resourceName); - modelTreeMap = treeLocationCache.putIfAbsentAndGet(resourceName, modelTreeMap); + modelTreeMap = TREE_LOCATION_CACHE.putIfAbsentAndGet(resourceName, modelTreeMap); } ModelTree modelTree = modelTreeMap.get(treeName); if (modelTree == null) { @@ -61,7 +62,8 @@ public class TreeFactory { return modelTree; } - public static Map<String, ModelTree> readTreeDocument(Document treeFileDoc, Delegator delegator, LocalDispatcher dispatcher, String treeLocation) { + public static Map<String, ModelTree> readTreeDocument(Document treeFileDoc, Delegator delegator, + LocalDispatcher dispatcher, String treeLocation) { Map<String, ModelTree> modelTreeMap = new HashMap<>(); if (treeFileDoc != null) { // read document and construct ModelTree for each tree element diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenRenderer.java index a672a08..00852bb 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenRenderer.java @@ -92,7 +92,8 @@ public class ScreenRenderer { /** * Renders the named screen using the render environment configured when this ScreenRenderer was created. - * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, separated by a pound sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file. + * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, + * separated by a pound sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file. * @throws IOException * @throws SAXException * @throws ParserConfigurationException @@ -106,7 +107,8 @@ public class ScreenRenderer { /** * Renders the named screen using the render environment configured when this ScreenRenderer was created. - * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs + * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" + * and other special OFBiz style URLs * @param screenName The name of the screen within the XML file specified by the resourceName. * @throws IOException * @throws SAXException @@ -172,11 +174,13 @@ public class ScreenRenderer { * @param locale the locale * @param userLogin the user login */ - public void populateBasicContext(Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) { + public void populateBasicContext(Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, + Security security, Locale locale, GenericValue userLogin) { populateBasicContext(context, this, parameters, delegator, dispatcher, security, locale, userLogin); } - public static void populateBasicContext(MapStack<String> context, ScreenRenderer screens, Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) { + public static void populateBasicContext(MapStack<String> context, ScreenRenderer screens, Map<String, Object> parameters, + Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) { // ========== setup values that should always be in a screen context // include an object to more easily render screens context.put("screens", screens); @@ -184,7 +188,8 @@ public class ScreenRenderer { // make a reference for high level variables, a global context context.put("globalContext", context.standAloneStack()); - // make sure the "nullField" object is in there for entity ops; note this is nullField and not null because as null causes problems in FreeMarker and such... + // make sure the "nullField" object is in there for entity ops; note this is nullField and not null because as null + // causes problems in FreeMarker and such... context.put("nullField", GenericEntity.NULL_FIELD); context.put("parameters", parameters); @@ -195,7 +200,8 @@ public class ScreenRenderer { context.put("userLogin", userLogin); context.put("nowTimestamp", UtilDateTime.nowTimestamp()); try { - Map<String, Object> result = dispatcher.runSync("getUserPreferenceGroup", UtilMisc.toMap("userLogin", userLogin, "userPrefGroupTypeId", "GLOBAL_PREFERENCES")); + Map<String, Object> result = dispatcher.runSync("getUserPreferenceGroup", + UtilMisc.toMap("userLogin", userLogin, "userPrefGroupTypeId", "GLOBAL_PREFERENCES")); context.put("userPreferences", result.get("userPrefMap")); } catch (GenericServiceException e) { Debug.logError(e, "Error while getting user preferences: ", MODULE); @@ -213,10 +219,12 @@ public class ScreenRenderer { populateContextForRequest(context, this, request, response, servletContext); } - public static void populateContextForRequest(MapStack<String> context, ScreenRenderer screens, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) { + public static void populateContextForRequest(MapStack<String> context, ScreenRenderer screens, HttpServletRequest request, + HttpServletResponse response, ServletContext servletContext) { HttpSession session = request.getSession(); - // attribute names to skip for session and application attributes; these are all handled as special cases, duplicating results and causing undesired messages + // attribute names to skip for session and application attributes; these are all handled as special cases, + // duplicating results and causing undesired messages Set<String> attrNamesToSkip = UtilMisc.toSet("delegator", "dispatcher", "security", "webSiteId", "org.apache.catalina.jsp_classpath"); Map<String, Object> parameterMap = UtilHttp.getCombinedMap(request, attrNamesToSkip); @@ -240,7 +248,8 @@ public class ScreenRenderer { // ========== setup values that are specific to OFBiz webapps VisualTheme visualTheme = UtilHttp.getVisualTheme(request); if (visualTheme == null) { - String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", (Delegator) request.getAttribute("delegator")); + String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", + "VISUAL_THEME", (Delegator) request.getAttribute("delegator")); visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId); } context.put("visualTheme", visualTheme); @@ -273,8 +282,8 @@ public class ScreenRenderer { // these ones are FreeMarker specific and will only work in FTL templates, mainly here for backward compatibility context.put("sessionAttributes", new HttpSessionHashModel(session, FreeMarkerWorker.getDefaultOfbizWrapper())); context.put("requestAttributes", new HttpRequestHashModel(request, FreeMarkerWorker.getDefaultOfbizWrapper())); - TaglibFactory JspTaglibs = new TaglibFactory(servletContext); - context.put("JspTaglibs", JspTaglibs); + TaglibFactory jspTaglibs = new TaglibFactory(servletContext); + context.put("JspTaglibs", jspTaglibs); context.put("requestParameters", UtilHttp.getParameterMap(request)); ServletContextHashModel ftlServletContext = (ServletContextHashModel) request.getAttribute("ftlServletContext"); @@ -350,10 +359,19 @@ public class ScreenRenderer { context.push(); } + /** + * Gets context. + * @return the context + */ public Map<String, Object> getContext() { return context; } + /** + * Populate context for service. + * @param dctx the dctx + * @param serviceContext the service context + */ public void populateContextForService(DispatchContext dctx, Map<String, Object> serviceContext) { this.populateBasicContext(serviceContext, dctx.getDelegator(), dctx.getDispatcher(), dctx.getSecurity(), (Locale) serviceContext.get("locale"), (GenericValue) serviceContext.get("userLogin")); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/FoFormRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/FoFormRenderer.java index 4cf5959..37ad1fd 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/FoFormRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/FoFormRenderer.java @@ -67,8 +67,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend private static final String MODULE = FoFormRenderer.class.getName(); - HttpServletRequest request; - HttpServletResponse response; + private HttpServletRequest request; + private HttpServletResponse response; public FoFormRenderer() { } @@ -139,14 +139,17 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend if (UtilValidate.isNotEmpty(explicitDescription)) { makeBlockString(writer, modelFormField.getWidgetStyle(), explicitDescription); } else { - makeBlockString(writer, modelFormField.getWidgetStyle(), FieldInfoWithOptions.getDescriptionForOptionKey(currentValue, allOptionValues)); + makeBlockString(writer, modelFormField.getWidgetStyle(), + FieldInfoWithOptions.getDescriptionForOptionKey(currentValue, allOptionValues)); } } else { boolean optionSelected = false; for (ModelFormField.OptionValue optionValue : allOptionValues) { String noCurrentSelectedKey = dropDownField.getNoCurrentSelectedKey(context); - if ((UtilValidate.isNotEmpty(currentValue) && currentValue.equals(optionValue.getKey()) && "selected".equals(dropDownField.getCurrent())) - || (UtilValidate.isEmpty(currentValue) && noCurrentSelectedKey != null && noCurrentSelectedKey.equals(optionValue.getKey()))) { + if ((UtilValidate.isNotEmpty(currentValue) && currentValue.equals(optionValue.getKey()) + && "selected".equals(dropDownField.getCurrent())) + || (UtilValidate.isEmpty(currentValue) && noCurrentSelectedKey != null + && noCurrentSelectedKey.equals(optionValue.getKey()))) { makeBlockString(writer, modelFormField.getWidgetStyle(), optionValue.getDescription()); optionSelected = true; break; @@ -204,7 +207,7 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend @Override public void renderFormOpen(Appendable writer, Map<String, Object> context, ModelForm modelForm) throws IOException { - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + this.setWidgetCommentsEnabled(ModelWidget.widgetBoundaryCommentsEnabled(context)); renderBeginningBoundaryComment(writer, "Form Widget", modelForm); } @@ -272,7 +275,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatHeaderRowCellOpen(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { + public void renderFormatHeaderRowCellOpen(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField, + int positionSpan) throws IOException { writer.append("<fo:table-cell "); if (positionSpan > 1) { writer.append("number-columns-spanned=\""); @@ -286,7 +290,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatHeaderRowCellClose(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { + public void renderFormatHeaderRowCellClose(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField) + throws IOException { writer.append("</fo:block>"); writer.append("</fo:table-cell>"); appendWhitespace(writer); @@ -305,7 +310,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatHeaderRowFormCellTitleSeparator(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField, boolean isLast) throws IOException { + public void renderFormatHeaderRowFormCellTitleSeparator(Appendable writer, Map<String, Object> context, ModelForm modelForm, + ModelFormField modelFormField, boolean isLast) throws IOException { } @Override @@ -321,7 +327,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatItemRowCellOpen(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { + public void renderFormatItemRowCellOpen(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField, + int positionSpan) throws IOException { writer.append("<fo:table-cell "); if (positionSpan > 1) { writer.append("number-columns-spanned=\""); @@ -338,7 +345,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatItemRowCellClose(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { + public void renderFormatItemRowCellClose(Appendable writer, Map<String, Object> context, ModelForm modelForm, ModelFormField modelFormField) + throws IOException { writer.append("</fo:table-cell>"); appendWhitespace(writer); } @@ -406,13 +414,15 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend } @Override - public void renderFormatFieldRowWidgetCellOpen(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { + public void renderFormatFieldRowWidgetCellOpen(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, int positions, + int positionSpan, Integer nextPositionInRow) throws IOException { writer.append("<fo:table-cell text-align=\"left\" padding=\"2pt\" padding-left=\"5pt\">"); appendWhitespace(writer); } @Override - public void renderFormatFieldRowWidgetCellClose(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { + public void renderFormatFieldRowWidgetCellClose(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, + int positions, int positionSpan, Integer nextPositionInRow) throws IOException { writer.append("</fo:table-cell>"); appendWhitespace(writer); } @@ -487,7 +497,8 @@ public class FoFormRenderer extends HtmlWidgetRenderer implements FormStringRend makeBlockString(writer, null, ""); } - public void renderHyperlinkTitle(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, String titleText) throws IOException { + public void renderHyperlinkTitle(Appendable writer, Map<String, Object> context, ModelFormField modelFormField, String titleText) + throws IOException { } @Override diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlMenuRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlMenuRenderer.java index 3167472..c8f5a6d 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlMenuRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlMenuRenderer.java @@ -127,6 +127,13 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe writer.append(location); } + /** + * Append tooltip. + * @param writer the writer + * @param context the context + * @param modelMenuItem the model menu item + * @throws IOException the io exception + */ public void appendTooltip(Appendable writer, Map<String, Object> context, ModelMenuItem modelMenuItem) throws IOException { // render the tooltip String tooltip = modelMenuItem.getTooltip(context); @@ -219,6 +226,12 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe appendWhitespace(writer); } + /** + * Is disable if empty boolean. + * @param menuItem the menu item + * @param context the context + * @return the boolean + */ public boolean isDisableIfEmpty(ModelMenuItem menuItem, Map<String, Object> context) { boolean disabled = false; String disableIfEmpty = menuItem.getDisableIfEmpty(); @@ -238,7 +251,7 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe @Override public void renderMenuOpen(Appendable writer, Map<String, Object> context, ModelMenu modelMenu) throws IOException { - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + this.setWidgetCommentsEnabled(ModelWidget.widgetBoundaryCommentsEnabled(context)); renderBeginningBoundaryComment(writer, "Menu Widget", modelMenu); writer.append("<div"); String menuId = modelMenu.getId(); @@ -335,6 +348,10 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe this.userLoginIdAtPermGrant = string; } + /** + * Gets user login id at perm grant. + * @return the user login id at perm grant + */ public String getUserLoginIdAtPermGrant() { return this.userLoginIdAtPermGrant; } @@ -382,6 +399,12 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe return hasChanged; } + /** + * Gets title. + * @param menuItem the menu item + * @param context the context + * @return the title + */ public String getTitle(ModelMenuItem menuItem, Map<String, Object> context) { String title = null; title = menuItem.getTitle(context); @@ -401,7 +424,8 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe HttpServletRequest request = (HttpServletRequest) context.get("request"); String targetWindow = link.getTargetWindow(context); - String uniqueItemName = menuItem.getModelMenu().getName() + "_" + menuItem.getName() + "_LF_" + UtilMisc.<String>addToBigDecimalInMap(context, "menuUniqueItemIndex", BigDecimal.ONE); + String uniqueItemName = menuItem.getModelMenu().getName() + "_" + menuItem.getName() + "_LF_" + + UtilMisc.<String>addToBigDecimalInMap(context, "menuUniqueItemIndex", BigDecimal.ONE); String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request); if ("hidden-form".equals(linkType)) { @@ -549,7 +573,7 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe } else { writer.append(src); } - } else if (urlMode != null && "content".equalsIgnoreCase(urlMode)) { + } else if (urlMode != null && "content".equalsIgnoreCase(urlMode)) { if (request != null && response != null) { StringBuilder newURL = new StringBuilder(); ContentUrlTag.appendContentPrefix(request, newURL); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlTreeRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlTreeRenderer.java index a5edc8e..3658028 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlTreeRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlTreeRenderer.java @@ -50,7 +50,7 @@ import freemarker.template.TemplateException; */ public class HtmlTreeRenderer extends HtmlWidgetRenderer implements TreeStringRenderer { - ScreenStringRenderer screenStringRenderer = null; + private ScreenStringRenderer screenStringRenderer = null; private static final String MODULE = HtmlTreeRenderer.class.getName(); public HtmlTreeRenderer() { } @@ -62,7 +62,7 @@ public class HtmlTreeRenderer extends HtmlWidgetRenderer implements TreeStringRe List<String> currentNodeTrail = (obj instanceof List) ? UtilGenerics.cast(obj) : null; if (node.isRootNode()) { appendWhitespace(writer); - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + this.setWidgetCommentsEnabled(ModelWidget.widgetBoundaryCommentsEnabled(context)); renderBeginningBoundaryComment(writer, "Tree Widget", node.getModelTree()); writer.append("<ul class=\"basic-tree\">"); } @@ -325,7 +325,7 @@ public class HtmlTreeRenderer extends HtmlWidgetRenderer implements TreeStringRe } else { writer.append(src); } - } else if (urlMode != null && "content".equalsIgnoreCase(urlMode)) { + } else if (urlMode != null && "content".equalsIgnoreCase(urlMode)) { if (request != null && response != null) { StringBuilder newURL = new StringBuilder(); ContentUrlTag.appendContentPrefix(request, newURL); diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlWidgetRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlWidgetRenderer.java index 7a63054..7c26716 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlWidgetRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/html/HtmlWidgetRenderer.java @@ -34,16 +34,32 @@ public class HtmlWidgetRenderer { * Characters that are appended to the end of each rendered element. Currently set to * CR/LF. */ - public static final String whiteSpace = "\r\n"; + public static final String WHITE_SPACE = "\r\n"; - protected boolean widgetCommentsEnabled = false; + /** + * Sets widget comments enabled. + * @param widgetCommentsEnabled the widget comments enabled + */ + public void setWidgetCommentsEnabled(boolean widgetCommentsEnabled) { + this.widgetCommentsEnabled = widgetCommentsEnabled; + } + + private boolean widgetCommentsEnabled = false; + + /** + * Is widget comments enabled boolean. + * @return the boolean + */ + public boolean isWidgetCommentsEnabled() { + return widgetCommentsEnabled; + } /** * Helper method used to append whitespace characters to the end of each rendered element. * @param writer The writer to write to */ public void appendWhitespace(Appendable writer) throws IOException { - writer.append(whiteSpace); + writer.append(WHITE_SPACE); } /** @@ -57,11 +73,11 @@ public class HtmlWidgetRenderer { } public static String formatBoundaryComment(String boundaryType, String widgetType, String widgetName) { - return "<!-- " + boundaryType + " " + widgetType + " " + widgetName + " -->" + whiteSpace; + return "<!-- " + boundaryType + " " + widgetType + " " + widgetName + " -->" + WHITE_SPACE; } public static String formatBoundaryJsComment(String boundaryType, String widgetType, String widgetName) { - return "// " + boundaryType + " " + widgetType + " " + widgetName + whiteSpace; + return "// " + boundaryType + " " + widgetType + " " + widgetName + WHITE_SPACE; } /** |
Free forum by Nabble | Edit this page |