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 7d82b17 Improved: Corrected some line is longer than 150 characters checkstyle issues in framework component. Also fixed some extra spaces and naming conventions related checkstyle issues. (OFBIZ-11921) 7d82b17 is described below commit 7d82b17c726f91600d35e21940c74b3085d9e145 Author: Suraj Khurana <[hidden email]> AuthorDate: Mon Aug 3 10:11:40 2020 +0530 Improved: Corrected some line is longer than 150 characters checkstyle issues in framework component. Also fixed some extra spaces and naming conventions related checkstyle issues. (OFBIZ-11921) --- .../base/component/ComponentResourceHandler.java | 6 +- .../apache/ofbiz/base/config/ResourceHandler.java | 14 +- .../org/apache/ofbiz/base/container/Container.java | 6 +- .../apache/ofbiz/base/conversion/Converters.java | 10 +- .../ofbiz/base/conversion/LocalizedConverter.java | 8 +- .../java/org/apache/ofbiz/base/lang/Factory.java | 2 +- .../ofbiz/base/util/HttpRequestFileUpload.java | 8 +- .../org/apache/ofbiz/base/util/ObjectType.java | 18 +- .../java/org/apache/ofbiz/base/util/SSLUtil.java | 22 +- .../java/org/apache/ofbiz/base/util/UtilCodec.java | 6 +- .../org/apache/ofbiz/base/util/UtilFormatOut.java | 20 +- .../java/org/apache/ofbiz/base/util/UtilHttp.java | 178 +++--- .../java/org/apache/ofbiz/base/util/UtilMisc.java | 4 +- .../java/org/apache/ofbiz/base/util/UtilTimer.java | 2 +- .../apache/ofbiz/base/util/cache/UtilCache.java | 2 +- .../base/util/string/FlexibleStringExpander.java | 2 +- .../ofbiz/base/util/string/NodeELResolver.java | 2 +- .../ofbiz/base/util/string/UelFunctions.java | 336 ++++++----- .../catalina/container/CatalinaContainer.java | 8 +- .../org/apache/ofbiz/common/CdyneServices.java | 4 +- .../org/apache/ofbiz/common/CommonServices.java | 2 +- .../org/apache/ofbiz/common/CommonWorkers.java | 2 +- .../java/org/apache/ofbiz/common/FtpServices.java | 2 +- .../org/apache/ofbiz/common/UrlServletHelper.java | 2 +- .../apache/ofbiz/common/email/EmailServices.java | 2 +- .../ofbiz/common/email/NotificationServices.java | 4 +- .../apache/ofbiz/common/period/PeriodWorker.java | 2 +- .../apache/ofbiz/common/qrcode/QRCodeServices.java | 6 +- .../ofbiz/common/telecom/TelecomServices.java | 2 +- .../org/apache/ofbiz/datafile/ModelDataFile.java | 1 - .../org/apache/ofbiz/entity/GenericDelegator.java | 2 +- .../java/org/apache/ofbiz/entity/GenericValue.java | 126 ++-- .../apache/ofbiz/entity/condition/EntityExpr.java | 10 +- .../apache/ofbiz/entity/datasource/GenericDAO.java | 200 ++++--- .../ofbiz/entity/datasource/GenericHelper.java | 2 +- .../ofbiz/entity/datasource/GenericHelperDAO.java | 2 +- .../ofbiz/entity/datasource/GenericHelperInfo.java | 5 +- .../org/apache/ofbiz/entity/finder/ListFinder.java | 33 +- .../org/apache/ofbiz/entity/jdbc/DatabaseUtil.java | 635 ++++++++++++--------- .../apache/ofbiz/entity/jdbc/JdbcValueHandler.java | 2 +- .../org/apache/ofbiz/entity/jdbc/SQLProcessor.java | 8 +- .../org/apache/ofbiz/entity/jdbc/SqlJdbcUtil.java | 172 ++++-- .../ofbiz/entity/model/ModelEntityChecker.java | 2 +- .../org/apache/ofbiz/entity/model/ModelReader.java | 22 +- .../apache/ofbiz/entity/model/ModelViewEntity.java | 6 +- .../apache/ofbiz/entity/test/EntityTestSuite.java | 2 +- .../ofbiz/entity/transaction/TransactionUtil.java | 3 +- .../ofbiz/entity/util/DistributedCacheClear.java | 12 +- .../ofbiz/entity/util/EntityBatchIterator.java | 2 +- .../apache/ofbiz/entity/util/EntityDataAssert.java | 4 +- .../ofbiz/entity/util/EntityListIterator.java | 8 +- .../org/apache/ofbiz/entity/util/EntityQuery.java | 6 +- .../apache/ofbiz/entity/util/EntitySaxReader.java | 8 +- .../apache/ofbiz/entity/util/EntityTypeUtil.java | 2 +- .../org/apache/ofbiz/entity/util/EntityUtil.java | 176 +++--- .../ofbiz/entity/util/EntityUtilProperties.java | 2 +- .../synchronization/EntitySyncContext.java | 6 +- .../ofbiz/minilang/MiniLangRuntimeException.java | 2 +- .../org/apache/ofbiz/minilang/SimpleMethod.java | 256 +++++---- .../apache/ofbiz/minilang/ValidationException.java | 2 +- .../method/conditional/CombinedCondition.java | 8 +- .../ofbiz/minilang/method/conditional/Compare.java | 12 +- .../method/conditional/CompareCondition.java | 2 +- .../method/conditional/CompareFieldCondition.java | 2 +- .../minilang/method/conditional/Conditional.java | 4 +- .../method/conditional/EmptyCondition.java | 2 +- .../method/conditional/HasPermissionCondition.java | 2 +- .../minilang/method/conditional/MasterIf.java | 2 +- .../conditional/ValidateMethodCondition.java | 2 +- .../minilang/method/ifops/CheckPermission.java | 2 +- .../ofbiz/minilang/method/ifops/IfInstanceOf.java | 2 +- .../ofbiz/minilang/method/ifops/IfNotEmpty.java | 2 +- .../apache/ofbiz/minilang/test/MiniLangTests.java | 12 +- .../ofbiz/service/GenericAbstractDispatcher.java | 2 +- .../org/apache/ofbiz/service/ModelService.java | 9 +- .../apache/ofbiz/service/ModelServiceReader.java | 4 +- .../apache/ofbiz/service/ServiceDispatcher.java | 8 +- .../java/org/apache/ofbiz/service/ServiceUtil.java | 8 +- .../service/calendar/TemporalExpressionWorker.java | 62 +- .../ofbiz/service/config/ServiceConfigUtil.java | 2 +- .../ofbiz/service/eca/ServiceEcaCondition.java | 4 +- .../ofbiz/service/engine/EntityAutoEngine.java | 14 +- .../apache/ofbiz/service/engine/GenericEngine.java | 18 +- .../ofbiz/service/jms/GenericMessageListener.java | 8 +- .../org/apache/ofbiz/service/job/AbstractJob.java | 2 +- .../org/apache/ofbiz/service/job/JobPoller.java | 20 +- .../ofbiz/service/job/PersistedServiceJob.java | 2 +- .../org/apache/ofbiz/service/job/PurgeJob.java | 2 +- .../ofbiz/service/rmi/ExampleRemoteClient.java | 2 +- .../service/test/ServiceEngineTestServices.java | 121 ++-- .../ofbiz/service/test/ServiceSOAPTests.java | 2 +- .../java/org/apache/ofbiz/base/start/Start.java | 15 +- .../apache/ofbiz/testtools/SimpleMethodTest.java | 2 +- .../apache/ofbiz/testtools/TestRunContainer.java | 4 +- .../apache/ofbiz/webapp/control/ContextFilter.java | 8 +- .../control/ControlActivationEventListener.java | 2 +- .../apache/ofbiz/webapp/control/JWTManager.java | 2 +- .../apache/ofbiz/webapp/control/LoginWorker.java | 12 +- .../ofbiz/webapp/control/ProtectViewWorker.java | 2 +- .../ofbiz/webapp/control/RequestHandler.java | 510 +++++++++-------- .../org/apache/ofbiz/webapp/event/CoreEvents.java | 55 +- .../webapp/event/RequestBodyMapHandlerFactory.java | 2 +- .../webapp/event/ServiceMultiEventHandler.java | 22 +- .../ofbiz/webapp/event/SimpleEventHandler.java | 4 +- .../ofbiz/webapp/ftl/OfbizContentTransform.java | 2 +- .../apache/ofbiz/webapp/ftl/OfbizUrlTransform.java | 2 +- .../ofbiz/webapp/ftl/SetContextFieldTransform.java | 18 +- .../webapp/ftl/SetRequestAttributeMethod.java | 18 +- .../org/apache/ofbiz/webtools/GenericWebEvent.java | 44 +- .../org/apache/ofbiz/webtools/UtilCacheEvents.java | 38 +- .../apache/ofbiz/webtools/WebToolsServices.java | 4 +- .../artifactinfo/ControllerViewArtifactInfo.java | 4 +- .../apache/ofbiz/widget/model/ModelFormField.java | 16 +- .../org/apache/ofbiz/widget/model/ModelTheme.java | 4 +- .../ofbiz/widget/portal/PortalPageWorker.java | 2 +- .../widget/renderer/ScreenStringRenderer.java | 58 +- .../widget/renderer/fo/ScreenFopViewHandler.java | 4 +- .../widget/renderer/html/HtmlMenuRenderer.java | 2 +- .../widget/renderer/macro/MacroFormRenderer.java | 67 ++- 119 files changed, 2064 insertions(+), 1604 deletions(-) diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentResourceHandler.java b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentResourceHandler.java index 831962d..2be1a32 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentResourceHandler.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentResourceHandler.java @@ -103,9 +103,9 @@ public class ComponentResourceHandler implements ResourceHandler { if (obj instanceof ComponentResourceHandler) { ComponentResourceHandler other = (ComponentResourceHandler) obj; - if (this.loaderName.equals(other.loaderName) && - this.componentName.equals(other.componentName) && - this.location.equals(other.location)) { + if (this.loaderName.equals(other.loaderName) + && this.componentName.equals(other.componentName) + && this.location.equals(other.location)) { return true; } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceHandler.java b/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceHandler.java index 45de39d..0e77cfc 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceHandler.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/config/ResourceHandler.java @@ -30,17 +30,17 @@ import org.w3c.dom.Document; */ public interface ResourceHandler extends Serializable { - public String getLoaderName(); + String getLoaderName(); - public String getLocation(); + String getLocation(); - public Document getDocument() throws GenericConfigException; + Document getDocument() throws GenericConfigException; - public InputStream getStream() throws GenericConfigException; + InputStream getStream() throws GenericConfigException; - public URL getURL() throws GenericConfigException; + URL getURL() throws GenericConfigException; - public boolean isFileResource() throws GenericConfigException; + boolean isFileResource() throws GenericConfigException; - public String getFullLocation() throws GenericConfigException; + String getFullLocation() throws GenericConfigException; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/Container.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/Container.java index 39f654a..579f84d 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/Container.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/Container.java @@ -61,19 +61,19 @@ public interface Container { * @return <code>true</code> if the process started. * @throws ContainerException If an error was encountered. */ - public boolean start() throws ContainerException; + boolean start() throws ContainerException; /** * Stop the container process. This method must not block. * * @throws ContainerException If an error was encountered. */ - public void stop() throws ContainerException; + void stop() throws ContainerException; /** * Return the container name. * * @return Name of the container's instance. */ - public String getName(); + String getName(); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/Converters.java b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/Converters.java index 9c52ad0..78d46a4 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/Converters.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/Converters.java @@ -74,7 +74,7 @@ public class Converters { if (Debug.verboseOn()) { Debug.logVerbose("Getting converter: " + key, MODULE); } -OUTER: + OUTER: do { Converter<?, ?> result = converterMap.get(key); if (result != null) { @@ -113,10 +113,10 @@ OUTER: addedToSet = noConversions.add(key); } if (addedToSet) { - Debug.logWarning("*** No converter found, converting from " + - sourceClass.getName() + " to " + targetClass.getName() + - ". Please report this message to the developer community so " + - "a suitable converter can be created. ***", MODULE); + Debug.logWarning("*** No converter found, converting from " + + sourceClass.getName() + " to " + targetClass.getName() + + ". Please report this message to the developer community so " + + "a suitable converter can be created. ***", MODULE); } throw new ClassNotFoundException("No converter found for " + key); } while (true); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/LocalizedConverter.java b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/LocalizedConverter.java index 6843849..58f4a34 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/LocalizedConverter.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/LocalizedConverter.java @@ -34,7 +34,7 @@ public interface LocalizedConverter<S, T> extends Converter<S, T> { * @return The converted <code>Object</code> * @throws ConversionException */ - public T convert(S obj, Locale locale, TimeZone timeZone) throws ConversionException; + T convert(S obj, Locale locale, TimeZone timeZone) throws ConversionException; /** Converts <code>obj</code> to <code>T</code>. * @@ -45,7 +45,7 @@ public interface LocalizedConverter<S, T> extends Converter<S, T> { * @return The converted <code>Object</code> * @throws ConversionException */ - public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone) throws ConversionException; + T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone) throws ConversionException; /** Converts <code>obj</code> to <code>T</code>. * @@ -56,7 +56,7 @@ public interface LocalizedConverter<S, T> extends Converter<S, T> { * @return The converted <code>Object</code> * @throws ConversionException */ - public T convert(S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException; + T convert(S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException; /** Converts <code>obj</code> to <code>T</code>. * @@ -68,5 +68,5 @@ public interface LocalizedConverter<S, T> extends Converter<S, T> { * @return The converted <code>Object</code> * @throws ConversionException */ - public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException; + T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/lang/Factory.java b/framework/base/src/main/java/org/apache/ofbiz/base/lang/Factory.java index 734d7ed..f17e45a 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/lang/Factory.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/lang/Factory.java @@ -30,6 +30,6 @@ public interface Factory<R, A> { * or to be used as a selector key * @return An instance of <code>R</code> */ - public R getInstance(A obj); + R getInstance(A obj); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java index ec44a9f..8be2dfe 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java @@ -284,10 +284,10 @@ public class HttpRequestFileUpload { while (((i = in.readLine(buf, off, len)) == -1) && (reqLen > 0)) { Debug.logInfo("waiting", MODULE); if (waitCount > MAX_WAITS) { - Debug.logInfo("waited " + waitCount + " times, bailing out while still expecting " + - reqLen + " bytes.", MODULE); - throw new IOException("waited " + waitCount + " times, bailing out while still expecting " + - reqLen + " bytes."); + Debug.logInfo("waited " + waitCount + " times, bailing out while still expecting " + + reqLen + " bytes.", MODULE); + throw new IOException("waited " + waitCount + " times, bailing out while still expecting " + + reqLen + " bytes."); } waitCount++; long endMS = new Date().getTime() + WAIT_INTERVAL; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java index b32227d..5a05fee 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java @@ -227,24 +227,24 @@ public class ObjectType { try { return loadClass(typeName, loader); } catch (SecurityException se1) { - throw new IllegalArgumentException("Problems with classloader: security exception (" + - se1.getMessage() + ")"); + throw new IllegalArgumentException("Problems with classloader: security exception (" + + se1.getMessage() + ")"); } catch (ClassNotFoundException e1) { try { return loadClass(LANG_PACKAGE + typeName, loader); } catch (SecurityException se2) { - throw new IllegalArgumentException("Problems with classloader: security exception (" + - se2.getMessage() + ")"); + throw new IllegalArgumentException("Problems with classloader: security exception (" + + se2.getMessage() + ")"); } catch (ClassNotFoundException e2) { try { return loadClass(SQL_PACKAGE + typeName, loader); } catch (SecurityException se3) { - throw new IllegalArgumentException("Problems with classloader: security exception (" + - se3.getMessage() + ")"); + throw new IllegalArgumentException("Problems with classloader: security exception (" + + se3.getMessage() + ")"); } catch (ClassNotFoundException e3) { - throw new IllegalArgumentException("Cannot find and load the class of type: " + typeName + - " or of type: " + LANG_PACKAGE + typeName + " or of type: " + SQL_PACKAGE + typeName + - ": (" + e3.getMessage() + ")"); + throw new IllegalArgumentException("Cannot find and load the class of type: " + typeName + + " or of type: " + LANG_PACKAGE + typeName + " or of type: " + SQL_PACKAGE + typeName + + ": (" + e3.getMessage() + ")"); } } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java index 36a6950..5d8f941 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java @@ -38,7 +38,6 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509KeyManager; @@ -170,11 +169,11 @@ public final class SSLUtil { } } - return new TrustManager[] { tm }; + return new TrustManager[] {tm }; } public static TrustManager[] getTrustAnyManagers() { - return new TrustManager[] { new TrustAnyManager() }; + return new TrustManager[] {new TrustAnyManager() }; } public static KeyManager[] getKeyManagers(KeyStore ks, String password, String alias) throws GeneralSecurityException { @@ -192,14 +191,16 @@ public final class SSLUtil { } public static TrustManager[] getTrustManagers(KeyStore ks) { - return new TrustManager[] { new MultiTrustManager(ks) }; + return new TrustManager[] {new MultiTrustManager(ks) }; } - public static SSLSocketFactory getSSLSocketFactory(KeyStore ks, String password, String alias) throws IOException, GeneralSecurityException, GenericConfigException { + public static SSLSocketFactory getSSLSocketFactory(KeyStore ks, String password, String alias) + throws IOException, GeneralSecurityException, GenericConfigException { return getSSLContext(ks, password, alias, false).getSocketFactory(); } - public static SSLContext getSSLContext(KeyStore ks, String password, String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException { + public static SSLContext getSSLContext(KeyStore ks, String password, String alias, boolean trustAny) + throws IOException, GeneralSecurityException, GenericConfigException { KeyManager[] km = SSLUtil.getKeyManagers(ks, password, alias); TrustManager[] tm; if (trustAny) { @@ -213,7 +214,8 @@ public final class SSLUtil { return context; } - public static SSLSocketFactory getSSLSocketFactory(String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException { + public static SSLSocketFactory getSSLSocketFactory(String alias, boolean trustAny) + throws IOException, GeneralSecurityException, GenericConfigException { return getSSLContext(alias, trustAny).getSocketFactory(); } @@ -239,11 +241,13 @@ public final class SSLUtil { return getSSLSocketFactory(null); } - public static SSLServerSocketFactory getSSLServerSocketFactory(KeyStore ks, String password, String alias) throws IOException, GeneralSecurityException, GenericConfigException { + public static SSLServerSocketFactory getSSLServerSocketFactory(KeyStore ks, String password, String alias) + throws IOException, GeneralSecurityException, GenericConfigException { return getSSLContext(ks, password, alias, false).getServerSocketFactory(); } - public static SSLServerSocketFactory getSSLServerSocketFactory(String alias) throws IOException, GeneralSecurityException, GenericConfigException { + public static SSLServerSocketFactory getSSLServerSocketFactory(String alias) + throws IOException, GeneralSecurityException, GenericConfigException { return getSSLContext(alias, false).getServerSocketFactory(); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java index f2fc4fd..3fb3f17 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java @@ -52,7 +52,7 @@ public class UtilCodec { private static final StringEncoder stringEncoder = new StringEncoder(); private static final UrlCodec urlCodec = new UrlCodec(); private static final List<Codec> codecs; - // From https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Event_Handlers + // From https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Event_Handlers private static final List<String> jsEventList = Arrays.asList(new String[] {"onAbort", "onActivate", "onAfterPrint", "onAfterUpdate", "onBeforeActivate", "onBeforeCopy", "onBeforeCut", "onBeforeDeactivate", "onBeforeEditFocus", "onBeforePaste", "onBeforePrint", "onBeforeUnload", "onBeforeUpdate", "onBegin", @@ -448,7 +448,7 @@ public class UtilCodec { /** * This method check if the input is safe HTML. * It is possible to configure a safe policy using the properties - * "sanitizer.safe.policy" and "sanitizer.custom.safe.policy.class". + * "sanitizer.safe.policy" and "sanitizer.custom.safe.policy.class". * The safe policy has to implement * {@link org.apache.ofbiz.base.html.SanitizerCustomPolicy}. * @@ -502,7 +502,7 @@ public class UtilCodec { } /** - * A simple Map wrapper class that will do HTML encoding. + * A simple Map wrapper class that will do HTML encoding. * To be used for passing a Map to something that will expand Strings with it as a context, etc. */ public static class HtmlEncodingMapWrapper<K> implements Map<K, Object> { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java index 8b12610..5f68a18 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java @@ -70,19 +70,19 @@ public final class UtilFormatOut { //Resolve template to use from formatType String formatTypeKey = formatType + ".displaying.format"; - String template = delegator != null ? - EntityUtilProperties.getPropertyValue("number", formatTypeKey, delegator): - UtilProperties.getPropertyValue("number", formatTypeKey); + String template = delegator != null + ? EntityUtilProperties.getPropertyValue("number", formatTypeKey, delegator) + : UtilProperties.getPropertyValue("number", formatTypeKey); if (UtilValidate.isEmpty(template)) { - Debug.logWarning("Number template not found for format " + formatType + - ", please check your property on number for " + formatTypeKey, MODULE); - template = delegator != null ? - EntityUtilProperties.getPropertyValue("number", "default.displaying.format", delegator): - UtilProperties.getPropertyValue("number", "default.displaying.format"); + Debug.logWarning("Number template not found for format " + formatType + + ", please check your property on number for " + formatTypeKey, MODULE); + template = delegator != null + ? EntityUtilProperties.getPropertyValue("number", "default.displaying.format", delegator) + : UtilProperties.getPropertyValue("number", "default.displaying.format"); } if (UtilValidate.isEmpty(template)) { - Debug.logWarning("Number template not found for default displaying.format" + - ", please check your property on number for default.displaying.format", MODULE); + Debug.logWarning("Number template not found for default displaying.format" + + ", please check your property on number for default.displaying.format", MODULE); template = "##0.00"; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java index de23af1..342583c 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java @@ -126,7 +126,7 @@ public final class UtilHttp { * <p> * If parameters are empty, the multi-part parameter map will be used. * - * @param request the HTTP request containing the parameters + * @param request the HTTP request containing the parameters * @return a canonicalized parameter map. */ public static Map<String, Object> getParameterMap(HttpServletRequest request) { @@ -139,7 +139,7 @@ public final class UtilHttp { * If parameters are empty, the multi-part parameter map will be used. * * @param req the HTTP request containing the parameters - * @param pred the predicate filtering the parameter names + * @param pred the predicate filtering the parameter names * @return a canonicalized parameter map. */ public static Map<String, Object> getParameterMap(HttpServletRequest req, Predicate<String> pred) { @@ -168,7 +168,7 @@ public final class UtilHttp { * <p> * This is meant to facilitate the work of request handlers. * - * @param value the array of string to prepare + * @param value the array of string to prepare * @return the adapted value. * @throws NullPointerException when {@code value} is {@code null}. */ @@ -207,7 +207,7 @@ public final class UtilHttp { } if (uploadedItems != null) { request.setAttribute("fileItems", uploadedItems); - for (FileItem item: uploadedItems) { + for (FileItem item : uploadedItems) { String fieldName = item.getFieldName(); //byte[] itemBytes = item.get(); /* @@ -322,7 +322,8 @@ public final class UtilHttp { while (queryTokens.hasMoreTokens()) { String token = queryTokens.nextToken(); if (token.startsWith("amp;")) { - // this is most likely a split value that had an & in it, so don't consider this a name; note that some old code just stripped the "amp;" and went with it + // this is most likely a split value that had an & in it, so don't consider this a name; note that some old code just + // stripped the "amp;" and went with it continue; } int equalsIndex = token.indexOf("="); @@ -352,13 +353,13 @@ public final class UtilHttp { * path parameters are denoted by "/~KEY0=VALUE0/~KEY1=VALUE1/". * This is an obsolete syntax for passing parameters to request handlers. * - * @param path the URI path part which can be {@code null} - * @param pred the predicate filtering parameter names + * @param path the URI path part which can be {@code null} + * @param pred the predicate filtering parameter names * @return a canonicalized parameter map. */ static Map<String, Object> getPathInfoOnlyParameterMap(String path, Predicate<String> pred) { - String path$ = Optional.ofNullable(path).orElse(""); - Map<String, List<String>> allParams = Arrays.stream(path$.split("/")) + String path1 = Optional.ofNullable(path).orElse(""); + Map<String, List<String>> allParams = Arrays.stream(path1.split("/")) .filter(segment -> segment.startsWith("~") && segment.contains("=")) .map(kv -> kv.substring(1).split("=")) .collect(groupingBy(kv -> kv[0], mapping(kv -> kv[1], toList()))); @@ -379,12 +380,12 @@ public final class UtilHttp { } public static Map<String, Object> canonicalizeParameterMap(Map<String, Object> paramMap) { - for (Map.Entry<String, Object> paramEntry: paramMap.entrySet()) { + for (Map.Entry<String, Object> paramEntry : paramMap.entrySet()) { if (paramEntry.getValue() instanceof String) { paramEntry.setValue(canonicalizeParameter((String) paramEntry.getValue())); } else if (paramEntry.getValue() instanceof Collection<?>) { List<String> newList = new LinkedList<>(); - for (String listEntry: UtilGenerics.<Collection<String>>cast(paramEntry.getValue())) { + for (String listEntry : UtilGenerics.<Collection<String>>cast(paramEntry.getValue())) { newList.add(canonicalizeParameter(listEntry)); } paramEntry.setValue(newList); @@ -395,10 +396,12 @@ public final class UtilHttp { public static String canonicalizeParameter(String paramValue) { try { - /** calling canonicalize with strict flag set to false so we only get warnings about double encoding, etc; can be set to true for exceptions and more security */ + /** calling canonicalize with strict flag set to false so we only get warnings about double encoding, etc; can be set to true for + * exceptions and more security */ String cannedStr = UtilCodec.canonicalize(paramValue, false); if (Debug.verboseOn()) { - Debug.logVerbose("Canonicalized parameter with " + (cannedStr.equals(paramValue) ? "no " : "") + "change: original [" + paramValue + "] canned [" + cannedStr + "]", MODULE); + Debug.logVerbose("Canonicalized parameter with " + (cannedStr.equals(paramValue) ? "no " : "") + "change: original [" + + paramValue + "] canned [" + cannedStr + "]", MODULE); } return cannedStr; } catch (Exception e) { @@ -409,6 +412,7 @@ public final class UtilHttp { /** * Create a map from a HttpRequest (attributes) object used in JSON requests + * * @return The resulting Map */ public static Map<String, Object> getJSONAttributeMap(HttpServletRequest request) { @@ -433,6 +437,7 @@ public final class UtilHttp { /** * Create a map from a HttpRequest (attributes) object + * * @return The resulting Map */ public static Map<String, Object> getAttributeMap(HttpServletRequest request) { @@ -441,6 +446,7 @@ public final class UtilHttp { /** * Create a map from a HttpRequest (attributes) object + * * @return The resulting Map */ public static Map<String, Object> getAttributeMap(HttpServletRequest request, Set<? extends String> namesToSkip) { @@ -468,6 +474,7 @@ public final class UtilHttp { /** * Create a map from a HttpSession object + * * @return The resulting Map */ public static Map<String, Object> getSessionMap(HttpServletRequest request) { @@ -476,6 +483,7 @@ public final class UtilHttp { /** * Create a map from a HttpSession object + * * @return The resulting Map */ public static Map<String, Object> getSessionMap(HttpServletRequest request, Set<? extends String> namesToSkip) { @@ -504,6 +512,7 @@ public final class UtilHttp { /** * Create a map from a ServletContext object + * * @return The resulting Map */ public static Map<String, Object> getServletContextMap(HttpServletRequest request) { @@ -512,6 +521,7 @@ public final class UtilHttp { /** * Create a map from a ServletContext object + * * @return The resulting Map */ public static Map<String, Object> getServletContextMap(HttpServletRequest request, Set<? extends String> namesToSkip) { @@ -531,7 +541,8 @@ public final class UtilHttp { if (Debug.verboseOn()) { Debug.logVerbose("Made ServletContext Attribute Map with [" + servletCtxMap.size() + "] Entries", MODULE); - Debug.logVerbose("ServletContext Attribute Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(servletCtxMap), MODULE); + Debug.logVerbose("ServletContext Attribute Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(servletCtxMap), + MODULE); } return servletCtxMap; @@ -541,13 +552,15 @@ public final class UtilHttp { return makeParamMapWithPrefix(request, null, prefix, suffix); } - public static Map<String, Object> makeParamMapWithPrefix(HttpServletRequest request, Map<String, ? extends Object> additionalFields, String prefix, String suffix) { + public static Map<String, Object> makeParamMapWithPrefix(HttpServletRequest request, Map<String, ? extends Object> additionalFields, + String prefix, String suffix) { return makeParamMapWithPrefix(getCombinedMap(request), additionalFields, prefix, suffix); } - public static Map<String, Object> makeParamMapWithPrefix(Map<String, ? extends Object> context, Map<String, ? extends Object> additionalFields, String prefix, String suffix) { + public static Map<String, Object> makeParamMapWithPrefix(Map<String, ? extends Object> context, Map<String, ? extends Object> additionalFields, + String prefix, String suffix) { Map<String, Object> paramMap = new HashMap<>(); - for (Map.Entry<String, ? extends Object> entry: context.entrySet()) { + for (Map.Entry<String, ? extends Object> entry : context.entrySet()) { String parameterName = entry.getKey(); if (parameterName.startsWith(prefix)) { if (UtilValidate.isNotEmpty(suffix)) { @@ -574,7 +587,7 @@ public final class UtilHttp { } } if (additionalFields != null) { - for (Map.Entry<String, ? extends Object> entry: additionalFields.entrySet()) { + for (Map.Entry<String, ? extends Object> entry : additionalFields.entrySet()) { String fieldName = entry.getKey(); if (fieldName.startsWith(prefix)) { if (UtilValidate.isNotEmpty(suffix)) { @@ -639,7 +652,7 @@ public final class UtilHttp { /** * Constructs a list of parameter values whose keys are matching a given prefix and suffix. * - * @param request the HTTP request containing the parameters + * @param request the HTTP request containing the parameters * @param suffix the suffix that must be matched which can be {@code null} * @param prefix the prefix that must be matched which can be {@code null} * @return the list of parameter values whose keys are matching {@code prefix} and {@code suffix}. @@ -652,15 +665,15 @@ public final class UtilHttp { /** * Constructs a list of parameter values whose keys are matching a given prefix and suffix. * - * @param request the HTTP request containing the parameters - * @param additionalFields the additional parameters - * @param suffix the suffix that must be matched which can be {@code null} - * @param prefix the prefix that must be matched which can be {@code null} + * @param request the HTTP request containing the parameters + * @param additionalFields the additional parameters + * @param suffix the suffix that must be matched which can be {@code null} + * @param prefix the prefix that must be matched which can be {@code null} * @return the list of parameter values whose keys are matching {@code prefix} and {@code suffix}. * @throws NullPointerException when {@code request} or {@code additionalFields} are {@code null}. */ public static List<Object> makeParamListWithSuffix(HttpServletRequest request, Map<String, ?> additionalFields, - String suffix, String prefix) { + String suffix, String prefix) { Objects.requireNonNull(request); Objects.requireNonNull(additionalFields); Predicate<Map.Entry<String, ?>> pred = UtilValidate.isEmpty(prefix) @@ -680,6 +693,7 @@ public final class UtilHttp { /** * Given a request, returns the application name or "root" if deployed on root + * * @param request An HttpServletRequest to get the name info from * @return String */ @@ -690,7 +704,7 @@ public final class UtilHttp { } // When you set a mountpoint which contains a slash inside its name (ie not only a slash as a trailer, which is possible), // as it's needed with OFBIZ-10765, OFBiz tries to create a cookie with a slash in its name and that's impossible. - return appName.replaceAll("/","_"); + return appName.replaceAll("/", "_"); } public static void setInitialRequestInfo(HttpServletRequest request) { @@ -737,15 +751,16 @@ public final class UtilHttp { return requestUrl.toString(); } - /** Resolve the method send with the request. - * check first the parameter _method before return the request method + /** + * Resolve the method send with the request. + * check first the parameter _method before return the request method + * * @param request * @return */ public static String getRequestMethod(HttpServletRequest request) { - return request.getParameter("_method") != null ? - request.getParameter("_method") : - request.getMethod(); + return request.getParameter("_method") != null + ? request.getParameter("_method") : request.getMethod(); } public static Locale getLocale(HttpServletRequest request, HttpSession session, Object appDefaultLocale) { @@ -779,6 +794,7 @@ public final class UtilHttp { /** * Get the Locale object from a session variable; if not found use the browser's default + * * @param request HttpServletRequest object to use for lookup * @return Locale The current Locale to use */ @@ -792,6 +808,7 @@ public final class UtilHttp { /** * Get the Locale object from a session variable; if not found use the system's default. * NOTE: This method is not recommended because it ignores the Locale from the browser not having the request object. + * * @param session HttpSession object to use for lookup * @return Locale The current Locale to use */ @@ -878,21 +895,25 @@ public final class UtilHttp { /** * Return the VisualTheme object from the user session + * * @param request * @return */ public static VisualTheme getVisualTheme(HttpServletRequest request) { return (VisualTheme) request.getSession().getAttribute(SESSION_KEY_THEME); } + public static void setVisualTheme(HttpServletRequest request, VisualTheme visualTheme) { setVisualTheme(request.getSession(), visualTheme); } + public static void setVisualTheme(HttpSession session, VisualTheme visualTheme) { session.setAttribute(SESSION_KEY_THEME, visualTheme); } /** * Get the currency string from the session. + * * @param session HttpSession object to use for lookup * @return String The ISO currency code */ @@ -938,6 +959,7 @@ public final class UtilHttp { /** * Get the currency string from the session. + * * @param request HttpServletRequest object to use for lookup * @return String The ISO currency code */ @@ -945,7 +967,9 @@ public final class UtilHttp { return getCurrencyUom(request.getSession(), null); } - /** Simple event to set the users per-session currency uom value */ + /** + * Simple event to set the users per-session currency uom value + */ public static void setCurrencyUom(HttpSession session, String currencyUom) { session.setAttribute("currencyUom", currencyUom); } @@ -956,21 +980,27 @@ public final class UtilHttp { } } - /** URL Encodes a Map of arguments */ + /** + * URL Encodes a Map of arguments + */ public static String urlEncodeArgs(Map<String, ? extends Object> args) { return urlEncodeArgs(args, true); } - /** URL Encodes a Map of arguments */ + /** + * URL Encodes a Map of arguments + */ public static String urlEncodeArgs(Map<String, ? extends Object> args, boolean useExpandedEntites) { return urlEncodeArgs(args, useExpandedEntites, false); } - /** URL Encodes a Map of arguments */ + /** + * URL Encodes a Map of arguments + */ public static String urlEncodeArgs(Map<String, ? extends Object> args, boolean useExpandedEntites, boolean preserveEmpty) { StringBuilder buf = new StringBuilder(); if (args != null) { - for (Map.Entry<String, ? extends Object> entry: args.entrySet()) { + for (Map.Entry<String, ? extends Object> entry : args.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (preserveEmpty && value == null) { @@ -992,7 +1022,7 @@ public final class UtilHttp { } String valueStr = null; - for (Object colValue: col) { + for (Object colValue : col) { if (colValue instanceof String) { valueStr = (String) colValue; } else if (colValue == null) { @@ -1037,8 +1067,10 @@ public final class UtilHttp { return requestUri; } - /** Returns the query string contained in a request target - basically everything + /** + * Returns the query string contained in a request target - basically everything * after and including the ? character. + * * @param target The request target * @return The query string */ @@ -1053,8 +1085,10 @@ public final class UtilHttp { return ""; } - /** Removes the query string from a request target - basically everything + /** + * Removes the query string from a request target - basically everything * after and including the ? character. + * * @param target The request target * @return The request target string */ @@ -1090,7 +1124,8 @@ public final class UtilHttp { StringBuilder htmlBuffer = new StringBuilder(htmlString); int ampLoc = -1; while ((ampLoc = htmlBuffer.indexOf("&", ampLoc + 1)) != -1) { - //NOTE: this should work fine, but if it doesn't could try making sure all characters between & and ; are letters, that would qualify as an entity + //NOTE: this should work fine, but if it doesn't could try making sure all characters between & and ; are letters, that would qualify + // as an entity // found ampersand, is it already and entity? if not change it to & int semiLoc = htmlBuffer.indexOf(";", ampLoc); @@ -1150,18 +1185,22 @@ public final class UtilHttp { resp.addHeader("strict-transport-security", strictTransportSecurity); } } else { - if (EntityUtilProperties.getPropertyAsBoolean("requestHandler", "strict-transport-security", true)) { // FIXME later pass req.getAttribute("delegator") as last argument + if (EntityUtilProperties.getPropertyAsBoolean("requestHandler", "strict-transport-security", true)) { // FIXME later pass req + // .getAttribute("delegator") as last argument resp.addHeader("strict-transport-security", "max-age=31536000; includeSubDomains"); } } - /** The only x-content-type-options defined value, "nosniff", prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. + /** The only x-content-type-options defined value, "nosniff", prevents Internet Explorer from MIME-sniffing a response away from the + * declared content-type. This also applies to Google Chrome, when downloading extensions. */ resp.addHeader("x-content-type-options", "nosniff"); - /** This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. - It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. - This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header. + /** This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. + It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was + disabled by the user. + This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that + version honored this header. FireFox has still an open bug entry and "offers" only the noscript plugin https://wiki.mozilla.org/Security/Features/XSS_Filter https://bugzilla.mozilla.org/show_bug.cgi?id=528661 @@ -1170,9 +1209,10 @@ public final class UtilHttp { resp.setHeader("Referrer-Policy", "no-referrer-when-downgrade"); // This is the default (in Firefox at least) resp.setHeader("Content-Security-Policy-Report-Only", "default-src 'self'"); SameSiteFilter.addSameSiteCookieAttribute(resp); - // TODO in custom project. Public-Key-Pins-Report-Only is interesting but can't be used OOTB because of demos (the letsencrypt certificate is renewed every 3 months) + // TODO in custom project. Public-Key-Pins-Report-Only is interesting but can't be used OOTB because of demos (the letsencrypt certificate + // is renewed every 3 months) } - + public static String getContentTypeByFileName(String fileName) { FileNameMap mime = URLConnection.getFileNameMap(); @@ -1183,10 +1223,10 @@ public final class UtilHttp { * Stream an array of bytes to the browser * This method will close the ServletOutputStream when finished * - * @param response HttpServletResponse object to get OutputStream from - * @param bytes Byte array of content to stream + * @param response HttpServletResponse object to get OutputStream from + * @param bytes Byte array of content to stream * @param contentType The content type to pass to the browser - * @param fileName the fileName to tell the browser we are downloading + * @param fileName the fileName to tell the browser we are downloading * @throws IOException */ public static void streamContentToBrowser(HttpServletResponse response, byte[] bytes, String contentType, String fileName) throws IOException { @@ -1223,13 +1263,14 @@ public final class UtilHttp { * This method will close the ServletOutputStream when finished * This method does not close the InputSteam passed * - * @param response HttpServletResponse object to get OutputStream from - * @param in InputStream of the actual content - * @param length Size (in bytes) of the content + * @param response HttpServletResponse object to get OutputStream from + * @param in InputStream of the actual content + * @param length Size (in bytes) of the content * @param contentType The content type to pass to the browser * @throws IOException */ - public static void streamContentToBrowser(HttpServletResponse response, InputStream in, int length, String contentType, String fileName) throws IOException { + public static void streamContentToBrowser(HttpServletResponse response, InputStream in, int length, String contentType, String fileName) + throws IOException { // tell the browser not the cache setResponseBrowserProxyNoCache(response); @@ -1259,8 +1300,8 @@ public final class UtilHttp { * Stream binary content from InputStream to OutputStream * This method does not close the streams passed * - * @param out OutputStream content should go to - * @param in InputStream of the actual content + * @param out OutputStream content should go to + * @param in InputStream of the actual content * @param length Size (in bytes) of the content * @throws IOException */ @@ -1285,7 +1326,7 @@ public final class UtilHttp { byte[] buffer = new byte[bufferSize]; int read = 0; try (BufferedOutputStream bos = new BufferedOutputStream(out, bufferSize); - BufferedInputStream bis = new BufferedInputStream(in, bufferSize)) { + BufferedInputStream bis = new BufferedInputStream(in, bufferSize)) { while ((read = bis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, read); } @@ -1450,7 +1491,7 @@ public final class UtilHttp { * with a value of "Timestamp". where "_c_" is the {@link #COMPOSITE_DELIMITER}. These parameters will then be * re-composed into a Timestamp object from the composite fields. * - * @param request the HTTP request containing the parameters + * @param request the HTTP request containing the parameters * @param prefix the string identifying the set of parameters that must be composed * @return a composite object from data or {@code null} if not supported or a parsing error occurred. */ @@ -1503,13 +1544,17 @@ public final class UtilHttp { return null; } - /** Obtains the session ID from the request, or "unknown" if no session pressent. */ + /** + * Obtains the session ID from the request, or "unknown" if no session pressent. + */ public static String getSessionId(HttpServletRequest request) { HttpSession session = request.getSession(); return (session == null ? "unknown" : session.getId()); } - /** Returns true if the user has JavaScript enabled. + /** + * Returns true if the user has JavaScript enabled. + * * @param request * @return whether javascript is enabled */ @@ -1519,19 +1564,22 @@ public final class UtilHttp { return javaScriptEnabled != null ? javaScriptEnabled : false; } - /** Returns the number or rows submitted by a multi form. + /** + * Returns the number or rows submitted by a multi form. */ public static int getMultiFormRowCount(HttpServletRequest request) { return getMultiFormRowCount(getParameterMap(request)); } - /** Returns the number or rows submitted by a multi form. + + /** + * Returns the number or rows submitted by a multi form. */ public static int getMultiFormRowCount(Map<String, ?> requestMap) { // The number of multi form rows is computed selecting the maximum index int rowCount = 0; String maxRowIndex = ""; int rowDelimiterLength = MULTI_ROW_DELIMITER.length(); - for (String parameterName: requestMap.keySet()) { + for (String parameterName : requestMap.keySet()) { int rowDelimiterIndex = (parameterName != null ? parameterName.indexOf(MULTI_ROW_DELIMITER) : -1); if (rowDelimiterIndex > 0) { String thisRowIndex = parameterName.substring(rowDelimiterIndex + rowDelimiterLength); @@ -1578,7 +1626,8 @@ public final class UtilHttp { paramMapStore.remove(paramMapId); for (Map.Entry<String, Object> paramEntry : paramMap.entrySet()) { if (request.getAttribute(paramEntry.getKey()) != null) { - Debug.logWarning("Skipped loading parameter [" + paramEntry.getKey() + "] because it would have overwritten a request attribute", MODULE); + Debug.logWarning("Skipped loading parameter [" + paramEntry.getKey() + "] because it would have overwritten a request " + + "attribute", MODULE); continue; } request.setAttribute(paramEntry.getKey(), paramEntry.getValue()); @@ -1589,11 +1638,12 @@ public final class UtilHttp { /** * Returns a unique Id for the current request + * * @param request An HttpServletRequest to get the name info from * @return String */ public static String getNextUniqueId(HttpServletRequest request) { - Integer uniqueIdNumber= (Integer) request.getAttribute("UNIQUE_ID"); + Integer uniqueIdNumber = (Integer) request.getAttribute("UNIQUE_ID"); if (uniqueIdNumber == null) { uniqueIdNumber = 1; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java index 4bb7eba..1c1b95d 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java @@ -572,8 +572,8 @@ public final class UtilMisc { String extension = localeString.substring(6); locale = new Locale(language, country, extension); } else { - Debug.logWarning("Do not know what to do with the localeString [" + localeString + "], should be length 2, 5, or greater than 6, " + - "returning null", MODULE); + Debug.logWarning("Do not know what to do with the localeString [" + localeString + "], should be length 2, 5, or greater than 6, " + + "returning null", MODULE); } return locale; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java index 17502a6..92cd6c2 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java @@ -87,7 +87,7 @@ public class UtilTimer { /** * Creates a string with information including the passed message, the last passed message and the time since the last call, and the time since * the beginning - * + * * @param message * A message to put into the timer String * @param className diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/cache/UtilCache.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/cache/UtilCache.java index 28cfaaf..5fbf02d 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/cache/UtilCache.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/cache/UtilCache.java @@ -70,7 +70,7 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C private static final ConcurrentHashMap<String, UtilCache<?, ?>> utilCacheTable = new ConcurrentHashMap<>(); /** An index number appended to utilCacheTable names when there are conflicts. */ - private final static ConcurrentHashMap<String, AtomicInteger> defaultIndices = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, AtomicInteger> defaultIndices = new ConcurrentHashMap<>(); /** The name of the UtilCache instance, is also the key for the instance in utilCacheTable. */ private final String name; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/FlexibleStringExpander.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/FlexibleStringExpander.java index afd7758..098ae39 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/FlexibleStringExpander.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/FlexibleStringExpander.java @@ -295,7 +295,7 @@ public abstract class FlexibleStringExpander implements Serializable, IsEmpty { String expression = new String(chars, 0, length + offset); int start = expression.indexOf(openBracket, offset); if (start == -1) { - return new FlexibleStringExpander[] { new ConstOffsetElem(chars, offset, length) }; + return new FlexibleStringExpander[] {new ConstOffsetElem(chars, offset, length) }; } int origLen = length; ArrayList<FlexibleStringExpander> strElems = new ArrayList<>(); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/NodeELResolver.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/NodeELResolver.java index 2897a2b..3674a81 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/NodeELResolver.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/NodeELResolver.java @@ -137,7 +137,7 @@ public class NodeELResolver extends ELResolver { } } - private final static boolean isResolvable(Object base) { + private static final boolean isResolvable(Object base) { return base != null && (base instanceof Node || base instanceof NodeImpl); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelFunctions.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelFunctions.java index 1f8f6d5..7768a9b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelFunctions.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelFunctions.java @@ -53,7 +53,8 @@ import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; -/** Implements Unified Expression Language functions. +/** + * Implements Unified Expression Language functions. * <p>Built-in functions are divided into a number of * namespace prefixes:</p> * <table border="1"> @@ -62,11 +63,14 @@ import org.xml.sax.SAXException; * <tr><td><code>date:second(Timestamp, TimeZone, Locale)</code></td><td>Returns the second value of <code>Timestamp</code> (0 - 59).</td></tr> * <tr><td><code>date:minute(Timestamp, TimeZone, Locale)</code></td><td>Returns the minute value of <code>Timestamp</code> (0 - 59).</td></tr> * <tr><td><code>date:hour(Timestamp, TimeZone, Locale)</code></td><td>Returns the hour value of <code>Timestamp</code> (0 - 23).</td></tr> - * <tr><td><code>date:dayOfMonth(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of month value of <code>Timestamp</code> (1 - 31).</td></tr> - * <tr><td><code>date:dayOfWeek(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of week value of <code>Timestamp</code> (Sunday = 1, Saturday = 7).</td></tr> + * <tr><td><code>date:dayOfMonth(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of month value of <code>Timestamp</code> (1 - 31) + * .</td></tr> + * <tr><td><code>date:dayOfWeek(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of week value of <code>Timestamp</code> (Sunday = 1, + * Saturday = 7).</td></tr> * <tr><td><code>date:dayOfYear(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of year value of <code>Timestamp</code>.</td></tr> * <tr><td><code>date:week(Timestamp, TimeZone, Locale)</code></td><td>Returns the week value of <code>Timestamp</code>.</td></tr> - * <tr><td><code>date:month(Timestamp, TimeZone, Locale)</code></td><td>Returns the month value of <code>Timestamp</code> (January = 0, December = 11).</td></tr> + * <tr><td><code>date:month(Timestamp, TimeZone, Locale)</code></td><td>Returns the month value of <code>Timestamp</code> (January = 0, December = + * 11).</td></tr> * <tr><td><code>date:year(Timestamp, TimeZone, Locale)</code></td><td>Returns the year value of <code>Timestamp</code>.</td></tr> * <tr><td><code>date:dayStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of day.</td></tr> * <tr><td><code>date:dayEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of day.</td></tr> @@ -76,11 +80,16 @@ import org.xml.sax.SAXException; * <tr><td><code>date:monthEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of month.</td></tr> * <tr><td><code>date:yearStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of year.</td></tr> * <tr><td><code>date:yearEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of year.</td></tr> - * <tr><td><code>date:dateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> (yyyy-mm-dd).</td></tr> - * <tr><td><code>date:localizedDateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> formatted according to the supplied locale.</td></tr> - * <tr><td><code>date:dateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time <code>String</code> (yyyy-mm-dd hh:mm).</td></tr> - * <tr><td><code>date:localizedDateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time <code>String</code> formatted according to the supplied locale.</td></tr> - * <tr><td><code>date:timeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a time <code>String</code> (hh:mm).</td></tr> + * <tr><td><code>date:dateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> (yyyy-mm-dd) + * .</td></tr> + * <tr><td><code>date:localizedDateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> + * formatted according to the supplied locale.</td></tr> + * <tr><td><code>date:dateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time <code>String</code> + * (yyyy-mm-dd hh:mm).</td></tr> + * <tr><td><code>date:localizedDateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time + * <code>String</code> formatted according to the supplied locale.</td></tr> + * <tr><td><code>date:timeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a time <code>String</code> (hh:mm) + * .</td></tr> * <tr><td><code>date:nowTimestamp()</code></td><td>Returns <code>Timestamp </code> for right now.</td></tr> * <tr><td colspan="2"><b><code>math:</code> maps to <code>java.lang.Math</code></b></td></tr> * <tr><td><code>math:absDouble(double)</code></td><td>Returns the absolute value of a <code>double</code> value.</td></tr> @@ -90,16 +99,21 @@ import org.xml.sax.SAXException; * <tr><td><code>math:acos(double)</code></td><td>Returns the arc cosine of an angle, in the range of 0.0 through <i>pi</i>.</td></tr> * <tr><td><code>math:asin(double)</code></td><td>Returns the arc sine of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2.</td></tr> * <tr><td><code>math:atan(double)</code></td><td>Returns the arc tangent of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2.</td></tr> - * <tr><td><code>math:atan2(double, double)</code></td><td>Converts rectangular coordinates (<code>x</code>, <code>y</code>) to polar (r, <i>theta</i>).</td></tr> + * <tr><td><code>math:atan2(double, double)</code></td><td>Converts rectangular coordinates (<code>x</code>, <code>y</code>) to polar (r, + * <i>theta</i>).</td></tr> * <tr><td><code>math:cbrt(double)</code></td><td>Returns the cube root of a <code>double</code> value.</td></tr> - * <tr><td><code>math:ceil(double)</code></td><td>Returns the smallest (closest to negative infinity) <code>double</code> value that is greater than or equal to the argument and is equal to a mathematical integer.</td></tr> + * <tr><td><code>math:ceil(double)</code></td><td>Returns the smallest (closest to negative infinity) <code>double</code> value that is greater + * than or equal to the argument and is equal to a mathematical integer.</td></tr> * <tr><td><code>math:cos(double)</code></td><td>Returns the trigonometric cosine of an angle.</td></tr> * <tr><td><code>math:cosh(double)</code></td><td>Returns the hyperbolic cosine of a <code>double</code> value.</td></tr> * <tr><td><code>math:exp(double)</code></td><td>Returns Euler's number <i>e</i> raised to the power of a <code>double</code> value.</td></tr> * <tr><td><code>math:expm1(double)</code></td><td>Returns <i>e</i><sup>x</sup> -1.</td></tr> - * <tr><td><code>math:floor(double)</code></td><td>Returns the largest (closest to positive infinity) <code>double</code> value that is less than or equal to the argument and is equal to a mathematical integer.</td></tr> - * <tr><td><code>math:hypot(double, double)</code></td><td>Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) without intermediate overflow or underflow.</td></tr> - * <tr><td><code>math:IEEEremainder(double, double)</code></td><td>Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.</td></tr> + * <tr><td><code>math:floor(double)</code></td><td>Returns the largest (closest to positive infinity) <code>double</code> value that is less than + * or equal to the argument and is equal to a mathematical integer.</td></tr> + * <tr><td><code>math:hypot(double, double)</code></td><td>Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) without intermediate + * overflow or underflow.</td></tr> + * <tr><td><code>math:IEEEremainder(double, double)</code></td><td>Computes the remainder operation on two arguments as prescribed by the IEEE 754 + * standard.</td></tr> * <tr><td><code>math:log(double)</code></td><td>Returns the natural logarithm (base <i>e</i>) of a <code>double</code> value.</td></tr> * <tr><td><code>math:log10(double)</code></td><td>Returns the base 10 logarithm of a <code>double</code> value.</td></tr> * <tr><td><code>math:log1p(double)</code></td><td>Returns the natural logarithm of the sum of the argument and 1.</td></tr> @@ -112,35 +126,50 @@ import org.xml.sax.SAXException; * <tr><td><code>math:minInt(int, int)</code></td><td>Returns the smaller of two <code>int</code> values.</td></tr> * <tr><td><code>math:minLong(long, long)</code></td><td>Returns the smaller of two <code>long</code> values.</td></tr> * <tr><td><code>math:pow(double, double)</code></td><td>Returns the value of the first argument raised to the power of the second argument.</td></tr> - * <tr><td><code>math:random()</code></td><td>Returns a <code>double</code> value with a positive sign, greater than or equal to <code>0.0</code> and less than <code>1.0</code>.</td></tr> - * <tr><td><code>math:rint(double)</code></td><td>Returns the <code>double</code> value that is closest in value to the argument and is equal to a mathematical integer.</td></tr> + * <tr><td><code>math:random()</code></td><td>Returns a <code>double</code> value with a positive sign, greater than or equal to <code>0.0</code> + * and less than <code>1.0</code>.</td></tr> + * <tr><td><code>math:rint(double)</code></td><td>Returns the <code>double</code> value that is closest in value to the argument and is equal to a + * mathematical integer.</td></tr> * <tr><td><code>math:roundDouble(double)</code></td><td>Returns the closest <code>long</code> to the argument.</td></tr> * <tr><td><code>math:roundFloat(float)</code></td><td>Returns the closest <code>int</code> to the argument.</td></tr> - * <tr><td><code>math:signumDouble(double)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.</td></tr> - * <tr><td><code>math:signumFloat(float)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.</td></tr> + * <tr><td><code>math:signumDouble(double)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0 if the + * argument is greater than zero, -1.0 if the argument is less than zero.</td></tr> + * <tr><td><code>math:signumFloat(float)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0f if the + * argument is greater than zero, -1.0f if the argument is less than zero.</td></tr> * <tr><td><code>math:sin(double)</code></td><td>Returns the trigonometric sine of an angle.</td></tr> * <tr><td><code>math:sinh(double)</code></td><td>Returns the hyperbolic sine of a <code>double</code> value.</td></tr> * <tr><td><code>math:sqrt(double)</code></td><td>Returns the correctly rounded positive square root of a <code>double</code> value.</td></tr> * <tr><td><code>math:tan(double)</code></td><td>Returns the trigonometric tangent of an angle.</td></tr> * <tr><td><code>math:tanh(double)</code></td><td>Returns the hyperbolic tangent of a <code>double</code> value.</td></tr> - * <tr><td><code>math:toDegrees(double)</code></td><td>Converts an angle measured in radians to an approximately equivalent angle measured in degrees.</td></tr> - * <tr><td><code>math:toRadians(double)</code></td><td>Converts an angle measured in degrees to an approximately equivalent angle measured in radians.</td></tr> + * <tr><td><code>math:toDegrees(double)</code></td><td>Converts an angle measured in radians to an approximately equivalent angle measured in + * degrees.</td></tr> + * <tr><td><code>math:toRadians(double)</code></td><td>Converts an angle measured in degrees to an approximately equivalent angle measured in + * radians.</td></tr> * <tr><td><code>math:ulpDouble(double)</code></td><td>Returns the size of an ulp (units in the last place) of the argument.</td></tr> * <tr><td><code>math:ulpFloat(float)</code></td><td>Returns the size of an ulp (units in the last place) of the argument.</td></tr> * <tr><td colspan="2"><b><code>str:</code> maps to <code>java.lang.String</code></b></td></tr> * <tr><td><code>str:endsWith(String, String)</code></td><td>Returns <code>true</code> if this string ends with the specified suffix.</td></tr> - * <tr><td><code>str:indexOf(String, String)</code></td><td>Returns the index within this string of the first occurrence of the specified substring.</td></tr> - * <tr><td><code>str:lastIndexOf(String, String)</code></td><td>Returns the index within this string of the last occurrence of the specified character.</td></tr> + * <tr><td><code>str:indexOf(String, String)</code></td><td>Returns the index within this string of the first occurrence of the specified substring + * .</td></tr> + * <tr><td><code>str:lastIndexOf(String, String)</code></td><td>Returns the index within this string of the last occurrence of the specified + * character.</td></tr> * <tr><td><code>str:length(String)</code></td><td>Returns the length of this string.</td></tr> - * <tr><td><code>str:replace(String, String, String)</code></td><td>Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.</td></tr> - * <tr><td><code>str:replaceAll(String, String, String)</code></td><td>Replaces each substring of this string that matches the given regular expression with the given replacement.</td></tr> - * <tr><td><code>str:replaceFirst(String, String, String)</code></td><td>Replaces the first substring of this string that matches the given regular expression with the given replacement.</td></tr> + * <tr><td><code>str:replace(String, String, String)</code></td><td>Replaces each substring of this string that matches the literal target sequence + * with the specified literal replacement sequence.</td></tr> + * <tr><td><code>str:replaceAll(String, String, String)</code></td><td>Replaces each substring of this string that matches the given regular + * expression with the given replacement.</td></tr> + * <tr><td><code>str:replaceFirst(String, String, String)</code></td><td>Replaces the first substring of this string that matches the given regular + * expression with the given replacement.</td></tr> * <tr><td><code>str:startsWith(String, String)</code></td><td>Returns <code>true</code> if this string starts with the specified prefix.</td></tr> - * <tr><td><code>str:endstring(String, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.</td></tr> - * <tr><td><code>str:substring(String, int, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.</td></tr> - * <tr><td><code>str:toLowerCase(String)</code></td><td>Converts all of the characters in this String to lower case using the rules of the default locale.</td></tr> + * <tr><td><code>str:endstring(String, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins with the + * character at the specified index and extends to the end of this string.</td></tr> + * <tr><td><code>str:substring(String, int, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins at + * the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.</td></tr> + * <tr><td><code>str:toLowerCase(String)</code></td><td>Converts all of the characters in this String to lower case using the rules of the default + * locale.</td></tr> * <tr><td><code>str:toString(Object)</code></td><td>Converts <code>Object</code> to a <code>String</code> - bypassing localization.</td></tr> - * <tr><td><code>str:toUpperCase(String)</code></td><td>Converts all of the characters in this String to upper case using the rules of the default locale.</td></tr> + * <tr><td><code>str:toUpperCase(String)</code></td><td>Converts all of the characters in this String to upper case using the rules of the default + * locale.</td></tr> * <tr><td><code>str:trim(String)</code></td><td>Returns a copy of the string, with leading and trailing whitespace omitted.</td></tr> * <tr><td colspan="2"><b><code>sys:</code> maps to <code>java.lang.System</code></b></td></tr> * <tr><td><code>sys:getenv(String)</code></td><td>Gets the value of the specified environment variable.</td></tr> @@ -155,134 +184,33 @@ import org.xml.sax.SAXException; * <tr><td colspan="2"><b><code>dom:</code> contains <code>org.w3c.dom.*</code> functions</b></td></tr> * <tr><td><code>dom:readHtmlDocument(String)</code></td><td>Reads an HTML file and returns a <code>org.w3c.dom.Document</code> instance.</td></tr> * <tr><td><code>dom:readXmlDocument(String)</code></td><td>Reads an XML file and returns a <code>org.w3c.dom.Document</code> instance.</td></tr> - * <tr><td><code>dom:toHtmlString(Node, String encoding, boolean indent, int indentAmount)</code></td><td>Returns a <code>org.w3c.dom.Node</code> as an HTML <code>String</code>.</td></tr> - * <tr><td><code>dom:toXmlString(Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount)</code></td><td>Returns a <code>org.w3c.dom.Node</code> as an XML <code>String</code>.</td></tr> - * <tr><td><code>dom:writeXmlDocument(String, Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount)</code></td><td>Writes a <code>org.w3c.dom.Node</code> to an XML file and returns <code>true</code> if successful.</td></tr> + * <tr><td><code>dom:toHtmlString(Node, String encoding, boolean indent, int indentAmount)</code></td><td>Returns a <code>org.w3c.dom.Node</code> + * as an HTML <code>String</code>.</td></tr> + * <tr><td><code>dom:toXmlString(Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount)</code></td><td>Returns a + * <code>org.w3c.dom.Node</code> as an XML <code>String</code>.</td></tr> + * <tr><td><code>dom:writeXmlDocument(String, Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount) + * </code></td><td>Writes a <code>org.w3c.dom.Node</code> to an XML file and returns <code>true</code> if successful.</td></tr> * </table> */ public class UelFunctions { + protected static final Functions FUNCTION_MAPPER = new Functions(); private static final String MODULE = UelFunctions.class.getName(); - protected static final Functions functionMapper = new Functions(); - /** Returns a <code>FunctionMapper</code> instance. + /** + * Returns a <code>FunctionMapper</code> instance. + * * @return <code>FunctionMapper</code> instance */ public static FunctionMapper getFunctionMapper() { - return functionMapper; + return FUNCTION_MAPPER; } - protected static class Functions extends FunctionMapper { - protected final Map<String, Method> functionMap = new HashMap<>(); - public Functions() { - try { - this.functionMap.put("date:second", UtilDateTime.class.getMethod("getSecond", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:minute", UtilDateTime.class.getMethod("getMinute", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:hour", UtilDateTime.class.getMethod("getHour", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dayOfMonth", UtilDateTime.class.getMethod("getDayOfMonth", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dayOfWeek", UtilDateTime.class.getMethod("getDayOfWeek", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dayOfYear", UtilDateTime.class.getMethod("getDayOfYear", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:week", UtilDateTime.class.getMethod("getWeek", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:month", UtilDateTime.class.getMethod("getMonth", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:year", UtilDateTime.class.getMethod("getYear", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dayStart", UtilDateTime.class.getMethod("getDayStart", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dayEnd", UtilDateTime.class.getMethod("getDayEnd", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:weekStart", UtilDateTime.class.getMethod("getWeekStart", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:weekEnd", UtilDateTime.class.getMethod("getWeekEnd", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:monthStart", UtilDateTime.class.getMethod("getMonthStart", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:monthEnd", UtilDateTime.class.getMethod("getMonthEnd", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:yearStart", UtilDateTime.class.getMethod("getYearStart", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:yearEnd", UtilDateTime.class.getMethod("getYearEnd", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:dateStr", UelFunctions.class.getMethod("dateString", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:localizedDateStr", UelFunctions.class.getMethod("localizedDateString", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:localizedDateTimeStr", UelFunctions.class.getMethod("localizedDateTimeString", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:timeStr", UelFunctions.class.getMethod("timeString", Timestamp.class, TimeZone.class, Locale.class)); - this.functionMap.put("date:nowTimestamp", UtilDateTime.class.getMethod("nowTimestamp")); - this.functionMap.put("math:absDouble", Math.class.getMethod("abs", double.class)); - this.functionMap.put("math:absFloat", Math.class.getMethod("abs", float.class)); - this.functionMap.put("math:absInt", Math.class.getMethod("abs", int.class)); - this.functionMap.put("math:absLong", Math.class.getMethod("abs", long.class)); - this.functionMap.put("math:acos", Math.class.getMethod("abs", double.class)); - this.functionMap.put("math:asin", Math.class.getMethod("asin", double.class)); - this.functionMap.put("math:atan", Math.class.getMethod("atan", double.class)); - this.functionMap.put("math:atan2", Math.class.getMethod("max", double.class, double.class)); - this.functionMap.put("math:cbrt", Math.class.getMethod("cbrt", double.class)); - this.functionMap.put("math:ceil", Math.class.getMethod("ceil", double.class)); - this.functionMap.put("math:cos", Math.class.getMethod("cos", double.class)); - this.functionMap.put("math:cosh", Math.class.getMethod("cosh", double.class)); - this.functionMap.put("math:exp", Math.class.getMethod("exp", double.class)); - this.functionMap.put("math:expm1", Math.class.getMethod("expm1", double.class)); - this.functionMap.put("math:floor", Math.class.getMethod("floor", double.class)); - this.functionMap.put("math:hypot", Math.class.getMethod("hypot", double.class, double.class)); - this.functionMap.put("math:IEEEremainder", Math.class.getMethod("IEEEremainder", double.class, double.class)); - this.functionMap.put("math:log", Math.class.getMethod("log", double.class)); - this.functionMap.put("math:log10", Math.class.getMethod("log10", double.class)); - this.functionMap.put("math:log1p", Math.class.getMethod("log1p", double.class)); - this.functionMap.put("math:maxDouble", Math.class.getMethod("max", double.class, double.class)); - this.functionMap.put("math:maxFloat", Math.class.getMethod("max", float.class, float.class)); - this.functionMap.put("math:maxInt", Math.class.getMethod("max", int.class, int.class)); - this.functionMap.put("math:maxLong", Math.class.getMethod("max", long.class, long.class)); - this.functionMap.put("math:minDouble", Math.class.getMethod("min", double.class, double.class)); - this.functionMap.put("math:minFloat", Math.class.getMethod("min", float.class, float.class)); - this.functionMap.put("math:minInt", Math.class.getMethod("min", int.class, int.class)); - this.functionMap.put("math:minLong", Math.class.getMethod("min", long.class, long.class)); - this.functionMap.put("math:pow", Math.class.getMethod("pow", double.class, double.class)); - this.functionMap.put("math:random", Math.class.getMethod("random")); - this.functionMap.put("math:rint", Math.class.getMethod("rint", double.class)); - this.functionMap.put("math:roundDouble", Math.class.getMethod("round", double.class)); - this.functionMap.put("math:roundFloat", Math.class.getMethod("round", float.class)); - this.functionMap.put("math:signumDouble", Math.class.getMethod("signum", double.class)); - this.functionMap.put("math:signumFloat", Math.class.getMethod("signum", float.class)); - this.functionMap.put("math:sin", Math.class.getMethod("sin", double.class)); - this.functionMap.put("math:sinh", Math.class.getMethod("sinh", double.class)); - this.functionMap.put("math:sqrt", Math.class.getMethod("sqrt", double.class)); - this.functionMap.put("math:tan", Math.class.getMethod("tan", double.class)); - this.functionMap.put("math:tanh", Math.class.getMethod("tanh", double.class)); - this.functionMap.put("math:toDegrees", Math.class.getMethod("toDegrees", double.class)); - this.functionMap.put("math:toRadians", Math.class.getMethod("toRadians", double.class)); - this.functionMap.put("math:ulpDouble", Math.class.getMethod("ulp", double.class)); - this.functionMap.put("math:ulpFloat", Math.class.getMethod("ulp", float.class)); - this.functionMap.put("str:endsWith", UelFunctions.class.getMethod("endsWith", String.class, String.class)); - this.functionMap.put("str:indexOf", UelFunctions.class.getMethod("indexOf", String.class, String.class)); - this.functionMap.put("str:lastIndexOf", UelFunctions.class.getMethod("lastIndexOf", String.class, String.class)); - this.functionMap.put("str:length", UelFunctions.class.getMethod("length", String.class)); - this.functionMap.put("str:replace", UelFunctions.class.getMethod("replace", String.class, String.class, String.class)); - this.functionMap.put("str:replaceAll", UelFunctions.class.getMethod("replaceAll", String.class, String.class, String.class)); - this.functionMap.put("str:replaceFirst", UelFunctions.class.getMethod("replaceFirst", String.class, String.class, String.class)); - this.functionMap.put("str:startsWith", UelFunctions.class.getMethod("startsWith", String.class, String.class)); - this.functionMap.put("str:endstring", UelFunctions.class.getMethod("endString", String.class, int.class)); - this.functionMap.put("str:substring", UelFunctions.class.getMethod("subString", String.class, int.class, int.class)); - this.functionMap.put("str:toString", UelFunctions.class.getMethod("toString", Object.class)); - this.functionMap.put("str:toLowerCase", UelFunctions.class.getMethod("toLowerCase", String.class)); - this.functionMap.put("str:toUpperCase", UelFunctions.class.getMethod("toUpperCase", String.class)); - this.functionMap.put("str:trim", UelFunctions.class.getMethod("trim", String.class)); - this.functionMap.put("sys:getenv", UelFunctions.class.getMethod("sysGetEnv", String.class)); - this.functionMap.put("sys:getProperty", UelFunctions.class.getMethod("sysGetProp", String.class)); - this.functionMap.put("util:size", UelFunctions.class.getMethod("getSize", Object.class)); - this.functionMap.put("util:defaultLocale", Locale.class.getMethod("getDefault")); - this.functionMap.put("util:defaultTimeZone", TimeZone.class.getMethod("getDefault")); - this.functionMap.put("util:label", UelFunctions.class.getMethod("label", String.class, String.class, Locale.class)); - this.functionMap.put("dom:readHtmlDocument", UelFunctions.class.getMethod("readHtmlDocument", String.class)); - this.functionMap.put("dom:readXmlDocument", UelFunctions.class.getMethod("readXmlDocument", String.class)); - this.functionMap.put("dom:toHtmlString", UelFunctions.class.getMethod("toHtmlString", Node.class, String.class, boolean.class, int.class)); - this.functionMap.put("dom:toXmlString", UelFunctions.class.getMethod("toXmlString", Node.class, String.class, boolean.class, boolean.class, int.class)); - this.functionMap.put("dom:writeXmlDocument", UelFunctions.class.getMethod("writeXmlDocument", String.class, Node.class, String.class, boolean.class, boolean.class, int.class)); - } catch (NoSuchMethodException | NullPointerException | SecurityException e) { - Debug.logError(e, "Error while initializing UelFunctions.Functions instance", MODULE); - } - if (Debug.verboseOn()) { - Debug.logVerbose("UelFunctions.Functions loaded " + this.functionMap.size() + " functions", MODULE); - } - } - @Override - public Method resolveFunction(String prefix, String localName) { - return functionMap.get(prefix + ":" + localName); - } - } - - /** Add a function to OFBiz's built-in UEL functions. */ + /** + * Add a function to OFBiz's built-in UEL functions. + */ public static synchronized void setFunction(String prefix, String localName, Method method) { - functionMapper.functionMap.put(prefix + ":" + localName, method); + FUNCTION_MAPPER.functionMap.put(prefix + ":" + localName, method); } public static String dateString(Timestamp stamp, TimeZone timeZone, Locale locale) { @@ -478,7 +406,8 @@ public class UelFunctions { try { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); - sb.append("<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xalan=\"http://xml.apache.org/xslt\" version=\"1.0\">\n"); + sb.append("<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xalan=\"http://xml.apache.org/xslt\" version=\"1" + + ".0\">\n"); sb.append("<xsl:output method=\"html\" encoding=\""); sb.append(encoding == null ? "UTF-8" : encoding); sb.append("\""); @@ -514,4 +443,119 @@ public class UelFunctions { } return null; } + + protected static class Functions extends FunctionMapper { + protected final Map<String, Method> functionMap = new HashMap<>(); + + public Functions() { + try { + this.functionMap.put("date:second", UtilDateTime.class.getMethod("getSecond", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:minute", UtilDateTime.class.getMethod("getMinute", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:hour", UtilDateTime.class.getMethod("getHour", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dayOfMonth", UtilDateTime.class.getMethod("getDayOfMonth", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dayOfWeek", UtilDateTime.class.getMethod("getDayOfWeek", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dayOfYear", UtilDateTime.class.getMethod("getDayOfYear", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:week", UtilDateTime.class.getMethod("getWeek", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:month", UtilDateTime.class.getMethod("getMonth", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:year", UtilDateTime.class.getMethod("getYear", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dayStart", UtilDateTime.class.getMethod("getDayStart", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dayEnd", UtilDateTime.class.getMethod("getDayEnd", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:weekStart", UtilDateTime.class.getMethod("getWeekStart", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:weekEnd", UtilDateTime.class.getMethod("getWeekEnd", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:monthStart", UtilDateTime.class.getMethod("getMonthStart", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:monthEnd", UtilDateTime.class.getMethod("getMonthEnd", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:yearStart", UtilDateTime.class.getMethod("getYearStart", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:yearEnd", UtilDateTime.class.getMethod("getYearEnd", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:dateStr", UelFunctions.class.getMethod("dateString", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:localizedDateStr", UelFunctions.class.getMethod("localizedDateString", Timestamp.class, TimeZone.class, + Locale.class)); + this.functionMap.put("date:localizedDateTimeStr", UelFunctions.class.getMethod("localizedDateTimeString", Timestamp.class, + TimeZone.class, Locale.class)); + this.functionMap.put("date:timeStr", UelFunctions.class.getMethod("timeString", Timestamp.class, TimeZone.class, Locale.class)); + this.functionMap.put("date:nowTimestamp", UtilDateTime.class.getMethod("nowTimestamp")); + this.functionMap.put("math:absDouble", Math.class.getMethod("abs", double.class)); + this.functionMap.put("math:absFloat", Math.class.getMethod("abs", float.class)); + this.functionMap.put("math:absInt", Math.class.getMethod("abs", int.class)); + this.functionMap.put("math:absLong", Math.class.getMethod("abs", long.class)); + this.functionMap.put("math:acos", Math.class.getMethod("abs", double.class)); + this.functionMap.put("math:asin", Math.class.getMethod("asin", double.class)); + this.functionMap.put("math:atan", Math.class.getMethod("atan", double.class)); + this.functionMap.put("math:atan2", Math.class.getMethod("max", double.class, double.class)); + this.functionMap.put("math:cbrt", Math.class.getMethod("cbrt", double.class)); + this.functionMap.put("math:ceil", Math.class.getMethod("ceil", double.class)); + this.functionMap.put("math:cos", Math.class.getMethod("cos", double.class)); + this.functionMap.put("math:cosh", Math.class.getMethod("cosh", double.class)); + this.functionMap.put("math:exp", Math.class.getMethod("exp", double.class)); + this.functionMap.put("math:expm1", Math.class.getMethod("expm1", double.class)); + this.functionMap.put("math:floor", Math.class.getMethod("floor", double.class)); + this.functionMap.put("math:hypot", Math.class.getMethod("hypot", double.class, double.class)); + this.functionMap.put("math:IEEEremainder", Math.class.getMethod("IEEEremainder", double.class, double.class)); + this.functionMap.put("math:log", Math.class.getMethod("log", double.class)); + this.functionMap.put("math:log10", Math.class.getMethod("log10", double.class)); + this.functionMap.put("math:log1p", Math.class.getMethod("log1p", double.class)); + this.functionMap.put("math:maxDouble", Math.class.getMethod("max", double.class, double.class)); + this.functionMap.put("math:maxFloat", Math.class.getMethod("max", float.class, float.class)); + this.functionMap.put("math:maxInt", Math.class.getMethod("max", int.class, int.class)); + this.functionMap.put("math:maxLong", Math.class.getMethod("max", long.class, long.class)); + this.functionMap.put("math:minDouble", Math.class.getMethod("min", double.class, double.class)); + this.functionMap.put("math:minFloat", Math.class.getMethod("min", float.class, float.class)); + this.functionMap.put("math:minInt", Math.class.getMethod("min", int.class, int.class)); + this.functionMap.put("math:minLong", Math.class.getMethod("min", long.class, long.class)); + this.functionMap.put("math:pow", Math.class.getMethod("pow", double.class, double.class)); + this.functionMap.put("math:random", Math.class.getMethod("random")); + this.functionMap.put("math:rint", Math.class.getMethod("rint", double.class)); + this.functionMap.put("math:roundDouble", Math.class.getMethod("round", double.class)); + this.functionMap.put("math:roundFloat", Math.class.getMethod("round", float.class)); + this.functionMap.put("math:signumDouble", Math.class.getMethod("signum", double.class)); + this.functionMap.put("math:signumFloat", Math.class.getMethod("signum", float.class)); + this.functionMap.put("math:sin", Math.class.getMethod("sin", double.class)); + this.functionMap.put("math:sinh", Math.class.getMethod("sinh", double.class)); + this.functionMap.put("math:sqrt", Math.class.getMethod("sqrt", double.class)); + this.functionMap.put("math:tan", Math.class.getMethod("tan", double.class)); + this.functionMap.put("math:tanh", Math.class.getMethod("tanh", double.class)); + this.functionMap.put("math:toDegrees", Math.class.getMethod("toDegrees", double.class)); + this.functionMap.put("math:toRadians", Math.class.getMethod("toRadians", double.class)); + this.functionMap.put("math:ulpDouble", Math.class.getMethod("ulp", double.class)); + this.functionMap.put("math:ulpFloat", Math.class.getMethod("ulp", float.class)); + this.functionMap.put("str:endsWith", UelFunctions.class.getMethod("endsWith", String.class, String.class)); + this.functionMap.put("str:indexOf", UelFunctions.class.getMethod("indexOf", String.class, String.class)); + this.functionMap.put("str:lastIndexOf", UelFunctions.class.getMethod("lastIndexOf", String.class, String.class)); + this.functionMap.put("str:length", UelFunctions.class.getMethod("length", String.class)); + this.functionMap.put("str:replace", UelFunctions.class.getMethod("replace", String.class, String.class, String.class)); + this.functionMap.put("str:replaceAll", UelFunctions.class.getMethod("replaceAll", String.class, String.class, String.class)); + this.functionMap.put("str:replaceFirst", UelFunctions.class.getMethod("replaceFirst", String.class, String.class, String.class)); + this.functionMap.put("str:startsWith", UelFunctions.class.getMethod("startsWith", String.class, String.class)); + this.functionMap.put("str:endstring", UelFunctions.class.getMethod("endString", String.class, int.class)); + this.functionMap.put("str:substring", UelFunctions.class.getMethod("subString", String.class, int.class, int.class)); + this.functionMap.put("str:toString", UelFunctions.class.getMethod("toString", Object.class)); + this.functionMap.put("str:toLowerCase", UelFunctions.class.getMethod("toLowerCase", String.class)); + this.functionMap.put("str:toUpperCase", UelFunctions.class.getMethod("toUpperCase", String.class)); + this.functionMap.put("str:trim", UelFunctions.class.getMethod("trim", String.class)); + this.functionMap.put("sys:getenv", UelFunctions.class.getMethod("sysGetEnv", String.class)); + this.functionMap.put("sys:getProperty", UelFunctions.class.getMethod("sysGetProp", String.class)); + this.functionMap.put("util:size", UelFunctions.class.getMethod("getSize", Object.class)); + this.functionMap.put("util:defaultLocale", Locale.class.getMethod("getDefault")); + this.functionMap.put("util:defaultTimeZone", TimeZone.class.getMethod("getDefault")); + this.functionMap.put("util:label", UelFunctions.class.getMethod("label", String.class, String.class, Locale.class)); + this.functionMap.put("dom:readHtmlDocument", UelFunctions.class.getMethod("readHtmlDocument", String.class)); + this.functionMap.put("dom:readXmlDocument", UelFunctions.class.getMethod("readXmlDocument", String.class)); + this.functionMap.put("dom:toHtmlString", UelFunctions.class.getMethod("toHtmlString", Node.class, String.class, boolean.class, + int.class)); + this.functionMap.put("dom:toXmlString", UelFunctions.class.getMethod("toXmlString", Node.class, String.class, boolean.class, + boolean.class, int.class)); + this.functionMap.put("dom:writeXmlDocument", UelFunctions.class.getMethod("writeXmlDocument", String.class, Node.class, + String.class, boolean.class, boolean.class, int.class)); + } catch (NoSuchMethodException | NullPointerException | SecurityException e) { + Debug.logError(e, "Error while initializing UelFunctions.Functions instance", MODULE); + } + if (Debug.verboseOn()) { + Debug.logVerbose("UelFunctions.Functions loaded " + this.functionMap.size() + " functions", MODULE); + } + } + /** resolve function */ + @Override + public Method resolveFunction(String prefix, String localName) { + return functionMap.get(prefix + ":" + localName); + } + } } diff --git a/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/CatalinaContainer.java b/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/CatalinaContainer.java index 1cad7ec..1eb6705 100644 --- a/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/CatalinaContainer.java +++ b/framework/catalina/src/main/java/org/apache/ofbiz/catalina/container/CatalinaContainer.java @@ -135,8 +135,8 @@ public class CatalinaContainer implements Container { } for (Connector con: tomcat.getService().findConnectors()) { - Debug.logInfo("Connector " + con.getProtocol() + " @ " + con.getPort() + " - " + - (con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", MODULE); + Debug.logInfo("Connector " + con.getProtocol() + " @ " + con.getPort() + " - " + + (con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", MODULE); } Debug.logInfo("Started " + ServerInfo.getServerInfo(), MODULE); return true; @@ -171,8 +171,8 @@ public class CatalinaContainer implements Container { private static Tomcat prepareTomcatServer(ContainerConfig.Configuration cc, Configuration.Property engineConfig) throws ContainerException { - System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("ofbiz.home") + "/" + - ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina")); + System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("ofbiz.home") + "/" + + ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina")); System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty(Globals.CATALINA_HOME_PROP)); Tomcat tomcat = new Tomcat(); 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 dbda4ff..8368f2a 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 @@ -41,9 +41,9 @@ import org.xml.sax.SAXException; */ public class CdyneServices { - public final static String MODULE = CdyneServices.class.getName(); + private static final String MODULE = CdyneServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; - public final static String licenseKey = UtilProperties.getPropertyValue("cdyne", "LicenseKey", "0"); + public static final String licenseKey = UtilProperties.getPropertyValue("cdyne", "LicenseKey", "0"); /** * CDyne ReturnCityState Service 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 5933344..c3a7210 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 @@ -70,7 +70,7 @@ import org.apache.ofbiz.service.mail.MimeMessageWrapper; */ public class CommonServices { - public final static String MODULE = CommonServices.class.getName(); + private static final String MODULE = CommonServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; /** diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/CommonWorkers.java b/framework/common/src/main/java/org/apache/ofbiz/common/CommonWorkers.java index 84c4d99..28b494e 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/CommonWorkers.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/CommonWorkers.java @@ -40,7 +40,7 @@ import org.apache.ofbiz.entity.util.EntityUtilProperties; */ public final class CommonWorkers { - public final static String MODULE = CommonWorkers.class.getName(); + private static final String MODULE = CommonWorkers.class.getName(); private CommonWorkers() { } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/FtpServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/FtpServices.java index a55e3aa..e70c5ba 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/FtpServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/FtpServices.java @@ -45,7 +45,7 @@ import org.apache.ofbiz.service.ServiceUtil; */ public class FtpServices { - public final static String MODULE = FtpServices.class.getName(); + private static final String MODULE = FtpServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) { diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java b/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java index 035d986..eff506c 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/UrlServletHelper.java @@ -43,7 +43,7 @@ import org.apache.ofbiz.webapp.website.WebSiteWorker; public final class UrlServletHelper { - public final static String MODULE = UrlServletHelper.class.getName(); + private static final String MODULE = UrlServletHelper.class.getName(); private UrlServletHelper() { } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/email/EmailServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/email/EmailServices.java index 18a2916..6de0771 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/email/EmailServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/email/EmailServices.java @@ -87,7 +87,7 @@ import freemarker.template.TemplateException; */ public class EmailServices { - public final static String MODULE = EmailServices.class.getName(); + private static final String MODULE = EmailServices.class.getName(); private static final String RESOURCE = "CommonUiLabels"; diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/email/NotificationServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/email/NotificationServices.java index 75fe2ca..981ee4b 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/email/NotificationServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/email/NotificationServices.java @@ -48,7 +48,7 @@ import freemarker.template.TemplateException; * via email. * <p> * To use the NotificationService, a message specific service should be - * defined for a particular + * defined for a particular * <a href="http://freemarker.sourceforge.net/docs/dgui_quickstart_template.html"> * Freemarker Template</a> mapping the required fields of the template to the * required attributes of the service. @@ -70,7 +70,7 @@ import freemarker.template.TemplateException; * } * </pre> * <p> - * An optional parameter available to all message templates is + * An optional parameter available to all message templates is * <code>baseUrl</code> which can either be specified when the service is * invoked or let the <code>NotificationService</code> attempt to resolve it * as best it can, see {@link #setBaseUrl(Delegator, String, Map) setBaseUrl(Map)} diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/period/PeriodWorker.java b/framework/common/src/main/java/org/apache/ofbiz/common/period/PeriodWorker.java index d532872..fc2cbc6 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/period/PeriodWorker.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/period/PeriodWorker.java @@ -30,7 +30,7 @@ import org.apache.ofbiz.entity.condition.EntityExpr; import org.apache.ofbiz.entity.condition.EntityOperator; public final class PeriodWorker { - public final static String MODULE = PeriodWorker.class.getName(); + private static final String MODULE = PeriodWorker.class.getName(); private PeriodWorker() { } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/qrcode/QRCodeServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/qrcode/QRCodeServices.java index bebb145..a3189b4 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/qrcode/QRCodeServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/qrcode/QRCodeServices.java @@ -247,9 +247,9 @@ public class QRCodeServices { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int pixel = pixels[y * width + x]; - int luminance = (306 * ((pixel >> 16) & 0xFF) + - 601 * ((pixel >> 8) & 0xFF) + - 117 * (pixel & 0xFF)) >> 10; + int luminance = (306 * ((pixel >> 16) & 0xFF) + + 601 * ((pixel >> 8) & 0xFF) + + 117 * (pixel & 0xFF)) >> 10; if (luminance <= 0x7F) { matrix.set(x, y); } diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/telecom/TelecomServices.java b/framework/common/src/main/java/org/apache/ofbiz/common/telecom/TelecomServices.java index 2bce922..a81a98e 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/telecom/TelecomServices.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/telecom/TelecomServices.java @@ -38,7 +38,7 @@ import org.apache.ofbiz.service.ServiceUtil; public class TelecomServices { - public final static String MODULE = TelecomServices.class.getName(); + private static final String MODULE = TelecomServices.class.getName(); public static Map<String, Object> sendTelecomMessage(DispatchContext ctx, Map<String, ? extends Object> context) { Delegator delegator = ctx.getDelegator(); diff --git a/framework/datafile/src/main/java/org/apache/ofbiz/datafile/ModelDataFile.java b/framework/datafile/src/main/java/org/apache/ofbiz/datafile/ModelDataFile.java index 1236f84..7d3fb13 100644 --- a/framework/datafile/src/main/java/org/apache/ofbiz/datafile/ModelDataFile.java +++ b/framework/datafile/src/main/java/org/apache/ofbiz/datafile/ModelDataFile.java @@ -64,7 +64,6 @@ public class ModelDataFile { public String description = ""; /** file enconding, by default UTF-8 is used */ public String encodingType = "UTF-8"; - /** * the End Of Line type (CRLF or CR) diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericDelegator.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericDelegator.java index 81c9c2f..2a9fa38 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericDelegator.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericDelegator.java @@ -2608,7 +2608,7 @@ public class GenericDelegator implements Delegator { this.testMode = true; } - public final static class TestOperation { + public static final class TestOperation { private final OperationType operation; private final GenericValue value; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericValue.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericValue.java index 7d77799..ca4e60c 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericValue.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/GenericValue.java @@ -71,31 +71,34 @@ public class GenericValue extends GenericEntity { newValue.init(primaryKey); return newValue; } - + /** Creates new GenericValue from existing GenericValue */ public GenericValue create() throws GenericEntityException { return this.getDelegator().create(this); } - + /** store */ public void store() throws GenericEntityException { this.getDelegator().store(this); } - + /** remove */ public void remove() throws GenericEntityException { this.getDelegator().removeValue(this); } - + /** refresh */ public void refresh() throws GenericEntityException { this.getDelegator().refresh(this); } - + /** refresh from cache */ public void refreshFromCache() throws GenericEntityException { this.getDelegator().refreshFromCache(this); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - *@return List of GenericValue instances as specified in the relation definition - *@deprecated use {@link #getRelated(String, Map, List, boolean)} + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @return List of GenericValue instances as specified in the relation definition + * @deprecated use {@link #getRelated(String, Map, List, boolean)} */ @Deprecated public List<GenericValue> getRelated(String relationName) throws GenericEntityException { @@ -103,12 +106,15 @@ public class GenericValue extends GenericEntity { return this.getDelegator().getRelated(relationName, null, null, this, false); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending - *@return List of GenericValue instances as specified in the relation definition - *@deprecated use {@link #getRelated(String, Map, List, boolean)} + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue instances as specified in the relation definition + * @deprecated use {@link #getRelated(String, Map, List, boolean)} */ @Deprecated public List<GenericValue> getRelated(String relationName, List<String> orderBy) throws GenericEntityException { @@ -116,41 +122,50 @@ public class GenericValue extends GenericEntity { return this.getDelegator().getRelated(relationName, null, orderBy, this, false); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - * @param byAndFields the fields that must equal in order to keep; may be null - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending - *@return List of GenericValue instances as specified in the relation definition - *@deprecated use {@link #getRelated(String, Map, List, boolean)} + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @param byAndFields the fields that must equal in order to keep; may be null + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue instances as specified in the relation definition + * @deprecated use {@link #getRelated(String, Map, List, boolean)} */ @Deprecated - public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy) throws GenericEntityException { + public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy) + throws GenericEntityException { Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", getStackTraceAsString()); return this.getDelegator().getRelated(relationName, byAndFields, orderBy, this, false); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - * @param byAndFields the fields that must equal in order to keep; may be null - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending - * @param useCache Whether to cache the results - *@return List of GenericValue instances as specified in the relation definition + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @param byAndFields the fields that must equal in order to keep; may be null + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending + * @param useCache Whether to cache the results + * @return List of GenericValue instances as specified in the relation definition */ - public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, boolean useCache) throws GenericEntityException { + public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, boolean useCache) + throws GenericEntityException { return this.getDelegator().getRelated(relationName, byAndFields, orderBy, this, useCache); } /** * Get the named Related Entity for the GenericValue from the persistent store across another Relation. * Helps to get related Values in a multi-to-multi relationship. + * * @param relationNameOne String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file, for first relation + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file, for first relation * @param relationNameTwo String containing the relation name for second relation - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending * @return List of GenericValue instances as specified in the relation definition */ public List<GenericValue> getRelatedMulti(String relationNameOne, String relationNameTwo, List<String> orderBy) throws GenericEntityException { @@ -160,9 +175,10 @@ public class GenericValue extends GenericEntity { /** * Get the named Related Entity for the GenericValue from the persistent store across another Relation. * Helps to get related Values in a multi-to-multi relationship. + * * @param relationNameOne String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file, for first relation + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file, for first relation * @param relationNameTwo String containing the relation name for second relation * @return List of GenericValue instances as specified in the relation definition */ @@ -170,10 +186,13 @@ public class GenericValue extends GenericEntity { return this.getDelegator().getMultiRelation(this, relationNameOne, relationNameTwo, null); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - *@return List of GenericValue instances as specified in the relation definition - *@deprecated use {@link #getRelatedOne(String, boolean)} + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @return List of GenericValue instances as specified in the relation definition + * @deprecated use {@link #getRelatedOne(String, boolean)} */ @Deprecated public GenericValue getRelatedOne(String relationName) throws GenericEntityException { @@ -181,17 +200,23 @@ public class GenericValue extends GenericEntity { return this.getDelegator().getRelatedOne(relationName, this, false); } - /** Get the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file - *@param useCache Whether to cache the results - *@return The single related GenericValue instance + /** + * Get the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file + * @param useCache Whether to cache the results + * @return The single related GenericValue instance */ public GenericValue getRelatedOne(String relationName, boolean useCache) throws GenericEntityException { return this.getDelegator().getRelatedOne(relationName, this, useCache); } - /** Remove the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file + /** + * Remove the named Related Entity for the GenericValue from the persistent store + * + * @param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified + * in the entity XML definition file */ public void removeRelated(String relationName) throws GenericEntityException { this.getDelegator().removeRelated(relationName, this); @@ -217,12 +242,12 @@ public class GenericValue extends GenericEntity { public GenericPK getRelatedDummyPK(String relationName, Map<String, ? extends Object> byAndFields) throws GenericEntityException { return this.getDelegator().getRelatedDummyPK(relationName, byAndFields, this); } - + /** hash code */ @Override public int hashCode() { return Objects.hashCode(super.hashCode()); } - + /** equals */ @Override public boolean equals(Object obj) { if (obj instanceof GenericValue) { @@ -230,7 +255,6 @@ public class GenericValue extends GenericEntity { } return false; } - /** Clones this GenericValue, this is a shallow clone and uses the default shallow HashMap clone * @return Object that is a clone of this GenericValue */ @@ -240,10 +264,12 @@ public class GenericValue extends GenericEntity { } protected static class NullGenericValue extends GenericValue implements NULL { + /** get entity name */ @Override public String getEntityName() { return "[null-entity-value]"; } + /** to string */ @Override public String toString() { return "[null-entity-value]"; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityExpr.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityExpr.java index ac1d500..405d867 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityExpr.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityExpr.java @@ -233,7 +233,7 @@ public final class EntityExpr implements EntityCondition { if (value instanceof EntityConditionSubSelect) { ModelFieldType valueType = null; try { - ModelEntity valueModelEntity= ((EntityConditionSubSelect) value).getModelEntity(); + ModelEntity valueModelEntity = ((EntityConditionSubSelect) value).getModelEntity(); valueType = deleg.getEntityFieldType(valueModelEntity, valueModelEntity.getField(((EntityConditionSubSelect) value).getKeyFieldName()).getType()); } catch (GenericEntityException e) { @@ -250,7 +250,7 @@ public final class EntityExpr implements EntityCondition { // Make sure the type of keyFieldName of EntityConditionSubSelect matches the field Java type. try { if (!ObjectType.instanceOf(ObjectType.loadClass(valueType.getJavaType()), type.getJavaType())) { - String msg = "Warning using ["+ value.getClass().getName() + "]" + String msg = "Warning using [" + value.getClass().getName() + "]" + " and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]." + " The Java type of keyFieldName : [" + valueType.getJavaType() + "]" + " is not compatible with the Java type of the field [" + type.getJavaType() + "]"; @@ -260,7 +260,7 @@ public final class EntityExpr implements EntityCondition { "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + msg, MODULE); } } catch (ClassNotFoundException e) { - String msg = "Warning using ["+ value.getClass().getName() + "]" + String msg = "Warning using [" + value.getClass().getName() + "]" + " and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]." + " The Java type of keyFieldName : [" + valueType.getJavaType()+ "] could not be found]"; // Eventually we should do this, but for now we'll do a "soft" failure: @@ -284,7 +284,7 @@ public final class EntityExpr implements EntityCondition { } try { if (!ObjectType.instanceOf(ObjectType.loadClass(rhsType.getJavaType()), type.getJavaType())) { - String msg = "Warning using ["+ value.getClass().getName() + "]" + String msg = "Warning using [" + value.getClass().getName() + "]" + " and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]." + " The Java type [" + rhsType.getJavaType() + "] of rhsFieldName : [" + rhsFieldName + "]" + " is not compatible with the Java type of the field [" + type.getJavaType() + "]"; @@ -294,7 +294,7 @@ public final class EntityExpr implements EntityCondition { "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=- " + msg, MODULE); } } catch (ClassNotFoundException e) { - String msg = "Warning using ["+ value.getClass().getName() + "]" + String msg = "Warning using [" + value.getClass().getName() + "]" + " and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]." + " The Java type [" + rhsType.getJavaType() + "]" + " of rhsFieldName : [" + rhsFieldName + "] could not be found]"; 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 1e3d24b..3049e9a 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 @@ -65,7 +65,6 @@ import org.apache.ofbiz.entity.util.EntityQuery; /** * Generic Entity Data Access Object - Handles persistence for any defined entity. - * */ public class GenericDAO { @@ -76,6 +75,12 @@ public class GenericDAO { private final ModelFieldTypeReader modelFieldTypeReader; private final Datasource datasource; + public GenericDAO(GenericHelperInfo helperInfo) { + this.helperInfo = helperInfo; + this.modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperInfo.getHelperBaseName()); + this.datasource = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); + } + public static GenericDAO getGenericDAO(GenericHelperInfo helperInfo) { String cacheKey = helperInfo.getHelperFullName(); GenericDAO newGenericDAO = genericDAOs.get(cacheKey); @@ -86,14 +91,8 @@ public class GenericDAO { return newGenericDAO; } - public GenericDAO(GenericHelperInfo helperInfo) { - this.helperInfo = helperInfo; - this.modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperInfo.getHelperBaseName()); - this.datasource = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); - } - private static void addFieldIfMissing(List<ModelField> fieldsToSave, String fieldName, ModelEntity modelEntity) { - for (ModelField fieldToSave: fieldsToSave) { + for (ModelField fieldToSave : fieldsToSave) { if (fieldName.equals(fieldToSave.getName())) { return; } @@ -117,7 +116,8 @@ public class GenericDAO { } } - private int singleInsert(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException { + private int singleInsert(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) + throws GenericEntityException { if (modelEntity instanceof ModelViewEntity) { return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP); } @@ -125,10 +125,13 @@ public class GenericDAO { // if we have a STAMP_TX_FIELD or CREATE_STAMP_TX_FIELD then set it with NOW, always do this before the STAMP_FIELD // NOTE: these fairly complicated if statements have a few objectives: // 1. don't run the TransationUtil.getTransaction*Stamp() methods when we don't need to - // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such) + // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it + // anyway, ie even if it was from an EntitySync (also used for imports and such) boolean stampTxIsField = modelEntity.isField(ModelEntity.STAMP_TX_FIELD); boolean createStampTxIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_TX_FIELD); - if ((stampTxIsField || createStampTxIsField) && (!entity.getIsFromEntitySync() || (stampTxIsField && entity.get(ModelEntity.STAMP_TX_FIELD) == null) || (createStampTxIsField && entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null))) { + if ((stampTxIsField || createStampTxIsField) && (!entity.getIsFromEntitySync() + || (stampTxIsField && entity.get(ModelEntity.STAMP_TX_FIELD) == null) + || (createStampTxIsField && entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null))) { Timestamp txStartStamp = TransactionUtil.getTransactionStartStamp(); if (stampTxIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) { entity.set(ModelEntity.STAMP_TX_FIELD, txStartStamp); @@ -143,7 +146,7 @@ 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); @@ -211,7 +214,8 @@ public class GenericDAO { } } - private int singleUpdate(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException { + private int singleUpdate(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) + throws GenericEntityException { if (modelEntity instanceof ModelViewEntity) { return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP); } @@ -219,7 +223,8 @@ public class GenericDAO { // no non-primaryKey fields, update doesn't make sense, so don't do it if (fieldsToSave.size() <= 0) { if (Debug.verboseOn()) { - Debug.logVerbose("Trying to do an update on an entity with no non-PK fields, returning having done nothing; entity=" + entity, MODULE); + Debug.logVerbose("Trying to do an update on an entity with no non-PK fields, returning having done nothing; entity=" + entity, + MODULE); } // returning one because it was effectively updated, ie the same thing, so don't trigger any errors elsewhere return 1; @@ -241,7 +246,8 @@ public class GenericDAO { // if we have a STAMP_TX_FIELD then set it with NOW, always do this before the STAMP_FIELD // NOTE: these fairly complicated if statements have a few objectives: // 1. don't run the TransationUtil.getTransaction*Stamp() methods when we don't need to - // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such) + // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it + // anyway, ie even if it was from an EntitySync (also used for imports and such) if (modelEntity.isField(ModelEntity.STAMP_TX_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) { entity.set(ModelEntity.STAMP_TX_FIELD, TransactionUtil.getTransactionStartStamp()); addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity); @@ -276,7 +282,8 @@ public class GenericDAO { return retVal; } - public int updateByCondition(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException { + public int updateByCondition(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, + EntityCondition condition) throws GenericEntityException { try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) { try { @@ -288,9 +295,11 @@ public class GenericDAO { } } - public int updateByCondition(ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition, SQLProcessor sqlP) throws GenericEntityException { - if (modelEntity == null || fieldsToSet == null || condition == null) + public int updateByCondition(ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition, SQLProcessor sqlP) + throws GenericEntityException { + if (modelEntity == null || fieldsToSet == null || condition == null) { return 0; + } if (modelEntity instanceof ModelViewEntity) { throw new org.apache.ofbiz.entity.GenericNotImplementedException("Operation updateByCondition not supported yet for view entities"); } @@ -298,7 +307,7 @@ public class GenericDAO { StringBuilder sql = new StringBuilder("UPDATE ").append(modelEntity.getTableName(datasource)); sql.append(" SET "); List<EntityConditionParam> params = new LinkedList<>(); - for (Map.Entry<String, ? extends Object> entry: fieldsToSet.entrySet()) { + for (Map.Entry<String, ? extends Object> entry : fieldsToSet.entrySet()) { String name = entry.getKey(); ModelField field = modelEntity.getField(name); if (field != null) { @@ -312,7 +321,7 @@ public class GenericDAO { sql.append(" WHERE ").append(condition.makeWhereString(modelEntity, params, this.datasource)); sqlP.prepareStatement(sql.toString()); - for (EntityConditionParam param: params) { + for (EntityConditionParam param : params) { SqlJdbcUtil.setValue(sqlP, param.getModelField(), modelEntity.getEntityName(), param.getFieldValue(), modelFieldTypeReader); } @@ -325,7 +334,7 @@ public class GenericDAO { /** * Try to update the given ModelViewEntity by trying to insert/update on the entities of which the view is composed. - * + * <p> * Works fine with standard O/R mapped models, but has some restrictions meeting more complicated view entities. * <li>A direct link is required, which means that one of the ModelViewLink field entries must have a value found * in the given view entity, for each ModelViewLink</li> @@ -334,16 +343,16 @@ public class GenericDAO { * <li>For now, aliased field names in views are not processed correctly, I guess. To be honest, I did not * find out how to construct such a view - so view fieldnames must have same named fields in member entities.</li> * <li>A new exception, e.g. GenericViewNotUpdatable, should be defined and thrown if the update fails</li> - * */ - private int singleUpdateView(GenericEntity entity, ModelViewEntity modelViewEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException { + private int singleUpdateView(GenericEntity entity, ModelViewEntity modelViewEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) + throws GenericEntityException { Delegator delegator = entity.getDelegator(); int retVal = 0; ModelEntity memberModelEntity = null; // Construct insert/update for each model entity - for (ModelViewEntity.ModelMemberEntity modelMemberEntity: modelViewEntity.getMemberModelMemberEntities().values()) { + for (ModelViewEntity.ModelMemberEntity modelMemberEntity : modelViewEntity.getMemberModelMemberEntities().values()) { String meName = modelMemberEntity.getEntityName(); String meAlias = modelMemberEntity.getEntityAlias(); @@ -424,18 +433,20 @@ public class GenericDAO { // Create new value to store meGenericValue = delegator.makeValue(meName, findByMap); } catch (Exception e) { - throw new GenericEntityException("Could not create new value for member entity" + meName + " of view " + modelViewEntity.getEntityName(), e); + throw new GenericEntityException("Could not create new value for member entity" + meName + " of view " + + modelViewEntity.getEntityName(), e); } } else if (meResult.size() == 1) { // Update existing value meGenericValue = meResult.iterator().next(); } else { - throw new GenericEntityException("Found more than one result for member entity " + meName + " in view " + modelViewEntity.getEntityName() + " - this is no updatable view"); + throw new GenericEntityException("Found more than one result for member entity " + meName + " in view " + + modelViewEntity.getEntityName() + " - this is no updatable view"); } // Construct fieldsToSave list for this member entity List<ModelField> meFieldsToSave = new LinkedList<>(); - for (ModelField modelField: fieldsToSave) { + for (ModelField modelField : fieldsToSave) { if (memberModelEntity.isField(modelField.getName())) { ModelField meModelField = memberModelEntity.getField(modelField.getName()); @@ -443,10 +454,12 @@ public class GenericDAO { meGenericValue.set(meModelField.getName(), entity.get(modelField.getName())); meFieldsToSave.add(meModelField); if (Debug.verboseOn()) { - Debug.logVerbose("[singleUpdateView]: --- Added field to save: " + meModelField.getName() + " with value " + meGenericValue.get(meModelField.getName()), MODULE); + Debug.logVerbose("[singleUpdateView]: --- Added field to save: " + meModelField.getName() + " with value " + + meGenericValue.get(meModelField.getName()), MODULE); } } else { - throw new GenericEntityException("Could not get field " + modelField.getName() + " from model entity " + memberModelEntity.getEntityName()); + throw new GenericEntityException("Could not get field " + modelField.getName() + " from model entity " + + memberModelEntity.getEntityName()); } } } @@ -579,19 +592,26 @@ public class GenericDAO { /* ====================================================================== */ /* ====================================================================== */ - /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. - *@param modelEntity The ModelEntity of the Entity as defined in the entity XML file - *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) - *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases) - *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. - *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE - * DONE WITH IT (preferably in a finally block), - * AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION. + /** + * Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. + * + * @param modelEntity The ModelEntity of the Entity as defined in the entity XML file + * @param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is + * a view entity with group-by aliases) + * @param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is + * a view entity with group-by aliases) + * @param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived + * @param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for + * descending + * @param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for + * more details. + * @return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE + * DONE WITH IT (preferably in a finally block), + * AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION. */ public EntityListIterator selectListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) + EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, + List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException { if (modelEntity == null) { return null; @@ -691,7 +711,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 @@ -739,8 +760,9 @@ public class GenericDAO { } } // set all of the values from the Where EntityCondition - for (EntityConditionParam whereEntityConditionParam: whereEntityConditionParams) { - SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader); + for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) { + SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), + whereEntityConditionParam.getFieldValue(), modelFieldTypeReader); } if (verboseOn) { // put this inside an if statement so that we don't have to generate the string when not used... @@ -749,8 +771,9 @@ public class GenericDAO { } } // set all of the values from the Having EntityCondition - for (EntityConditionParam havingEntityConditionParam: havingEntityConditionParams) { - SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader); + for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) { + SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), + havingEntityConditionParam.getFieldValue(), modelFieldTypeReader); } long queryStartTime = 0; @@ -762,18 +785,24 @@ public class GenericDAO { long queryEndTime = System.currentTimeMillis(); long queryTotalTime = queryEndTime - queryStartTime; if (queryTotalTime > 150) { - Debug.logTiming("Ran query in " + queryTotalTime + " milli-seconds: " + " EntityName: " + modelEntity.getEntityName() + " Sql: " + sql + " where clause:" + whereEntityConditionParams, MODULE); + Debug.logTiming("Ran query in " + queryTotalTime + " milli-seconds: " + " EntityName: " + modelEntity.getEntityName() + " Sql: " + + sql + " where clause:" + whereEntityConditionParams, MODULE); } } - return new EntityListIterator(sqlP, modelEntity, selectFields, modelFieldTypeReader, this, whereEntityCondition, havingEntityCondition, findOptions.getDistinct()); + return new EntityListIterator(sqlP, modelEntity, selectFields, modelFieldTypeReader, this, whereEntityCondition, havingEntityCondition, + findOptions.getDistinct()); } @Deprecated - protected StringBuilder makeConditionWhereString(ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException { + protected StringBuilder makeConditionWhereString(ModelEntity modelEntity, EntityCondition whereEntityCondition, + List<EntityCondition> viewWhereConditions, + List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException { return makeConditionWhereString(new StringBuilder(), "", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams); } - protected StringBuilder makeConditionWhereString(StringBuilder whereString, String prefix, ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException { + protected StringBuilder makeConditionWhereString(StringBuilder whereString, String prefix, ModelEntity modelEntity, + EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, + List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException { ModelViewEntity modelViewEntity = null; if (modelEntity instanceof ModelViewEntity) { modelViewEntity = (ModelViewEntity) modelEntity; @@ -799,18 +828,24 @@ public class GenericDAO { if (!conditions.isEmpty()) { whereString.append(prefix); - whereString.append(EntityCondition.makeCondition(conditions, EntityOperator.AND).makeWhereString(modelEntity, whereEntityConditionParams, this.datasource)); + whereString.append(EntityCondition.makeCondition(conditions, EntityOperator.AND).makeWhereString(modelEntity, + whereEntityConditionParams, this.datasource)); } return whereString; } @Deprecated - protected StringBuilder makeConditionHavingString(ModelEntity modelEntity, EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException { - return makeConditionHavingString(new StringBuilder(), "", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams); + protected StringBuilder makeConditionHavingString(ModelEntity modelEntity, EntityCondition havingEntityCondition, + List<EntityCondition> viewHavingConditions, + List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException { + return makeConditionHavingString(new StringBuilder(), "", modelEntity, havingEntityCondition, viewHavingConditions, + havingEntityConditionParams); } - protected StringBuilder makeConditionHavingString(StringBuilder havingString, String prefix, ModelEntity modelEntity, EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException { + protected StringBuilder makeConditionHavingString(StringBuilder havingString, String prefix, ModelEntity modelEntity, + EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, + List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException { ModelViewEntity modelViewEntity = null; if (modelEntity instanceof ModelViewEntity) { modelViewEntity = (ModelViewEntity) modelEntity; @@ -873,7 +908,8 @@ public class GenericDAO { } public List<GenericValue> selectByMultiRelation(GenericValue value, ModelRelation modelRelationOne, ModelEntity modelEntityOne, - ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) throws GenericEntityException { + ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) + throws GenericEntityException { // get the tables names String atable = modelEntityOne.getTableName(datasource); @@ -904,7 +940,8 @@ public class GenericDAO { if (wheresb.length() > 0) { wheresb.append(" AND "); } - wheresb.append(atable).append(".").append(modelEntityOne.getField(lfname).getColName()).append(" = ").append(ttable).append(".").append(modelEntityTwo.getField(rfname).getColName()); + wheresb.append(atable).append(".").append(modelEntityOne.getField(lfname).getColName()).append(" = ").append(ttable).append(".") + .append(modelEntityTwo.getField(rfname).getColName()); } // construct the source entity qualifier @@ -943,7 +980,7 @@ public class GenericDAO { try (SQLProcessor sqlP = new SQLProcessor(value.getDelegator(), helperInfo)) { sqlP.prepareStatement(sqlsb.toString()); - for (Map.Entry<ModelField, Object> entry: bindMap.entrySet()) { + for (Map.Entry<ModelField, Object> entry : bindMap.entrySet()) { ModelField mf = entry.getKey(); Object curvalue = entry.getValue(); @@ -958,7 +995,7 @@ public class GenericDAO { // loop thru all columns for in one row int idx = 1; - for (String fldname: fldlist) { + for (String fldname : fldlist) { ModelField mf = modelEntityTwo.getField(fldname); SqlJdbcUtil.getValue(sqlP.getResultSet(), idx, mf, gv, modelFieldTypeReader); idx++; @@ -970,11 +1007,14 @@ public class GenericDAO { return retlist; } - public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException { + public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, + EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException { return selectCountByCondition(delegator, modelEntity, whereEntityCondition, havingEntityCondition, null, findOptions); } - public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) throws GenericEntityException { + public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, + EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) + throws GenericEntityException { if (modelEntity == null) { return 0; } @@ -1012,9 +1052,10 @@ public class GenericDAO { if (findOptions.getDistinct()) { // old style, not sensitive to selecting limited columns: sqlBuffer.append("DISTINCT COUNT(*) "); - /* DEJ20100304: the code below was causing problems so the line above may be used instead, but hopefully this is fixed now - * may need varying SQL for different databases, and also in view-entities in some cases it seems to - * cause the "COUNT(DISTINCT " to appear twice, causing an attempt to try to count a count (function="count-distinct", distinct=true in find options) + /* DEJ20100304: the code below was causing problems so the line above may be used instead, but hopefully this is fixed now + * may need varying SQL for different databases, and also in view-entities in some cases it seems to + * cause the "COUNT(DISTINCT " to appear twice, causing an attempt to try to count a count (function="count-distinct", distinct=true in + * find options) */ if (selectFields != null && selectFields.size() > 0) { ModelField firstSelectField = selectFields.get(0); @@ -1024,7 +1065,8 @@ public class GenericDAO { sqlBuffer.append("COUNT(DISTINCT *) "); } else { sqlBuffer.append("COUNT(DISTINCT "); - // this only seems to support a single column, which is not desirable but seems a lot better than no columns or in certain cases all columns + // this only seems to support a single column, which is not desirable but seems a lot better than no columns or in certain + // cases all columns sqlBuffer.append(firstSelectField.getColValue()); // sqlBuffer.append(modelEntity.colNameString(selectFields, ", ", "", datasource.aliasViews)); sqlBuffer.append(")"); @@ -1033,7 +1075,8 @@ public class GenericDAO { sqlBuffer.append("COUNT(DISTINCT *) "); } } else { - // NOTE DEJ20080701 Changed from COUNT(*) to COUNT(1) to improve performance, and should get the same results at least when there is no DISTINCT + // NOTE DEJ20080701 Changed from COUNT(*) to COUNT(1) to improve performance, and should get the same results at least when there is no + // DISTINCT sqlBuffer.append("COUNT(1) "); } @@ -1045,7 +1088,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 @@ -1074,8 +1118,8 @@ public class GenericDAO { } try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) { - sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), - findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows()); + sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), + findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows()); if (verboseOn) { // put this inside an if statement so that we don't have to generate the string when not used... if (Debug.verboseOn()) { @@ -1083,8 +1127,9 @@ public class GenericDAO { } } // set all of the values from the Where EntityCondition - for (EntityConditionParam whereEntityConditionParam: whereEntityConditionParams) { - SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader); + for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) { + SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), + whereEntityConditionParam.getFieldValue(), modelFieldTypeReader); } if (verboseOn) { // put this inside an if statement so that we don't have to generate the string when not used... @@ -1093,8 +1138,9 @@ public class GenericDAO { } } // set all of the values from the Having EntityCondition - for (EntityConditionParam havingEntityConditionParam: havingEntityConditionParams) { - SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader); + for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) { + SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), + havingEntityConditionParam.getFieldValue(), modelFieldTypeReader); } try { sqlP.executeQuery(); @@ -1138,10 +1184,10 @@ public class GenericDAO { int retVal; - sqlP.prepareStatement(sql.toString()); - SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader); - retVal = sqlP.executeUpdate(); - entity.removedFromDatasource(); + sqlP.prepareStatement(sql.toString()); + SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader); + retVal = sqlP.executeUpdate(); + entity.removedFromDatasource(); return retVal; } @@ -1181,7 +1227,9 @@ public class GenericDAO { dbUtil.checkDb(modelEntities, messages, addMissing); } - /** Creates a list of ModelEntity objects based on meta data from the database */ + /** + * Creates a list of ModelEntity objects based on meta data from the database + */ public List<ModelEntity> induceModelFromDb(Collection<String> messages) { DatabaseUtil dbUtil = new DatabaseUtil(this.helperInfo); return dbUtil.induceModelFromDb(messages); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelper.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelper.java index f14bec7..09e885f 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelper.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelper.java @@ -89,7 +89,7 @@ public interface GenericHelper { *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE - * DONE WITH IT (preferably in a finally block), + * DONE WITH IT (preferably in a finally block), * AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION. */ EntityListIterator findListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperDAO.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperDAO.java index b2281ce..925e8a4 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperDAO.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperDAO.java @@ -145,7 +145,7 @@ public class GenericHelperDAO implements GenericHelper { *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE - * DONE WITH IT (preferably in a finally block), + * DONE WITH IT (preferably in a finally block), * AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION. */ @Override diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperInfo.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperInfo.java index ba6f408..c01a588 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperInfo.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/datasource/GenericHelperInfo.java @@ -20,11 +20,10 @@ package org.apache.ofbiz.entity.datasource; /** - * A container for datasource connection information. + * A container for data source connection information. * <p><b>Note that this class is not synchronized.</b> * If multiple threads access a <code>GenericHelperInfo</code> concurrently it must be synchronized externally. - * </p> - * + * </p> */ public final class GenericHelperInfo { private final String entityGroupName; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/ListFinder.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/ListFinder.java index 5ebc710..6af953e 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/ListFinder.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/ListFinder.java @@ -51,7 +51,6 @@ import org.w3c.dom.Element; /** * Uses the delegator to find entity values by a and - * */ @SuppressWarnings("serial") public abstract class ListFinder extends Finder { @@ -90,7 +89,7 @@ public abstract class ListFinder extends Finder { List<? extends Element> orderByElementList = UtilXml.childElementList(element, "order-by"); if (orderByElementList.size() > 0) { orderByExpanderList = new ArrayList<>(orderByElementList.size()); - for (Element orderByElement: orderByElementList) { + for (Element orderByElement : orderByElementList) { orderByExpanderList.add(FlexibleStringExpander.getInstance(orderByElement.getAttribute("field-name"))); } } @@ -99,8 +98,10 @@ public abstract class ListFinder extends Finder { Element limitRangeElement = UtilXml.firstChildElement(element, "limit-range"); Element limitViewElement = UtilXml.firstChildElement(element, "limit-view"); Element useIteratorElement = UtilXml.firstChildElement(element, "use-iterator"); - if ((limitRangeElement != null && limitViewElement != null) || (limitRangeElement != null && useIteratorElement != null) || (limitViewElement != null && useIteratorElement != null)) { - throw new IllegalArgumentException("In entity find by " + label + " element, cannot have more than one of the following: limit-range, limit-view, " + label + " use-iterator"); + if ((limitRangeElement != null && limitViewElement != null) || (limitRangeElement != null && useIteratorElement != null) + || (limitViewElement != null && useIteratorElement != null)) { + throw new IllegalArgumentException("In entity find by " + label + " element, cannot have more than one of the following: limit-range, " + + "limit-view, " + label + " use-iterator"); } if (limitRangeElement != null) { outputHandler = new LimitRange(limitRangeElement); @@ -125,7 +126,8 @@ public abstract class ListFinder extends Finder { String resultSetTypeString = this.resultSetTypeExdr.expandString(context); if (modelEntity == null) { - throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "]."); + throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "]" + + "."); } boolean useCache = "true".equals(useCacheStr); @@ -145,14 +147,17 @@ public abstract class ListFinder extends Finder { if (useCache) { // if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination if (outputHandler instanceof UseIterator) { - Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", MODULE); + Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the " + + "output type. Using cache and ignoring use-iterator setting.", MODULE); outputHandler = new GetAll(); } if (distinct) { - throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true."); + throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to" + + " true."); } if (havingEntityCondition != null) { - throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list)."); + throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a " + + "having-condition-list (can only use a where condition with condition-expr or condition-list)."); } } @@ -162,7 +167,8 @@ public abstract class ListFinder extends Finder { //if fieldsToSelect != null and useCacheBool is true, throw an error if (fieldsToSelect != null && useCache) { - throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when use-cache is set to true"); + throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when " + + "use-cache is set to true"); } // get the list of orderByFields from orderByExpanderList @@ -189,7 +195,8 @@ public abstract class ListFinder extends Finder { boolean useTransaction = true; if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) { Exception newE = new Exception("Stack Trace"); - Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", MODULE); + Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place." + + " Wrap this call in a transaction.", MODULE); useTransaction = false; } @@ -212,9 +219,11 @@ public abstract class ListFinder extends Finder { if (useTransaction) { beganTransaction = TransactionUtil.begin(); } - EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options); + EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, + options); this.outputHandler.handleOutput(eli, context, listAcsr); - // NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see EntityAnd.getChildren() in ModelTree.java) + // NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see + // EntityAnd.getChildren() in ModelTree.java) } catch (GenericEntityException e) { String errMsg = "Failure in by " + label + " find operation, rolling back transaction"; Debug.logError(e, errMsg, MODULE); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/DatabaseUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/DatabaseUtil.java index dc6f0d3..4d7843a 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/DatabaseUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/DatabaseUtil.java @@ -64,23 +64,74 @@ import org.apache.ofbiz.entity.transaction.TransactionUtil; /** * Utilities for Entity Database Maintenance - * */ public class DatabaseUtil { private static final String MODULE = DatabaseUtil.class.getName(); + private static final List<Detection> detections = new ArrayList<>(); + private static final String goodFormatStr; + private static final String badFormatStr; + + static { + try { + detections.add(new Detection("supports transactions", true, "supportsTransactions")); + detections.add(new Detection("isolation None", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_NONE)); + detections.add(new Detection("isolation ReadCommitted", false, "supportsTransactionIsolationLevel", + Connection.TRANSACTION_READ_COMMITTED)); + detections.add(new Detection("isolation ReadUncommitted", false, "supportsTransactionIsolationLevel", + Connection.TRANSACTION_READ_UNCOMMITTED)); + detections.add(new Detection("isolation RepeatableRead", false, "supportsTransactionIsolationLevel", + Connection.TRANSACTION_REPEATABLE_READ)); + detections.add(new Detection("isolation Serializable", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_SERIALIZABLE)); + detections.add(new Detection("forward only type", false, "supportsResultSetType", ResultSet.TYPE_FORWARD_ONLY)); + detections.add(new Detection("scroll sensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_SENSITIVE)); + detections.add(new Detection("scroll insensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_INSENSITIVE)); + detections.add(new Detection("is case sensitive", false, "supportsMixedCaseIdentifiers")); + detections.add(new Detection("stores LowerCase", false, "storesLowerCaseIdentifiers")); + detections.add(new Detection("stores MixedCase", false, "storesMixedCaseIdentifiers")); + detections.add(new Detection("stores UpperCase", false, "storesUpperCaseIdentifiers")); + detections.add(new Detection("max table name length", false, "getMaxTableNameLength")); + detections.add(new Detection("max column name length", false, "getMaxColumnNameLength")); + detections.add(new Detection("concurrent connections", false, "getMaxConnections")); + detections.add(new Detection("concurrent statements", false, "getMaxStatements")); + detections.add(new Detection("ANSI SQL92 Entry", false, "supportsANSI92EntryLevelSQL")); + detections.add(new Detection("ANSI SQL92 Intermediate", false, "supportsANSI92IntermediateSQL")); + detections.add(new Detection("ANSI SQL92 Full", false, "supportsANSI92FullSQL")); + detections.add(new Detection("ODBC SQL Grammar Core", false, "supportsCoreSQLGrammar")); + detections.add(new Detection("ODBC SQL Grammar Extended", false, "supportsExtendedSQLGrammar")); + detections.add(new Detection("ODBC SQL Grammar Minimum", false, "supportsMinimumSQLGrammar")); + detections.add(new Detection("outer joins", true, "supportsOuterJoins")); + detections.add(new Detection("limited outer joins", false, "supportsLimitedOuterJoins")); + detections.add(new Detection("full outer joins", false, "supportsFullOuterJoins")); + detections.add(new Detection("group by", true, "supportsGroupBy")); + detections.add(new Detection("group by not in select", false, "supportsGroupByUnrelated")); + detections.add(new Detection("column aliasing", false, "supportsColumnAliasing")); + detections.add(new Detection("order by not in select", false, "supportsOrderByUnrelated")); + detections.add(new Detection("alter table add column", true, "supportsAlterTableWithAddColumn")); + detections.add(new Detection("non-nullable column", true, "supportsNonNullableColumns")); + //detections.add(new Detection("", false, "", )); + } catch (NoSuchMethodException e) { + throw (InternalError) new InternalError(e.getMessage()).initCause(e); + } + int maxWidth = 0; + for (Detection detection : detections) { + if (detection.name.length() > maxWidth) { + maxWidth = detection.name.length(); + } + } + goodFormatStr = "- %-" + maxWidth + "s [%s]%s"; + badFormatStr = "- %-" + maxWidth + "s [ DETECTION FAILED ]%s"; + } // OFBiz Connections protected ModelFieldTypeReader modelFieldTypeReader = null; protected Datasource datasourceInfo = null; protected GenericHelperInfo helperInfo = null; - // Legacy Connections protected String connectionUrl = null; protected String driverName = null; protected String userName = null; protected String password = null; - boolean isLegacy = false; // OFBiz DatabaseUtil @@ -90,34 +141,18 @@ public class DatabaseUtil { this.datasourceInfo = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); } - protected Connection getConnection() throws SQLException, GenericEntityException { - Connection connection = null; - if (!isLegacy) { - connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); - } else { - connection = getConnection(driverName, connectionUrl, null, userName, password); - } + /* ====================================================================== */ - if (connection == null) { - if (!isLegacy) { - throw new GenericEntityException("No connection available for helper named [" + helperInfo.getHelperFullName() + "]"); - } else { - throw new GenericEntityException("No connection avaialble for URL [" + connectionUrl + "]"); - } - } - if (!TransactionUtil.isTransactionInPlace()) { - connection.setAutoCommit(true); - } - return connection; - } + /* ====================================================================== */ private static Connection getConnection(String driverName, String connectionUrl, Properties props, String userName, - String password) throws SQLException { + String password) throws SQLException { // first register the JDBC driver with the DriverManager if (driverName != null) { if (DriverManager.getDriver(driverName) == null) { try { - Driver driver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).getDeclaredConstructor().newInstance(); + Driver driver = + (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).getDeclaredConstructor().newInstance(); DriverManager.registerDriver(driver); } catch (ReflectiveOperationException e) { Debug.logWarning(e, "Unable to load driver [" + driverName + "]", MODULE); @@ -138,11 +173,41 @@ public class DatabaseUtil { } } + private static String makeTempFieldName(ModelField field) { + String tempName = "tmp_" + field.getName(); + if (tempName.length() > 30) { + tempName = tempName.substring(0, 30); + } + return tempName.toUpperCase(); + } + + protected Connection getConnection() throws SQLException, GenericEntityException { + Connection connection = null; + if (!isLegacy) { + connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); + } else { + connection = getConnection(driverName, connectionUrl, null, userName, password); + } + + if (connection == null) { + if (!isLegacy) { + throw new GenericEntityException("No connection available for helper named [" + helperInfo.getHelperFullName() + "]"); + } else { + throw new GenericEntityException("No connection avaialble for URL [" + connectionUrl + "]"); + } + } + if (!TransactionUtil.isTransactionInPlace()) { + connection.setAutoCommit(true); + } + return connection; + } + protected Connection getConnectionLogged(Collection<String> messages) { try { return getConnection(); } catch (SQLException | GenericEntityException e) { - String message = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String message = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(message, MODULE); if (messages != null) messages.add(message); return null; @@ -153,15 +218,14 @@ public class DatabaseUtil { return this.datasourceInfo; } - /* ====================================================================== */ - - /* ====================================================================== */ - public void checkDb(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) { - checkDb(modelEntities, null, messages, datasourceInfo.getCheckPksOnStart(), (datasourceInfo.getUseForeignKeys() && datasourceInfo.getCheckFksOnStart()), (datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.getCheckFkIndicesOnStart()), addMissing); + checkDb(modelEntities, null, messages, datasourceInfo.getCheckPksOnStart(), + (datasourceInfo.getUseForeignKeys() && datasourceInfo.getCheckFksOnStart()), + (datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.getCheckFkIndicesOnStart()), addMissing); } - public void checkDb(Map<String, ModelEntity> modelEntities, List<String> colWrongSize, List<String> messages, boolean checkPks, boolean checkFks, boolean checkFkIdx, boolean addMissing) { + public void checkDb(Map<String, ModelEntity> modelEntities, List<String> colWrongSize, List<String> messages, boolean checkPks, + boolean checkFks, boolean checkFkIdx, boolean addMissing) { if (isLegacy) { throw new RuntimeException("Cannot run checkDb on a legacy database connection; configure a database helper (entityengine.xml)"); } @@ -219,18 +283,20 @@ public class DatabaseUtil { return; } List<Future<CreateTableCallable>> tableFutures = new LinkedList<>(); - for (ModelEntity entity: modelEntityList) { + for (ModelEntity entity : modelEntityList) { curEnt++; // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { - String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " View Entity " + entity.getEntityName(); + String entMessage = + "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, MODULE); if (messages != null) messages.add(entMessage); continue; - // if never-check is set then don't check it either + // if never-check is set then don't check it either } else if (entity.getNeverCheck()) { - String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName(); + String entMessage = + "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, MODULE); if (messages != null) messages.add(entMessage); continue; @@ -243,8 +309,8 @@ public class DatabaseUtil { } else { tableName = plainTableName; } - String entMessage = "(" + timer.timeSinceLast() + "ms) Checking #" + curEnt + "/" + totalEnt + - " Entity " + entity.getEntityName() + " with table " + tableName; + String entMessage = "(" + timer.timeSinceLast() + "ms) Checking #" + curEnt + "/" + totalEnt + + " Entity " + entity.getEntityName() + " with table " + tableName; Debug.logVerbose(entMessage, MODULE); if (messages != null) messages.add(entMessage); @@ -262,7 +328,7 @@ public class DatabaseUtil { Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); if (colMap != null) { - for (ColumnCheckInfo ccInfo: colMap.values()) { + for (ColumnCheckInfo ccInfo : colMap.values()) { // -list all columns that do not have a corresponding field if (fieldColNames.containsKey(ccInfo.columnName)) { ModelField field = null; @@ -283,7 +349,8 @@ public class DatabaseUtil { if (openParen > 0 && closeParen > 0 && closeParen > openParen) { typeName = fullTypeStr.substring(0, openParen); - if (!("DATETIME".equals(typeName) || "TIME".equals(typeName))) { // for DATETIME and TIME fields the number within the parenthesis doesn't represent the column size + if (!("DATETIME".equals(typeName) || "TIME".equals(typeName))) { // for DATETIME and TIME fields the number + // within the parenthesis doesn't represent the column size if (comma > 0 && comma > openParen && comma < closeParen) { String csStr = fullTypeStr.substring(openParen + 1, comma); try { @@ -319,15 +386,16 @@ public class DatabaseUtil { // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay just compare with ignore case if (!ccInfo.typeName.equalsIgnoreCase(typeName)) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" - + entity.getEntityName() + "] is of type [" + ccInfo.typeName + "] in the database, but is defined as type [" - + typeName + "] in the entity definition."; + + entity.getEntityName() + "] is of type [" + ccInfo.typeName + "] in the database, but is " + + "defined as type [" + typeName + "] in the entity definition."; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } if (columnSize != -1 && ccInfo.columnSize != -1 && columnSize != ccInfo.columnSize && (columnSize * 3) != ccInfo.columnSize) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" - + entity.getEntityName() + "] has a column size of [" + ccInfo.columnSize + - "] in the database, but is defined to have a column size of [" + columnSize + "] in the entity definition."; + + entity.getEntityName() + "] has a column size of [" + ccInfo.columnSize + + "] in the database, but is defined to have a column size of [" + columnSize + "] in the " + + "entity definition."; Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); if (columnSize > ccInfo.columnSize && colWrongSize != null) { @@ -337,8 +405,9 @@ public class DatabaseUtil { } if (decimalDigits != -1 && decimalDigits != ccInfo.decimalDigits) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" - + entity.getEntityName() + "] has a decimalDigits of [" + ccInfo.decimalDigits + - "] in the database, but is defined to have a decimalDigits of [" + decimalDigits + "] in the entity definition."; + + entity.getEntityName() + "] has a decimalDigits of [" + ccInfo.decimalDigits + + "] in the database, but is defined to have a decimalDigits of [" + decimalDigits + "] in the" + + " entity definition."; Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); } @@ -346,24 +415,33 @@ public class DatabaseUtil { // do primary key matching check if (checkPks && ccInfo.isPk && !field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" - + entity.getEntityName() + "] IS a primary key in the database, but IS NOT a primary key in the entity definition. The primary key for this table needs to be re-created or modified so that this column is NOT part of the primary key."; + + entity.getEntityName() + "] IS a primary key in the database, but IS NOT a primary key in " + + "the entity definition. The primary key for this table needs to be re-created or modified so " + + "that this column is NOT part of the primary key."; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } if (checkPks && !ccInfo.isPk && field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" - + entity.getEntityName() + "] IS NOT a primary key in the database, but IS a primary key in the entity definition. The primary key for this table needs to be re-created or modified to add this column to the primary key. Note that data may need to be added first as a primary key column cannot have an null values."; + + entity.getEntityName() + "] IS NOT a primary key in the database, but IS a primary key in " + + "the entity definition. The primary key for this table needs to be re-created or modified to " + + "add this column to the primary key. Note that data may need to be added first as a primary " + + "key column cannot have an null values."; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } } else { - String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + - "] has a field type name of [" + field.getType() + "] which is not found in the field type definitions"; + String message = + "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + + "] has a field type name of [" + field.getType() + "] which is not found in the field type definitions"; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } } else { - String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] exists in the database but has no corresponding field" + ((checkPks && ccInfo.isPk) ? " (and it is a PRIMARY KEY COLUMN)" : ""); + String message = + "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] " + + "exists in the database but has no corresponding field" + ((checkPks && ccInfo.isPk) + ? " (and it is a PRIMARY KEY COLUMN)" : ""); Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); } @@ -371,7 +449,9 @@ public class DatabaseUtil { // -display message if number of table columns does not match number of entity fields if (colMap.size() != entity.getFieldsSize()) { - String message = "Entity [" + entity.getEntityName() + "] has " + entity.getFieldsSize() + " fields but table [" + tableName + "] has " + colMap.size() + " columns."; + String message = + "Entity [" + entity.getEntityName() + "] has " + entity.getFieldsSize() + " fields but table [" + tableName + "] " + + "has " + colMap.size() + " columns."; Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); } @@ -379,7 +459,8 @@ public class DatabaseUtil { // -list all fields that do not have a corresponding column for (ModelField field : fieldColNames.values()) { - String message = "Field [" + field.getName() + "] of entity [" + entity.getEntityName() + "] is missing its corresponding column [" + field.getColName() + "]" + (field.getIsPk() ? " (and it is a PRIMARY KEY FIELD)" : ""); + String message = "Field [" + field.getName() + "] of entity [" + entity.getEntityName() + "] is missing its corresponding " + + "column [" + field.getColName() + "]" + (field.getIsPk() ? " (and it is a PRIMARY KEY FIELD)" : ""); Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); @@ -393,7 +474,9 @@ public class DatabaseUtil { Debug.logError(message, MODULE); if (messages != null) messages.add(message); } else { - message = "Added column [" + field.getColName() + "] to table [" + tableName + "]" + (field.getIsPk() ? " (NOTE: this is a PRIMARY KEY FIELD, but the primary key was not updated automatically (not considered a safe operation), be sure to fill in any needed data and re-create the primary key)" : ""); + message = "Added column [" + field.getColName() + "] to table [" + tableName + "]" + (field.getIsPk() + ? " (NOTE: this is a PRIMARY KEY FIELD, but the primary key was not updated automatically (not considered a" + + "safe operation), be sure to fill in any needed data and re-create the primary key)" : ""); Debug.logImportant(message, MODULE); if (messages != null) messages.add(message); } @@ -410,14 +493,14 @@ public class DatabaseUtil { } } } - for (CreateTableCallable tableCallable: ExecutionPool.getAllFutures(tableFutures)) { + for (CreateTableCallable tableCallable : ExecutionPool.getAllFutures(tableFutures)) { tableCallable.updateData(messages, entitiesAdded); } timer.timerString("After Individual Table/Column Check"); // -list all tables that do not have a corresponding entity - for (String tableName: tableNames) { + for (String tableName : tableNames) { String message = "Table named [" + tableName + "] exists in the database but has no corresponding entity"; Debug.logWarning(message, MODULE); if (messages != null) messages.add(message); @@ -427,7 +510,7 @@ public class DatabaseUtil { if (datasourceInfo.getUseForeignKeyIndices()) { int totalFkIndices = 0; List<Future<AbstractCountingCallable>> fkIndicesFutures = new LinkedList<>(); - for (ModelEntity curEntity: entitiesAdded) { + for (ModelEntity curEntity : entitiesAdded) { if (curEntity.getRelationsOneSize() > 0) { fkIndicesFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { @Override @@ -438,7 +521,7 @@ public class DatabaseUtil { })); } } - for (AbstractCountingCallable fkIndicesCallable: ExecutionPool.getAllFutures(fkIndicesFutures)) { + for (AbstractCountingCallable fkIndicesCallable : ExecutionPool.getAllFutures(fkIndicesFutures)) { totalFkIndices += fkIndicesCallable.updateData(messages); } if (totalFkIndices > 0) Debug.logImportant("==== TOTAL Foreign Key Indices Created: " + totalFkIndices, MODULE); @@ -447,8 +530,9 @@ public class DatabaseUtil { // for each newly added table, add fks if (datasourceInfo.getUseForeignKeys()) { int totalFks = 0; - for (ModelEntity curEntity: entitiesAdded) { - totalFks += this.createForeignKeys(curEntity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); + for (ModelEntity curEntity : entitiesAdded) { + totalFks += this.createForeignKeys(curEntity, modelEntities, datasourceInfo.getConstraintNameClipLength(), + datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); } if (totalFks > 0) Debug.logImportant("==== TOTAL Foreign Keys Created: " + totalFks, MODULE); } @@ -457,7 +541,7 @@ public class DatabaseUtil { if (datasourceInfo.getUseIndices()) { int totalDis = 0; List<Future<AbstractCountingCallable>> disFutures = new LinkedList<>(); - for (ModelEntity curEntity: entitiesAdded) { + for (ModelEntity curEntity : entitiesAdded) { if (curEntity.getIndexesSize() > 0) { disFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { @Override @@ -469,7 +553,7 @@ public class DatabaseUtil { } } - for (AbstractCountingCallable disCallable: ExecutionPool.getAllFutures(disFutures)) { + for (AbstractCountingCallable disCallable : ExecutionPool.getAllFutures(disFutures)) { totalDis += disCallable.updateData(messages); } if (totalDis > 0) Debug.logImportant("==== TOTAL Declared Indices Created: " + totalDis, MODULE); @@ -477,7 +561,7 @@ public class DatabaseUtil { // make sure each one-relation has an FK if (checkFks) { - //if (!justColumns && datasourceInfo.getUseForeignKeys() && datasourceInfo.checkForeignKeysOnStart) { + //if (!justColumns && datasourceInfo.getUseForeignKeys() && datasourceInfo.checkForeignKeysOnStart) { // NOTE: This ISN'T working for Postgres or MySQL, who knows about others, may be from JDBC driver bugs... int numFksCreated = 0; // TODO: check each key-map to make sure it exists in the FK, if any differences warn and then remove FK and recreate it @@ -493,7 +577,7 @@ public class DatabaseUtil { Debug.logVerbose("Ref Table Info Map is null", MODULE); } } else { - for (ModelEntity entity: modelEntityList) { + for (ModelEntity entity : modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { @@ -541,9 +625,12 @@ public class DatabaseUtil { } if (addMissing) { - String errMsg = createForeignKey(entity, modelRelation, relModelEntity, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred()); + String errMsg = createForeignKey(entity, modelRelation, relModelEntity, + datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), + datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(errMsg)) { - String message = "Could not create foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; + String message = + "Could not create foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } else { @@ -564,7 +651,7 @@ public class DatabaseUtil { // show foreign key references that exist but are unknown if (rcInfoMap != null) { - for (String rcKeyLeft: rcInfoMap.keySet()) { + for (String rcKeyLeft : rcInfoMap.keySet()) { String message = "Unknown Foreign Key Constraint " + rcKeyLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, MODULE); if (messages != null) messages.add(message); @@ -579,7 +666,7 @@ public class DatabaseUtil { // make sure each one-relation has an index if (checkFkIdx || datasourceInfo.getCheckIndicesOnStart()) { - //if (!justColumns && datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.checkFkIndicesOnStart) { + //if (!justColumns && datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.checkFkIndicesOnStart) { int numIndicesCreated = 0; // TODO: check each key-map to make sure it exists in the index, if any differences warn and then remove the index and recreate it @@ -595,7 +682,7 @@ public class DatabaseUtil { Debug.logVerbose("Ref Table Info Map is null", MODULE); } } else { - for (ModelEntity entity: modelEntityList) { + for (ModelEntity entity : modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { @@ -644,11 +731,14 @@ public class DatabaseUtil { if (addMissing) { String errMsg = createForeignKeyIndex(entity, modelRelation, datasourceInfo.getConstraintNameClipLength()); if (UtilValidate.isNotEmpty(errMsg)) { - String message = "Could not create foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; + String message = + "Could not create foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]:" + + " " + errMsg; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } else { - String message = "Created foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; + String message = + "Created foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, MODULE); if (messages != null) messages.add(message); createdConstraints = true; @@ -686,7 +776,8 @@ public class DatabaseUtil { if (addMissing) { String errMsg = createDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(errMsg)) { - String message = "Could not create index " + relIndexName + " for entity [" + entity.getEntityName() + "]: " + errMsg; + String message = "Could not create index " + relIndexName + " for entity [" + entity.getEntityName() + "]: " + + errMsg; Debug.logError(message, MODULE); if (messages != null) messages.add(message); } else { @@ -707,7 +798,7 @@ public class DatabaseUtil { } // show index key references that exist but are unknown - for (String indexLeft: tableIndexList) { + for (String indexLeft : tableIndexList) { String message = "Unknown Index " + indexLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, MODULE); if (messages != null) messages.add(message); @@ -722,7 +813,9 @@ public class DatabaseUtil { timer.timerString("Finished Checking Entity Database"); } - /** Creates a list of ModelEntity objects based on meta data from the database */ + /** + * Creates a list of ModelEntity objects based on meta data from the database + */ public List<ModelEntity> induceModelFromDb(Collection<String> messages) { ExecutorService executor = Executors.newFixedThreadPool(datasourceInfo.getMaxWorkerPoolSize()); @@ -740,7 +833,7 @@ public class DatabaseUtil { boolean isCaseSensitive = getIsCaseSensitive(messages); // iterate over the table names is alphabetical order - for (String tableName: new TreeSet<>(colInfo.keySet())) { + for (String tableName : new TreeSet<>(colInfo.keySet())) { Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); ModelEntity newEntity = new ModelEntity(tableName, colMap, modelFieldTypeReader, isCaseSensitive); newEntList.add(newEntity); @@ -792,80 +885,6 @@ public class DatabaseUtil { return dbData; } - private static final List<Detection> detections = new ArrayList<>(); - private static final String goodFormatStr; - private static final String badFormatStr; - - private static class Detection { - protected final String name; - protected final boolean required; - protected final Method method; - protected final Object[] params; - - protected Detection(String name, boolean required, String methodName, Object... params) throws NoSuchMethodException { - this.name = name; - this.required = required; - Class<?>[] paramTypes = new Class<?>[params.length]; - for (int i = 0; i < params.length; i++) { - Class<?> paramType = params[i].getClass(); - if (paramType == Integer.class) { - paramType = Integer.TYPE; - } - paramTypes[i] = paramType; - } - method = DatabaseMetaData.class.getMethod(methodName, paramTypes); - this.params = params; - } - } - - static { - try { - detections.add(new Detection("supports transactions", true, "supportsTransactions")); - detections.add(new Detection("isolation None", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_NONE)); - detections.add(new Detection("isolation ReadCommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_COMMITTED)); - detections.add(new Detection("isolation ReadUncommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_UNCOMMITTED)); - detections.add(new Detection("isolation RepeatableRead", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_REPEATABLE_READ)); - detections.add(new Detection("isolation Serializable", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_SERIALIZABLE)); - detections.add(new Detection("forward only type", false, "supportsResultSetType", ResultSet.TYPE_FORWARD_ONLY)); - detections.add(new Detection("scroll sensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_SENSITIVE)); - detections.add(new Detection("scroll insensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_INSENSITIVE)); - detections.add(new Detection("is case sensitive", false, "supportsMixedCaseIdentifiers")); - detections.add(new Detection("stores LowerCase", false, "storesLowerCaseIdentifiers")); - detections.add(new Detection("stores MixedCase", false, "storesMixedCaseIdentifiers")); - detections.add(new Detection("stores UpperCase", false, "storesUpperCaseIdentifiers")); - detections.add(new Detection("max table name length", false, "getMaxTableNameLength")); - detections.add(new Detection("max column name length", false, "getMaxColumnNameLength")); - detections.add(new Detection("concurrent connections", false, "getMaxConnections")); - detections.add(new Detection("concurrent statements", false, "getMaxStatements")); - detections.add(new Detection("ANSI SQL92 Entry", false, "supportsANSI92EntryLevelSQL")); - detections.add(new Detection("ANSI SQL92 Intermediate", false, "supportsANSI92IntermediateSQL")); - detections.add(new Detection("ANSI SQL92 Full", false, "supportsANSI92FullSQL")); - detections.add(new Detection("ODBC SQL Grammar Core", false, "supportsCoreSQLGrammar")); - detections.add(new Detection("ODBC SQL Grammar Extended", false, "supportsExtendedSQLGrammar")); - detections.add(new Detection("ODBC SQL Grammar Minimum", false, "supportsMinimumSQLGrammar")); - detections.add(new Detection("outer joins", true, "supportsOuterJoins")); - detections.add(new Detection("limited outer joins", false, "supportsLimitedOuterJoins")); - detections.add(new Detection("full outer joins", false, "supportsFullOuterJoins")); - detections.add(new Detection("group by", true, "supportsGroupBy")); - detections.add(new Detection("group by not in select", false, "supportsGroupByUnrelated")); - detections.add(new Detection("column aliasing", false, "supportsColumnAliasing")); - detections.add(new Detection("order by not in select", false, "supportsOrderByUnrelated")); - detections.add(new Detection("alter table add column", true, "supportsAlterTableWithAddColumn")); - detections.add(new Detection("non-nullable column", true, "supportsNonNullableColumns")); - //detections.add(new Detection("", false, "", )); - } catch (NoSuchMethodException e) { - throw (InternalError) new InternalError(e.getMessage()).initCause(e); - } - int maxWidth = 0; - for (Detection detection: detections) { - if (detection.name.length() > maxWidth) { - maxWidth = detection.name.length(); - } - } - goodFormatStr = "- %-" + maxWidth + "s [%s]%s"; - badFormatStr = "- %-" + maxWidth + "s [ DETECTION FAILED ]%s"; - } - public void printDbMiscData(DatabaseMetaData dbData, Connection con) { if (dbData == null) { return; @@ -890,7 +909,7 @@ public class DatabaseUtil { } // Db/Driver support settings Debug.logInfo("Database Setting/Support Information (those with a * should be true):", MODULE); - for (Detection detection: detections) { + for (Detection detection : detections) { String requiredFlag = detection.required ? "*" : ""; try { Object result = detection.method.invoke(dbData, detection.params); @@ -994,12 +1013,12 @@ public class DatabaseUtil { // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay for now just do a compare with equalsIgnoreCase String tableType = tableSet.getString("TABLE_TYPE"); // only allow certain table types - if (tableType != null - && !"TABLE".equalsIgnoreCase(tableType) - && !"VIEW".equalsIgnoreCase(tableType) - && !"ALIAS".equalsIgnoreCase(tableType) - && !"SYNONYM".equalsIgnoreCase(tableType) - && !"BASE TABLE".equalsIgnoreCase(tableType)) { + if (tableType != null + && !"TABLE".equalsIgnoreCase(tableType) + && !"VIEW".equalsIgnoreCase(tableType) + && !"ALIAS".equalsIgnoreCase(tableType) + && !"SYNONYM".equalsIgnoreCase(tableType) + && !"BASE TABLE".equalsIgnoreCase(tableType)) { continue; } // String remarks = tableSet.getString("REMARKS"); @@ -1036,7 +1055,8 @@ public class DatabaseUtil { return tableNames; } - private Map<String, Map<String, ColumnCheckInfo>> getColumnInfo(Set<String> tableNames, boolean getPks, Collection<String> messages, ExecutorService executor) { + private Map<String, Map<String, ColumnCheckInfo>> getColumnInfo(Set<String> tableNames, boolean getPks, Collection<String> messages, + ExecutorService executor) { // if there are no tableNames, don't even try to get the columns if (tableNames.size() == 0) { return new HashMap<>(); @@ -1150,22 +1170,25 @@ public class DatabaseUtil { if (getPks) { int pkCount = 0; - // first try getting all at once for databases that support that and can generally perform WAY better, if that fails get one at a time so it will at least work + // first try getting all at once for databases that support that and can generally perform WAY better, if that fails get one at + // a time so it will at least work try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, null)) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { - Debug.logInfo("Error getting primary key info from database with null tableName, will try other means: " + e1.toString(), MODULE); + Debug.logInfo("Error getting primary key info from database with null tableName, will try other means: " + e1.toString(), + MODULE); } if (pkCount == 0) { try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, "%")) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { - Debug.logInfo("Error getting primary key info from database with % tableName, will try other means: " + e1.toString(), MODULE); + Debug.logInfo("Error getting primary key info from database with % tableName, will try other means: " + e1.toString(), + MODULE); } } if (pkCount == 0) { Debug.logInfo("Searching in " + tableNames.size() + " tables for primary key fields ...", MODULE); - for (String curTable: tableNames) { + for (String curTable : tableNames) { curTable = curTable.substring(curTable.indexOf('.') + 1); //cut off schema name try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, curTable)) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); @@ -1198,7 +1221,8 @@ public class DatabaseUtil { } } - public int checkPrimaryKeyInfo(ResultSet rsPks, String lookupSchemaName, boolean needsUpperCase, Map<String, Map<String, ColumnCheckInfo>> colInfo, Collection<String> messages) throws SQLException { + public int checkPrimaryKeyInfo(ResultSet rsPks, String lookupSchemaName, boolean needsUpperCase, + Map<String, Map<String, ColumnCheckInfo>> colInfo, Collection<String> messages) throws SQLException { int pkCount = 0; while (rsPks.next()) { pkCount++; @@ -1427,7 +1451,7 @@ public class DatabaseUtil { try { int totalIndices = 0; String lookupSchemaName = getSchemaName(dbData); - for (String curTableName: tableNames) { + for (String curTableName : tableNames) { if (lookupSchemaName != null) { curTableName = curTableName.substring(lookupSchemaName.length() + 1); } @@ -1438,7 +1462,8 @@ public class DatabaseUtil { // true for approximate, don't really care if stats are up-to-date rsCols = dbData.getIndexInfo(null, lookupSchemaName, needsUpperCase[0] ? curTableName.toLowerCase() : curTableName, false, true); } catch (Exception e) { - Debug.logWarning(e, "Error getting index info for table: " + curTableName + " using lookupSchemaName " + lookupSchemaName, MODULE); + Debug.logWarning(e, "Error getting index info for table: " + curTableName + " using lookupSchemaName " + lookupSchemaName, + MODULE); } while (rsCols != null && rsCols.next()) { @@ -1522,71 +1547,6 @@ public class DatabaseUtil { return indexInfo; } - private class CreateTableCallable implements Callable<CreateTableCallable> { - private final ModelEntity entity; - private final Map<String, ModelEntity> modelEntities; - private final String tableName; - private String message; - private boolean success; - - protected CreateTableCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities, String tableName) { - this.entity = entity; - this.modelEntities = modelEntities; - this.tableName = tableName; - } - - @Override - public CreateTableCallable call() throws Exception { - String errMsg = createTable(entity, modelEntities, false); - if (UtilValidate.isNotEmpty(errMsg)) { - this.success = false; - this.message = "Could not create table [" + tableName + "]: " + errMsg; - Debug.logError(this.message, MODULE); - } else { - this.success = true; - this.message = "Created table [" + tableName + "]"; - Debug.logImportant(this.message, MODULE); - } - return this; - } - - protected void updateData(Collection<String> messages, List<ModelEntity> entitiesAdded) { - if (this.success) { - entitiesAdded.add(entity); - if (messages != null) { - messages.add(this.message); - } - } else { - if (messages != null) { - messages.add(this.message); - } - } - } - } - - private abstract class AbstractCountingCallable implements Callable<AbstractCountingCallable> { - protected final ModelEntity entity; - protected final Map<String, ModelEntity> modelEntities; - protected final List<String> messages = new LinkedList<>(); - protected int count; - - protected AbstractCountingCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities) { - this.entity = entity; - this.modelEntities = modelEntities; - } - - protected int updateData(Collection<String> messages) { - if (messages != null && UtilValidate.isNotEmpty(this.messages)) { - this.messages.addAll(messages); - } - return count; - } - } - - /* ====================================================================== */ - - /* ====================================================================== */ - public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) { if (entity == null) { return "ModelEntity was null and is required to create a table"; @@ -1603,7 +1563,8 @@ public class DatabaseUtil { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { - return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."; + return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not " + + "creating table."; } sqlBuf.append(field.getColName()); @@ -1653,7 +1614,8 @@ public class DatabaseUtil { if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { - Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), MODULE); + Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName() + , MODULE); continue; } if (relModelEntity instanceof ModelViewEntity) { @@ -1661,7 +1623,10 @@ public class DatabaseUtil { continue; } - String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred()); + String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, + this.datasourceInfo.getConstraintNameClipLength(), + this.datasourceInfo.getFkStyle(), + this.datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(fkConstraintClause)) { sqlBuf.append(", "); sqlBuf.append(fkConstraintClause); @@ -1676,7 +1641,7 @@ public class DatabaseUtil { // if there is a tableType, add the TYPE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) { - // jaz:20101229 - This appears to be only used by mysql and now mysql has + // jaz:20101229 - This appears to be only used by mysql and now mysql has // deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is // changed to ENGINE which is supported starting at 4.1 sqlBuf.append(" ENGINE "); @@ -1706,7 +1671,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -1745,6 +1711,10 @@ public class DatabaseUtil { } } + /* ====================================================================== */ + + /* ====================================================================== */ + public String addColumn(ModelEntity entity, ModelField field) { if (entity == null || field == null) return "ModelEntity or ModelField where null, cannot add column"; @@ -1755,7 +1725,8 @@ public class DatabaseUtil { ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { - return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not adding column."; + return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not adding " + + "column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); @@ -1783,7 +1754,7 @@ public class DatabaseUtil { if (Debug.infoOn()) { Debug.logInfo("[addColumn] sql=" + sql, MODULE); } - try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql); } catch (SQLException e) { // if that failed try the alternate syntax real quick @@ -1812,18 +1783,20 @@ public class DatabaseUtil { if (Debug.infoOn()) { Debug.logInfo("[addColumn] sql failed, trying sql2=" + sql2, MODULE); } - try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql2); } catch (SQLException e2) { // if this also fails report original error, not this error... return "SQL Exception while executing the following:\n" + sql + "\nError was: " + e2.toString(); } catch (GenericEntityException e2) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e2.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]..." + + " Error was: " + e2.toString(); Debug.logError(e2, errMsg, MODULE); return errMsg; } } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -1840,7 +1813,8 @@ public class DatabaseUtil { ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { - return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not renaming column."; + return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not " + + "renaming column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); @@ -1861,7 +1835,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -1940,7 +1915,7 @@ public class DatabaseUtil { if (messages == null) messages = new ArrayList<>(); - for (String fieldInfo: fieldsWrongSize) { + for (String fieldInfo : fieldsWrongSize) { String entityName = fieldInfo.substring(0, fieldInfo.indexOf('.')); String fieldName = fieldInfo.substring(fieldInfo.indexOf('.') + 1); @@ -1950,16 +1925,6 @@ public class DatabaseUtil { } } - private static String makeTempFieldName(ModelField field) { - String tempName = "tmp_" + field.getName(); - if (tempName.length() > 30) { - tempName = tempName.substring(0, 30); - } - return tempName.toUpperCase(); - } - - /* ====================================================================== */ - /* ====================================================================== */ public String makePkConstraintName(ModelEntity entity, int constraintNameClipLength) { String pkName = "PK_" + entity.getPlainTableName(); @@ -1998,10 +1963,15 @@ public class DatabaseUtil { } /* ====================================================================== */ + + /* ====================================================================== */ public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, List<String> messages) { - return this.createForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); + return this.createForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), + datasourceInfo.getUseFkInitiallyDeferred(), messages); } - public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred, List<String> messages) { + + public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, + boolean useFkInitiallyDeferred, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to create foreign keys for a table"; Debug.logError(errMsg, MODULE); @@ -2031,7 +2001,8 @@ public class DatabaseUtil { continue; } if (relModelEntity instanceof ModelViewEntity) { - String errMsg = "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); + String errMsg = + "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); Debug.logError(errMsg, MODULE); if (messages != null) messages.add(errMsg); continue; @@ -2057,12 +2028,14 @@ public class DatabaseUtil { return fksCreated; } - public String createForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { + public String createForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, + String fkStyle, boolean useFkInitiallyDeferred) { // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); - String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred); + String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, + useFkInitiallyDeferred); if (UtilValidate.isEmpty(fkConstraintClause)) { return "Error creating foreign key constraint clause, see log for details"; } @@ -2078,14 +2051,16 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } return null; } - public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { + public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, + String fkStyle, boolean useFkInitiallyDeferred) { // make the two column lists StringBuilder mainCols = new StringBuilder(); StringBuilder relCols = new StringBuilder(); @@ -2194,7 +2169,8 @@ public class DatabaseUtil { continue; } if (relModelEntity instanceof ModelViewEntity) { - String errMsg = "Error removing foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); + String errMsg = + "Error removing foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); if (messages != null) messages.add(errMsg); Debug.logError(errMsg, MODULE); continue; @@ -2232,7 +2208,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -2292,7 +2269,8 @@ public class DatabaseUtil { } catch (SQLException e) { return "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); } catch (GenericEntityException e) { - return "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + return "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error " + + "was: " + e.toString(); } } else { message = "No primary-key defined for table [" + entity.getEntityName() + "]"; @@ -2342,7 +2320,8 @@ public class DatabaseUtil { sqlBuf.append(" CASCADE"); } else { sqlBuf.append(" PRIMARY KEY"); - // DEJ20050502 not sure why this is here, shouldn't be needed and some dbs don't support like this, ie when used with PRIMARY KEY: sqlBuf.append(" CASCADE"); + // DEJ20050502 not sure why this is here, shouldn't be needed and some dbs don't support like this, ie when used with PRIMARY KEY: + // sqlBuf.append(" CASCADE"); } if (Debug.verboseOn()) { @@ -2355,7 +2334,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]..." + + " Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -2367,8 +2347,7 @@ public class DatabaseUtil { return message; } - /* ====================================================================== */ - /* ====================================================================== */ + /** create declared indices */ public int createDeclaredIndices(ModelEntity entity, List<String> messages) { if (entity == null) { String message = "ModelEntity was null and is required to create declared indices for a table"; @@ -2407,7 +2386,7 @@ public class DatabaseUtil { } return dinsCreated; } - + /** create declared index */ public String createDeclaredIndex(ModelEntity entity, ModelIndex modelIndex) { String createIndexSql = makeIndexClause(entity, modelIndex); if (Debug.verboseOn()) { @@ -2421,13 +2400,14 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } return null; } - + /** make index clause */ public String makeIndexClause(ModelEntity entity, ModelIndex modelIndex) { StringBuilder mainCols = new StringBuilder(); @@ -2508,8 +2488,8 @@ public class DatabaseUtil { StringBuilder indexSqlBuf = new StringBuilder("DROP INDEX "); String tableName = entity.getTableName(datasourceInfo); - String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : - tableName.substring(0, tableName.indexOf('.')); + String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" + : tableName.substring(0, tableName.indexOf('.')); indexSqlBuf.append(schemaName); indexSqlBuf.append("."); @@ -2527,7 +2507,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -2597,7 +2578,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -2611,7 +2593,8 @@ public class DatabaseUtil { ModelField mainField = entity.getField(keyMap.getFieldName()); if (mainField == null) { - Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", MODULE); + Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", MODULE); return null; } @@ -2682,8 +2665,8 @@ public class DatabaseUtil { String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); String tableName = entity.getTableName(datasourceInfo); - String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : - tableName.substring(0, tableName.indexOf('.')); + String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" + : tableName.substring(0, tableName.indexOf('.')); if (UtilValidate.isNotEmpty(schemaName)) { indexSqlBuf.append(schemaName); @@ -2704,7 +2687,8 @@ public class DatabaseUtil { Debug.logError(e, errMsg, MODULE); return errMsg; } catch (GenericEntityException e) { - String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); + String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... " + + "Error was: " + e.toString(); Debug.logError(e, errMsg, MODULE); return errMsg; } @@ -2735,7 +2719,8 @@ public class DatabaseUtil { return; } if (UtilValidate.isEmpty(this.datasourceInfo.getCharacterSet()) && UtilValidate.isEmpty(this.datasourceInfo.getCollate())) { - messages.add("Not setting character-set and collate for entity [" + entity.getEntityName() + "], options not specified in the datasource definition in the entityengine.xml file."); + messages.add("Not setting character-set and collate for entity [" + entity.getEntityName() + "], options not specified in the " + + "datasource definition in the entityengine.xml file."); return; } @@ -2776,7 +2761,8 @@ public class DatabaseUtil { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { - messages.add("Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."); + messages.add("Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + + "], not creating table."); continue; } if (!"String".equals(type.getJavaType()) && !"java.lang.String".equals(type.getJavaType())) { @@ -2801,7 +2787,7 @@ public class DatabaseUtil { sqlBuf.append(this.datasourceInfo.getCollate()); } - if (field.getIsPk() || field.getIsNotNull()) { + if (field.getIsPk() || field.getIsNotNull()) { if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) { sqlBuf.append(" CONSTRAINT NOT NULL"); } else { @@ -2825,6 +2811,28 @@ public class DatabaseUtil { } } + private static class Detection { + protected final String name; + protected final boolean required; + protected final Method method; + protected final Object[] params; + + protected Detection(String name, boolean required, String methodName, Object... params) throws NoSuchMethodException { + this.name = name; + this.required = required; + Class<?>[] paramTypes = new Class<?>[params.length]; + for (int i = 0; i < params.length; i++) { + Class<?> paramType = params[i].getClass(); + if (paramType == Integer.class) { + paramType = Integer.TYPE; + } + paramTypes[i] = paramType; + } + method = DatabaseMetaData.class.getMethod(methodName, paramTypes); + this.params = params; + } + } + /* ====================================================================== */ /* ====================================================================== */ @SuppressWarnings("serial") @@ -2860,12 +2868,16 @@ public class DatabaseUtil { public static class ReferenceCheckInfo implements Serializable { public String pkTableName; - /** Comma separated list of column names in the related tables primary key */ + /** + * Comma separated list of column names in the related tables primary key + */ public String pkColumnName; public String fkName; public String fkTableName; - /** Comma separated list of column names in the primary tables foreign keys */ + /** + * Comma separated list of column names in the primary tables foreign keys + */ public String fkColumnName; @Override @@ -2873,4 +2885,65 @@ public class DatabaseUtil { return "FK Reference from table " + fkTableName + " called " + fkName + " to PK in table " + pkTableName; } } + + private class CreateTableCallable implements Callable<CreateTableCallable> { + private final ModelEntity entity; + private final Map<String, ModelEntity> modelEntities; + private final String tableName; + private String message; + private boolean success; + + protected CreateTableCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities, String tableName) { + this.entity = entity; + this.modelEntities = modelEntities; + this.tableName = tableName; + } + + @Override + public CreateTableCallable call() throws Exception { + String errMsg = createTable(entity, modelEntities, false); + if (UtilValidate.isNotEmpty(errMsg)) { + this.success = false; + this.message = "Could not create table [" + tableName + "]: " + errMsg; + Debug.logError(this.message, MODULE); + } else { + this.success = true; + this.message = "Created table [" + tableName + "]"; + Debug.logImportant(this.message, MODULE); + } + return this; + } + + protected void updateData(Collection<String> messages, List<ModelEntity> entitiesAdded) { + if (this.success) { + entitiesAdded.add(entity); + if (messages != null) { + messages.add(this.message); + } + } else { + if (messages != null) { + messages.add(this.message); + } + } + } + } + + private abstract class AbstractCountingCallable implements Callable<AbstractCountingCallable> { + protected final ModelEntity entity; + protected final Map<String, ModelEntity> modelEntities; + protected final List<String> messages = new LinkedList<>(); + protected int count; + + protected AbstractCountingCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities) { + this.entity = entity; + this.modelEntities = modelEntities; + } + + protected int updateData(Collection<String> messages) { + if (messages != null && UtilValidate.isNotEmpty(this.messages)) { + this.messages.addAll(messages); + } + return count; + } + } } 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 22a0e96..1dc27e5 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 @@ -739,7 +739,7 @@ public abstract class JdbcValueHandler<T> { * don't support sub-second precision. If the date-time field type * is a <code>CHAR(30)</code> SQL type, <code>java.sql.Timestamp</code>s * will be stored as JDBC timestamp escape format strings - * (<code>yyyy-mm-dd hh:mm:ss.fffffffff</code>), referenced to UTC.</p> + * (<code>yyyy-mm-dd hh:mm:ss.fffffffff</code>), referenced to UTC.</p> */ protected static class TimestampJdbcValueHandler extends JdbcValueHandler<java.sql.Timestamp> { protected TimestampJdbcValueHandler(int jdbcType) { 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 b3ba25b..a1a4b70 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 @@ -339,8 +339,8 @@ public class SQLProcessor implements AutoCloseable { } } catch (GenericTransactionException e) { // nevermind, don't worry about it, but print the exc anyway - Debug.logWarning("[SQLProcessor.getConnection]: Exception was thrown trying to check " + - "transaction status: " + e.toString(), MODULE); + Debug.logWarning("[SQLProcessor.getConnection]: Exception was thrown trying to check " + + "transaction status: " + e.toString(), MODULE); } if (Debug.verboseOn()) { @@ -552,8 +552,8 @@ public class SQLProcessor implements AutoCloseable { } } catch (SQLException sqle) { - Debug.logWarning("[SQLProcessor.execQuery]: SQL Exception while executing the following:\n" + - sql + "\nError was:", MODULE); + 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); } finally { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SqlJdbcUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SqlJdbcUtil.java index a00ed12..3873c68 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SqlJdbcUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/SqlJdbcUtil.java @@ -66,13 +66,13 @@ import org.apache.ofbiz.entity.model.ModelViewEntity; /** * GenericDAO Utility methods for general tasks - * */ public final class SqlJdbcUtil { private static final String MODULE = SqlJdbcUtil.class.getName(); private static final int CHAR_BUFFER_SIZE = 4096; private static Map<String, Integer> fieldTypeMap = new HashMap<>(); + static { fieldTypeMap.put("java.lang.String", 1); fieldTypeMap.put("String", 1); @@ -116,9 +116,14 @@ public final class SqlJdbcUtil { fieldTypeMap.put("java.util.LinkedList", 15); } - private SqlJdbcUtil() { } - /** Makes the FROM clause and when necessary the JOIN clause(s) as well */ - public static String makeFromClause(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException { + private SqlJdbcUtil() { + } + + /** + * Makes the FROM clause and when necessary the JOIN clause(s) as well + */ + public static String makeFromClause(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) + throws GenericEntityException { StringBuilder sql = new StringBuilder(" FROM "); if (modelEntity instanceof ModelViewEntity) { @@ -160,7 +165,8 @@ public final class SqlJdbcUtil { ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias()); // ModelViewEntity.ModelMemberEntity linkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getEntityAlias()); - // ModelViewEntity.ModelMemberEntity relLinkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getRelEntityAlias()); + // ModelViewEntity.ModelMemberEntity relLinkMemberEntity = + // modelViewEntity.getMemberModelMemberEntity(viewLink.getRelEntityAlias()); if (i == 0) { // this is the first referenced member alias, so keep track of it for future use... @@ -173,7 +179,10 @@ public final class SqlJdbcUtil { } else { // make sure the left entity alias is already in the join... if (!joinedAliasSet.contains(viewLink.getEntityAlias())) { - throw new GenericModelException("Tried to link the " + viewLink.getEntityAlias() + " alias to the " + viewLink.getRelEntityAlias() + " alias of the " + modelViewEntity.getEntityName() + " view-entity, but it is not the first view-link and has not been included in a previous view-link. In other words, the left/main alias isn't connected to the rest of the member-entities yet."); + throw new GenericModelException("Tried to link the " + viewLink.getEntityAlias() + " alias to the " + + viewLink.getRelEntityAlias() + " alias of the " + modelViewEntity.getEntityName() + + " view-entity, but it is not the first view-link and has not been included in a previous view-link." + + "In other words, the left/main alias isn't connected to the rest of the member-entities yet."); } } // now put the rel (right) entity alias into the set that is in the join @@ -198,11 +207,17 @@ public final class SqlJdbcUtil { ModelKeyMap keyMap = viewLink.getKeyMap(j); ModelField linkField = linkEntity.getField(keyMap.getFieldName()); if (linkField == null) { - throw new GenericModelException("Invalid field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getFieldName() + "] does not exist on the [" + linkEntity.getEntityName() + "] entity."); + throw new GenericModelException("Invalid field name in view-link key-map for the " + viewLink.getEntityAlias() + + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + + " view-entity; the field [" + keyMap.getFieldName() + "] does not exist on the [" + linkEntity.getEntityName() + + "] entity."); } ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName()); if (relLinkField == null) { - throw new GenericModelException("Invalid related field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getRelFieldName() + "] does not exist on the [" + relLinkEntity.getEntityName() + "] entity."); + throw new GenericModelException("Invalid related field name in view-link key-map for the " + viewLink.getEntityAlias() + + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + + " view-entity; the field [" + keyMap.getRelFieldName() + "] does not exist on the [" + + relLinkEntity.getEntityName() + "] entity."); } if (condBuffer.length() > 0) { @@ -220,7 +235,8 @@ public final class SqlJdbcUtil { condBuffer.append(relLinkField.getColName()); } if (condBuffer.length() == 0 && viewEntityCondition == null) { - throw new GenericModelException("No view-link/join key-maps found for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity."); + throw new GenericModelException("No view-link/join key-maps found for the " + viewLink.getEntityAlias() + " and the " + + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity."); } if (viewEntityCondition != null) { @@ -240,7 +256,7 @@ public final class SqlJdbcUtil { // handle tables not included in view-link boolean fromEmpty = restOfStatement.length() == 0; - for (String aliasName: modelViewEntity.getMemberModelMemberEntities().keySet()) { + for (String aliasName : modelViewEntity.getMemberModelMemberEntities().keySet()) { ModelEntity fromEntity = modelViewEntity.getMemberModelEntity(aliasName); if (!joinedAliasSet.contains(aliasName)) { @@ -278,24 +294,33 @@ public final class SqlJdbcUtil { return sql.toString(); } - /** Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated */ + /** + * Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated + */ @Deprecated public static String makeWhereStringFromFields(List<ModelField> modelFields, Map<String, Object> fields, String operator) { return makeWhereStringFromFields(new StringBuilder(), modelFields, fields, operator, null).toString(); } - public static StringBuilder makeWhereStringFromFields(StringBuilder sb, List<ModelField> modelFields, Map<String, Object> fields, String operator) { + public static StringBuilder makeWhereStringFromFields(StringBuilder sb, List<ModelField> modelFields, Map<String, Object> fields, + String operator) { return makeWhereStringFromFields(sb, modelFields, fields, operator, null); } - /** Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated */ + /** + * Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated + */ @Deprecated - public static String makeWhereStringFromFields(List<ModelField> modelFields, Map<String, Object> fields, String operator, List<EntityConditionParam> entityConditionParams) { + public static String makeWhereStringFromFields(List<ModelField> modelFields, Map<String, Object> fields, String operator, + List<EntityConditionParam> entityConditionParams) { return makeWhereStringFromFields(new StringBuilder(), modelFields, fields, operator, entityConditionParams).toString(); } - /** Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated */ - public static StringBuilder makeWhereStringFromFields(StringBuilder sb, List<ModelField> modelFields, Map<String, Object> fields, String operator, List<EntityConditionParam> entityConditionParams) { + /** + * Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated + */ + public static StringBuilder makeWhereStringFromFields(StringBuilder sb, List<ModelField> modelFields, Map<String, Object> fields, + String operator, List<EntityConditionParam> entityConditionParams) { if (modelFields.size() < 1) { return sb; } @@ -332,7 +357,8 @@ public final class SqlJdbcUtil { return sb; } - public static String makeWhereClause(ModelEntity modelEntity, List<ModelField> modelFields, Map<String, Object> fields, String operator, String joinStyle) throws GenericEntityException { + public static String makeWhereClause(ModelEntity modelEntity, List<ModelField> modelFields, Map<String, Object> fields, String operator, + String joinStyle) throws GenericEntityException { StringBuilder whereString = new StringBuilder(""); if (UtilValidate.isNotEmpty(modelFields)) { @@ -376,11 +402,13 @@ public final class SqlJdbcUtil { ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias()); if (linkEntity == null) { - throw new GenericEntityException("Link entity not found with alias: " + viewLink.getEntityAlias() + " for entity: " + modelViewEntity.getEntityName()); + throw new GenericEntityException("Link entity not found with alias: " + viewLink.getEntityAlias() + " for entity: " + + modelViewEntity.getEntityName()); } if (relLinkEntity == null) { - throw new GenericEntityException("Rel-Link entity not found with alias: " + viewLink.getRelEntityAlias() + " for entity: " + modelViewEntity.getEntityName()); + throw new GenericEntityException("Rel-Link entity not found with alias: " + viewLink.getRelEntityAlias() + " for entity: " + + modelViewEntity.getEntityName()); } // ModelViewEntity.ModelMemberEntity linkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getEntityAlias()); @@ -412,7 +440,7 @@ public final class SqlJdbcUtil { whereString.append(viewLink.getRelEntityAlias()); whereString.append("."); whereString.append(relLinkField.getColName()); - } + } } } else { throw new GenericModelException("The join-style " + joinStyle + " is not supported"); @@ -429,7 +457,8 @@ public final class SqlJdbcUtil { return makeOrderByClause(modelEntity, orderBy, false, datasourceInfo); } - public static String makeOrderByClause(ModelEntity modelEntity, List<String> orderBy, boolean includeTablenamePrefix, Datasource datasourceInfo) throws GenericModelException { + public static String makeOrderByClause(ModelEntity modelEntity, List<String> orderBy, boolean includeTablenamePrefix, Datasource datasourceInfo) + throws GenericModelException { StringBuilder sql = new StringBuilder(""); //String fieldPrefix = includeTablenamePrefix ? (modelEntity.getTableName(datasourceInfo) + ".") : ""; @@ -447,7 +476,8 @@ public final class SqlJdbcUtil { return sql.toString(); } - public static String makeViewTable(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException { + public static String makeViewTable(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) + throws GenericEntityException { if (modelEntity instanceof ModelViewEntity) { StringBuilder sql = new StringBuilder("(SELECT "); Iterator<ModelField> fieldsIter = modelEntity.getFieldsIterator(); @@ -474,7 +504,8 @@ public final class SqlJdbcUtil { modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, whereConditions, havingConditions, orderByList, null); String viewConditionClause; if (!whereConditions.isEmpty()) { - viewConditionClause = EntityCondition.makeCondition(whereConditions, EntityOperator.AND).makeWhereString(modelViewEntity, null, datasourceInfo); + viewConditionClause = EntityCondition.makeCondition(whereConditions, EntityOperator.AND).makeWhereString(modelViewEntity, null, + datasourceInfo); } else { viewConditionClause = null; } @@ -501,7 +532,7 @@ public final class SqlJdbcUtil { } public static String filterColName(String colName) { - return colName.replace('.', '_').replace('(','_').replace(')','_'); + return colName.replace('.', '_').replace('(', '_').replace(')', '_'); } /* ====================================================================== */ @@ -509,23 +540,24 @@ public final class SqlJdbcUtil { /* ====================================================================== */ /** - * The elements (ModelFields) of the list are bound to an SQL statement - * (SQL-Processor) + * The elements (ModelFields) of the list are bound to an SQL statement + * (SQL-Processor) * * @param sqlP * @param list * @param entity * @throws GenericEntityException */ - public static void setValues(SQLProcessor sqlP, List<ModelField> list, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { - for (ModelField curField: list) { + public static void setValues(SQLProcessor sqlP, List<ModelField> list, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) + throws GenericEntityException { + for (ModelField curField : list) { setValue(sqlP, curField, entity, modelFieldTypeReader); } } /** - * The elements (ModelFields) of the list are bound to an SQL statement - * (SQL-Processor), but values must not be null. + * The elements (ModelFields) of the list are bound to an SQL statement + * (SQL-Processor), but values must not be null. * * @param sqlP * @param list @@ -533,8 +565,10 @@ public final class SqlJdbcUtil { * @param modelFieldTypeReader * @throws GenericEntityException */ - public static void setValuesWhereClause(SQLProcessor sqlP, List<ModelField> list, GenericValue dummyValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { - for (ModelField curField: list) { + public static void setValuesWhereClause(SQLProcessor sqlP, List<ModelField> list, GenericValue dummyValue, + ModelFieldTypeReader modelFieldTypeReader) + throws GenericEntityException { + for (ModelField curField : list) { // for where clause variables only setValue if not null... if (dummyValue.get(curField.getName()) != null) { setValue(sqlP, curField, dummyValue, modelFieldTypeReader); @@ -543,8 +577,8 @@ public final class SqlJdbcUtil { } /** - * Get all primary keys from the model entity and bind their values - * to the an SQL statement (SQL-Processor) + * Get all primary keys from the model entity and bind their values + * to the an SQL statement (SQL-Processor) * * @param sqlP * @param modelEntity @@ -552,7 +586,8 @@ public final class SqlJdbcUtil { * @param modelFieldTypeReader * @throws GenericEntityException */ - public static void setPkValues(SQLProcessor sqlP, ModelEntity modelEntity, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { + public static void setPkValues(SQLProcessor sqlP, ModelEntity modelEntity, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) + throws GenericEntityException { Iterator<ModelField> pksIter = modelEntity.getPksIterator(); while (pksIter.hasNext()) { ModelField curField = pksIter.next(); @@ -564,12 +599,13 @@ public final class SqlJdbcUtil { } } - public static void getValue(ResultSet rs, int ind, ModelField curField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { + public static void getValue(ResultSet rs, int ind, ModelField curField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) + throws GenericEntityException { ModelFieldType mft = modelFieldTypeReader.getModelFieldType(curField.getType()); if (mft == null) { - throw new GenericModelException("definition fieldType " + curField.getType() + " not found, cannot getValue for field " + - entity.getEntityName() + "." + curField.getName() + "."); + throw new GenericModelException("definition fieldType " + curField.getType() + " not found, cannot getValue for field " + + entity.getEntityName() + "." + curField.getName() + "."); } ModelEntity model = entity.getModelEntity(); @@ -596,10 +632,10 @@ public final class SqlJdbcUtil { Debug.logError(e, MODULE); } } else { - Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + - ", falling back on switch statement. Entity = " + - curField.getModelEntity().getEntityName() + - ", field = " + curField.getName() + ".", MODULE); + Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + + ", falling back on switch statement. Entity = " + + curField.getModelEntity().getEntityName() + + ", field = " + curField.getName() + ".", MODULE); } // ------------------------------------------ @@ -616,7 +652,8 @@ public final class SqlJdbcUtil { switch (typeValue) { case 1: if (java.sql.Types.CLOB == colType) { - // Debug.logInfo("For field " + curField.getName() + " of entity " + entity.getEntityName() + " getString is a CLOB, trying getCharacterStream", MODULE); + // Debug.logInfo("For field " + curField.getName() + " of entity " + entity.getEntityName() + " getString is a CLOB, + // trying getCharacterStream", MODULE); // if the String is empty, try to get a text input stream, this is required for some databases for larger fields, like CLOBs Clob valueClob = rs.getClob(ind); @@ -636,7 +673,8 @@ public final class SqlJdbcUtil { } valueReader.close(); } catch (IOException e) { - throw new GenericEntityException("Error reading long character stream for field " + curField.getName() + " of entity " + entity.getEntityName(), e); + throw new GenericEntityException("Error reading long character stream for field " + curField.getName() + + " of entity " + entity.getEntityName(), e); } entity.dangerousSetNoCheckButFast(curField, strBuf.toString()); } else { @@ -695,7 +733,8 @@ public final class SqlJdbcUtil { entity.dangerousSetNoCheckButFast(curField, blobObject); } else { if (originalObject instanceof Blob) { - // NOTE using SerialBlob here instead of the Blob from the database to make sure we can pass it around, serialize it, etc + // NOTE using SerialBlob here instead of the Blob from the database to make sure we can pass it around, + // serialize it, etc entity.dangerousSetNoCheckButFast(curField, new SerialBlob((Blob) originalObject)); } else { entity.dangerousSetNoCheckButFast(curField, originalObject); @@ -770,7 +809,8 @@ public final class SqlJdbcUtil { } } } catch (SQLException sqle) { - throw new GenericDataSourceException("SQL Exception while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + ")", sqle); + throw new GenericDataSourceException("SQL Exception while getting value : " + curField.getName() + " [" + curField.getColName() + + "] (" + ind + ")", sqle); } } @@ -784,7 +824,8 @@ public final class SqlJdbcUtil { } if (fieldBytes != null && fieldBytes.length <= 0) { - Debug.logWarning("Got bytes back for Object field with length: " + fieldBytes.length + " while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): ", MODULE); + Debug.logWarning("Got bytes back for Object field with length: " + fieldBytes.length + " while getting value : " + curField.getName() + + " [" + curField.getColName() + "] (" + ind + "): ", MODULE); } //alt 1: binaryInput = rs.getBinaryStream(ind); @@ -800,12 +841,14 @@ public final class SqlJdbcUtil { return in.readObject(); } catch (IOException ex) { if (Debug.verboseOn()) { - Debug.logVerbose("Unable to read BLOB data from input stream while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): " + ex.toString(), MODULE); + Debug.logVerbose("Unable to read BLOB data from input stream while getting value : " + curField.getName() + " [" + + curField.getColName() + "] (" + ind + "): " + ex.toString(), MODULE); } return null; } catch (ClassNotFoundException ex) { if (Debug.verboseOn()) { - Debug.logVerbose("Class not found: Unable to cast BLOB data to an Java object while getting value: " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "); most likely because it is a straight byte[], so just using the raw bytes" + ex.toString(), MODULE); + Debug.logVerbose("Class not found: Unable to cast BLOB data to an Java object while getting value: " + curField.getName() + + " [" + curField.getColName() + "] (" + ind + "); most likely because it is a straight byte[], so just using the raw bytes" + ex.toString(), MODULE); } return null; } finally { @@ -813,7 +856,8 @@ public final class SqlJdbcUtil { try { in.close(); } catch (IOException e) { - throw new GenericDataSourceException("Unable to close binary input stream while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): " + e.toString(), e); + throw new GenericDataSourceException("Unable to close binary input stream while getting value : " + curField.getName() + " [" + + curField.getColName() + "] (" + ind + "): " + e.toString(), e); } } } @@ -822,18 +866,21 @@ public final class SqlJdbcUtil { return null; } - public static void setValue(SQLProcessor sqlP, ModelField modelField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { + public static void setValue(SQLProcessor sqlP, ModelField modelField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) + throws GenericEntityException { Object fieldValue = entity.dangerousGetNoCheckButFast(modelField); setValue(sqlP, modelField, entity.getEntityName(), fieldValue, modelFieldTypeReader); } - public static <T> void setValue(SQLProcessor sqlP, ModelField modelField, String entityName, Object fieldValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { + public static <T> void setValue(SQLProcessor sqlP, ModelField modelField, String entityName, Object fieldValue, + ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException { ModelFieldType mft = modelFieldTypeReader.getModelFieldType(modelField.getType()); if (mft == null) { - throw new GenericModelException("GenericDAO.getValue: definition fieldType " + modelField.getType() + " not found, cannot setValue for field " + - entityName + "." + modelField.getName() + "."); + throw new GenericModelException("GenericDAO.getValue: definition fieldType " + modelField.getType() + + " not found, cannot setValue for field " + + entityName + "." + modelField.getName() + "."); } // if the value is the GenericEntity.NullField, treat as null @@ -853,13 +900,14 @@ public final class SqlJdbcUtil { sqlP.setValue(handler, handler.getJavaClass().cast(fieldValue)); return; } catch (SQLException e) { - throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", e); + throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + + entityName + ": ", e); } } else { - Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + - ", falling back on switch statement. Entity = " + - modelField.getModelEntity().getEntityName() + - ", field = " + modelField.getName() + ".", MODULE); + Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + + ", falling back on switch statement. Entity = " + + modelField.getModelEntity().getEntityName() + + ", field = " + modelField.getName() + ".", MODULE); } // ------------------------------------------ @@ -961,9 +1009,11 @@ public final class SqlJdbcUtil { break; } } catch (GenericNotImplementedException e) { - throw new GenericNotImplementedException("Not Implemented Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": " + e.toString(), e); + throw new GenericNotImplementedException("Not Implemented Exception while setting value on field [" + modelField.getName() + + "] of entity " + entityName + ": " + e.toString(), e); } catch (SQLException sqle) { - throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", sqle); + throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + + entityName + ": ", sqle); } } 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 05f0371..2a306da 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 @@ -205,7 +205,7 @@ 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() + 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() + "."); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelReader.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelReader.java index 7bbe27a..9371fd5 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelReader.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelReader.java @@ -146,12 +146,12 @@ public class ModelReader implements Serializable { // check to see if entity with same name has already been read if (entityCache.containsKey(entityName) && !redefinedEntity) { - Debug.logWarning("Entity " + entityName + - " is defined more than once, most recent will over-write " + - "previous definition(s)", MODULE); - Debug.logWarning("Entity " + entityName + " was found in " + - entityResourceHandler + ", but was already defined in " + - entityResourceHandlerMap.get(entityName).toString(), MODULE); + Debug.logWarning("Entity " + entityName + + " is defined more than once, most recent will over-write " + + "previous definition(s)", MODULE); + Debug.logWarning("Entity " + entityName + " was found in " + + entityResourceHandler + ", but was already defined in " + + entityResourceHandlerMap.get(entityName).toString(), MODULE); } // add entityName, entityFileName pair to entityResourceHandlerMap map @@ -188,8 +188,8 @@ public class ModelReader implements Serializable { } } } else { - Debug.logWarning("-- -- ENTITYGEN ERROR:getModelEntity: Could not create " + - "entity for entityName: " + entityName, MODULE); + Debug.logWarning("-- -- ENTITYGEN ERROR:getModelEntity: Could not create " + + "entity for entityName: " + entityName, MODULE); } return modelEntity; } @@ -345,8 +345,8 @@ public class ModelReader implements Serializable { Iterator<ModelRelation> relationsIter = curModelEntity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); - if (("one".equals(modelRelation.getType()) - || "one-nofk".equals(modelRelation.getType())) + if (("one".equals(modelRelation.getType()) + || "one-nofk".equals(modelRelation.getType())) && !modelRelation.isAutoRelation()) { ModelEntity relatedEnt = null; try { @@ -406,7 +406,7 @@ public class ModelReader implements Serializable { } else { if (newRel.equals(existingRelation)) { // don't warn if the target title+entity = current title+entity - if (Debug.infoOn() + if (Debug.infoOn() && !(title + curModelEntity.getEntityName()).equals(modelRelation.getTitle() + modelRelation.getRelEntityName())) { // String errorMsg = "Relation already exists to entity[] with title [" // + targetTitle + "], from entity[]"; 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 ef103be..4e4b308 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 @@ -459,8 +459,8 @@ public class ModelViewEntity extends ModelEntity { ModelEntity aliasedEntity = getAliasedEntity(alias.entityAlias, modelReader); ModelField aliasedField = getAliasedField(aliasedEntity, alias.field, modelReader); if (aliasedField == null) { - Debug.logError("[" + this.getEntityName() + "]: [populateFields] ERROR: could not find ModelField for field name \"" + - alias.field + "\" on entity with name: " + aliasedEntity.getEntityName(), MODULE); + Debug.logError("[" + this.getEntityName() + "]: [populateFields] ERROR: could not find ModelField for field name \"" + + alias.field + "\" on entity with name: " + aliasedEntity.getEntityName(), MODULE); continue; } if (alias.isPk != null) { @@ -1065,7 +1065,7 @@ public class ModelViewEntity extends ModelEntity { @Override public void makeAliasColName(StringBuilder colNameBuffer, StringBuilder fieldTypeBuffer, ModelViewEntity modelViewEntity, ModelReader modelReader) { if (UtilValidate.isEmpty(entityAlias) - && UtilValidate.isEmpty(field) + && UtilValidate.isEmpty(field) && UtilValidate.isNotEmpty(value)) { colNameBuffer.append(value); } 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 41ec2a8..ed3513e 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 @@ -80,7 +80,7 @@ public class EntityTestSuite extends EntityTestCase { super(name); } - final static private int _level1max = 3; // number of TestingNode entities to create + static final private int _level1max = 3; // number of TestingNode entities to create public void testModels() throws Exception { ModelEntity modelEntity = delegator.getModelEntity("TestingType"); 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 efe789f..bd73d99 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 @@ -359,7 +359,8 @@ public final class TransactionUtil implements Status { if (status != STATUS_NO_TRANSACTION) { if (status != STATUS_MARKED_ROLLBACK) { if (Debug.warningOn()) { - Debug.logWarning(new Exception(causeMessage), "Calling transaction setRollbackOnly; this stack trace shows where this is happening:", MODULE); + Debug.logWarning(new Exception(causeMessage), + "Calling transaction setRollbackOnly; this stack trace shows where this is happening:", MODULE); } ut.setRollbackOnly(); setSetRollbackOnlyCause(causeMessage, causeThrowable); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/DistributedCacheClear.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/DistributedCacheClear.java index 9a7dd8f..480b1cf 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/DistributedCacheClear.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/DistributedCacheClear.java @@ -29,15 +29,15 @@ import org.apache.ofbiz.entity.condition.EntityCondition; */ public interface DistributedCacheClear { - public void setDelegator(Delegator delegator, String userLoginId); + void setDelegator(Delegator delegator, String userLoginId); - public void distributedClearCacheLine(GenericValue value); + void distributedClearCacheLine(GenericValue value); - public void distributedClearCacheLineFlexible(GenericEntity dummyPK); + void distributedClearCacheLineFlexible(GenericEntity dummyPK); - public void distributedClearCacheLineByCondition(String entityName, EntityCondition condition); + void distributedClearCacheLineByCondition(String entityName, EntityCondition condition); - public void distributedClearCacheLine(GenericPK primaryKey); + void distributedClearCacheLine(GenericPK primaryKey); - public void clearAllCaches(); + void clearAllCaches(); } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityBatchIterator.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityBatchIterator.java index 6b02f6c..3cbbbf0 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityBatchIterator.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityBatchIterator.java @@ -26,7 +26,7 @@ import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; public class EntityBatchIterator implements Iterator<GenericValue> { - public static final String MODULE = EntityBatchIterator.class.getName(); + private static final String MODULE = EntityBatchIterator.class.getName(); private EntityQuery query; List<GenericValue> currentResultSet; diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityDataAssert.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityDataAssert.java index dc473fe..4d74177 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityDataAssert.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityDataAssert.java @@ -105,8 +105,8 @@ public class EntityDataAssert { Object currentField = currentValue.get(nonpkFieldName); if (checkField != null && !checkField.equals(currentField)) { - errorMessages.add("Field [" + modelEntity.getEntityName() + "." + nonpkFieldName + - "] did not match; file value [" + checkField + "], db value [" + currentField + "] pk [" + checkPK + "]"); + errorMessages.add("Field [" + modelEntity.getEntityName() + "." + nonpkFieldName + + "] did not match; file value [" + checkField + "], db value [" + currentField + "] pk [" + checkPK + "]"); } } } catch (GenericEntityException e) { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java index a2f30b9..1a981b4 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java @@ -268,10 +268,10 @@ public class EntityListIterator implements AutoCloseable, ListIterator<GenericVa /** * PLEASE NOTE: Because of the nature of the JDBC ResultSet interface this method can be very inefficient. - * It is much better to just use next() until it returns null + * It is much better to just use next() until it returns null * For example, you could use the following to iterate through the results in an EntityListIterator: * - * GenericValue nextValue = null; + * GenericValue nextValue = null; * while ((nextValue = (GenericValue) * this.next()) != null) { ... } * @@ -427,14 +427,14 @@ public class EntityListIterator implements AutoCloseable, ListIterator<GenericVa } /** - * Gets a partial list of results starting at start and containing at most number elements. + * Gets a partial list of results starting at start and containing at most number elements. * Start is a one based value, i.e. 1 is the first element. * * @param start * the index from which on the elements should be retrieved. Is one based. * @param number * the maximum number of elements to get after the start index. - * @return A list with the retrieved elements, with the size of number or less if the result set does not contain enough values. + * @return A list with the retrieved elements, with the size of number or less if the result set does not contain enough values. * Empty list in case of no values or an invalid start index. * @throws GenericEntityException * if there is an issue with the database. diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityQuery.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityQuery.java index 167f58c..dca71a6 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityQuery.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityQuery.java @@ -91,7 +91,7 @@ public class EntityQuery { /** Set the fields to be returned when the query is executed. * Note that the select methods are not additive, if a subsequent - * call is made to select then the existing fields for selection + * call is made to select then the existing fields for selection * will be replaced. * @param fieldsToSelect - A Set of Strings containing the field names to be selected * @return this EntityQuery object, to enable chaining @@ -444,7 +444,7 @@ public class EntityQuery { if (dynamicViewEntity == null) { result = delegator.findList(entityName, makeWhereCondition(useCache), havingEntityCondition, fieldsToSelect, orderBy, findOptions, useCache); } else { - try (EntityListIterator it = queryIterator()) { + try (EntityListIterator it = queryIterator()) { result = it.getCompleteList(); } } @@ -519,7 +519,7 @@ public class EntityQuery { } /** - * Gets a list of values (no matter which type) for a specified entity field name. + * Gets a list of values (no matter which type) for a specified entity field name. * <p> * The field of the entity is first selected and the cache usage turned off to ensure no values are missing. * @param <T> diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntitySaxReader.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntitySaxReader.java index 1436869..4f4fd63 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntitySaxReader.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntitySaxReader.java @@ -243,10 +243,10 @@ public class EntitySaxReader extends DefaultHandler { throw new SAXException("A transaction error occurred reading data", e); } Debug.logImportant("Finished " + numberRead + " values from " + docDescription, MODULE); - if (Debug.verboseOn()) { - Debug.logVerbose(" Detail created : " + numberCreated + ", skipped : " + numberSkipped + - ", updated : " + numberUpdated + ", replaced : " + numberReplaced + - ", deleted : " + numberDeleted, MODULE); + if (Debug.verboseOn()) { + Debug.logVerbose(" Detail created : " + numberCreated + ", skipped : " + numberSkipped + + ", updated : " + numberUpdated + ", replaced : " + numberReplaced + + ", deleted : " + numberDeleted, MODULE); } return numberRead; } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityTypeUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityTypeUtil.java index eceeae6..02069e4 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityTypeUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityTypeUtil.java @@ -56,7 +56,7 @@ public final class EntityTypeUtil { while (iter.hasNext()) { if (isType((GenericValue) iter.next(), targetType)) { return true; - }//else keep looking + } //else keep looking } return false; }*/ diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtil.java index 80ea034..ad35e08 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtil.java @@ -26,7 +26,6 @@ import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -74,8 +73,12 @@ public final class EntityUtil { i++; V value = args[i]; if (value != null) { - if (!(value instanceof Comparable<?>)) throw new IllegalArgumentException("Value(" + i + "), with value(" + args[i] + ") does not implement Comparable."); - if (!(value instanceof Serializable)) throw new IllegalArgumentException("Value(" + i + "), with value(" + args[i] + ") does not implement Serializable."); + if (!(value instanceof Comparable<?>)) { + throw new IllegalArgumentException("Value(" + i + "), with value(" + args[i] + ") does not implement Comparable."); + } + if (!(value instanceof Serializable)) { + throw new IllegalArgumentException("Value(" + i + "), with value(" + args[i] + ") does not implement Serializable."); + } } fields.put(key, value); i++; @@ -147,57 +150,60 @@ public final class EntityUtil { } /** - *returns the values that are currently active. + * returns the values that are currently active. * - *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields - *@return List of GenericValue's that are currently active + * @param datedValues GenericValue's that have "fromDate" and "thruDate" fields + * @return List of GenericValue's that are currently active */ public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues) { return filterByDate(datedValues, UtilDateTime.nowTimestamp(), null, null, true); } /** - *returns the values that are currently active. + * returns the values that are currently active. * - *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields - *@param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we only have to see if the from and thru date fields are valid once - *@return List of GenericValue's that are currently active + * @param datedValues GenericValue's that have "fromDate" and "thruDate" fields + * @param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we + * only have to see if the from and thru date fields are valid once + * @return List of GenericValue's that are currently active */ public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, boolean allAreSame) { return filterByDate(datedValues, UtilDateTime.nowTimestamp(), null, null, allAreSame); } /** - *returns the values that are active at the moment. + * returns the values that are active at the moment. * - *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields - *@param moment the moment in question - *@return List of GenericValue's that are active at the moment + * @param datedValues GenericValue's that have "fromDate" and "thruDate" fields + * @param moment the moment in question + * @return List of GenericValue's that are active at the moment */ public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, java.util.Date moment) { return filterByDate(datedValues, new java.sql.Timestamp(moment.getTime()), null, null, true); } /** - *returns the values that are active at the moment. + * returns the values that are active at the moment. * - *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields - *@param moment the moment in question - *@return List of GenericValue's that are active at the moment + * @param datedValues GenericValue's that have "fromDate" and "thruDate" fields + * @param moment the moment in question + * @return List of GenericValue's that are active at the moment */ public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, java.sql.Timestamp moment) { return filterByDate(datedValues, moment, null, null, true); } /** - *returns the values that are active at the moment. + * returns the values that are active at the moment. * - *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields - *@param moment the moment in question - *@param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we only have to see if the from and thru date fields are valid once - *@return List of GenericValue's that are active at the moment + * @param datedValues GenericValue's that have "fromDate" and "thruDate" fields + * @param moment the moment in question + * @param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we + * only have to see if the from and thru date fields are valid once + * @return List of GenericValue's that are active at the moment */ - public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, java.sql.Timestamp moment, String fromDateName, String thruDateName, boolean allAreSame) { + public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, java.sql.Timestamp moment, String fromDateName, + String thruDateName, boolean allAreSame) { if (datedValues == null) return null; if (moment == null) return datedValues; if (fromDateName == null) fromDateName = "fromDate"; @@ -214,16 +220,20 @@ public final class EntityUtil { T datedValue = iter.next(); fromDateField = datedValue.getModelEntity().getField(fromDateName); - if (fromDateField == null) throw new IllegalArgumentException("\"" + fromDateName + "\" is not a field of " + datedValue.getEntityName()); + if (fromDateField == null) { + throw new IllegalArgumentException("\"" + fromDateName + "\" is not a field of " + datedValue.getEntityName()); + } thruDateField = datedValue.getModelEntity().getField(thruDateName); - if (thruDateField == null) throw new IllegalArgumentException("\"" + thruDateName + "\" is not a field of " + datedValue.getEntityName()); + if (thruDateField == null) { + throw new IllegalArgumentException("\"" + thruDateName + "\" is not a field of " + datedValue.getEntityName()); + } java.sql.Timestamp fromDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(fromDateField); java.sql.Timestamp thruDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(thruDateField); if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) { result.add(datedValue); - }// else not active at moment + } // else not active at moment } while (iter.hasNext()) { T datedValue = iter.next(); @@ -232,7 +242,7 @@ public final class EntityUtil { if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) { result.add(datedValue); - }// else not active at moment + } // else not active at moment } } else { // if not all values are known to be of the same entity, must check each one... @@ -243,7 +253,7 @@ public final class EntityUtil { if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) { result.add(datedValue); - }// else not active at moment + } // else not active at moment } } @@ -257,16 +267,16 @@ public final class EntityUtil { public static boolean isValueActive(GenericValue datedValue, java.sql.Timestamp moment, String fromDateName, String thruDateName) { java.sql.Timestamp fromDate = datedValue.getTimestamp(fromDateName); java.sql.Timestamp thruDate = datedValue.getTimestamp(thruDateName); - return (thruDate == null || thruDate.after(moment)) && - (fromDate == null || fromDate.before(moment) || fromDate.equals(moment)); + return (thruDate == null || thruDate.after(moment)) + && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment)); } /** - *returns the values that match the values in fields + * returns the values that match the values in fields * - *@param values List of GenericValues - *@param fields the field-name/value pairs that must match - *@return List of GenericValue's that match the values in fields + * @param values List of GenericValues + * @param fields the field-name/value pairs that must match + * @return List of GenericValue's that match the values in fields */ public static <T extends GenericEntity> List<T> filterByAnd(List<T> values, Map<String, ? extends Object> fields) { if (values == null || UtilValidate.isEmpty(fields)) { @@ -276,11 +286,11 @@ public final class EntityUtil { } /** - *returns the values that match all of the exprs in list + * returns the values that match all of the exprs in list * - *@param values List of GenericValues - *@param exprs the expressions that must validate to true - *@return List of GenericValue's that match the values in fields + * @param values List of GenericValues + * @param exprs the expressions that must validate to true + * @return List of GenericValue's that match the values in fields */ public static <T extends GenericEntity> List<T> filterByAnd(List<T> values, List<? extends EntityCondition> exprs) { if (values == null || UtilValidate.isEmpty(exprs)) { @@ -293,11 +303,11 @@ public final class EntityUtil { } /** - *returns the values that match any of the exprs in list + * returns the values that match any of the exprs in list * - *@param values List of GenericValues - *@param exprs the expressions that must validate to true - *@return List of GenericValue's that match the values in fields + * @param values List of GenericValues + * @param exprs the expressions that must validate to true + * @return List of GenericValue's that match the values in fields */ public static <T extends GenericEntity> List<T> filterByOr(List<T> values, List<? extends EntityCondition> exprs) { if (values == null || UtilValidate.isEmpty(exprs)) { @@ -310,13 +320,13 @@ public final class EntityUtil { } /** - *returns the values in the order specified after with localized value + * returns the values in the order specified after with localized value * - *@param values List of GenericValues - *@param orderBy The fields of the named entity to order the query by; - * optionally add a " ASC" for ascending or " DESC" for descending - *@param locale Locale use to retrieve localized value - *@return List of GenericValue's in the proper order + * @param values List of GenericValues + * @param orderBy The fields of the named entity to order the query by; + * optionally add a " ASC" for ascending or " DESC" for descending + * @param locale Locale use to retrieve localized value + * @return List of GenericValue's in the proper order */ public static <T extends GenericEntity> List<T> localizedOrderBy(Collection<T> values, List<String> orderBy, Locale locale) { if (values == null) return null; @@ -327,12 +337,12 @@ public final class EntityUtil { T newValue = UtilGenerics.cast(value.clone()); for (String orderByField : orderBy) { if (orderByField.endsWith(" DESC")) { - orderByField= orderByField.substring(0, orderByField.length() - 5); + orderByField = orderByField.substring(0, orderByField.length() - 5); } else if (orderByField.endsWith(" ASC")) { - orderByField= orderByField.substring(0, orderByField.length() - 4); + orderByField = orderByField.substring(0, orderByField.length() - 4); } else if (orderByField.startsWith("-") || orderByField.startsWith("+")) { - orderByField= orderByField.substring(1, orderByField.length()); + orderByField = orderByField.substring(1, orderByField.length()); } newValue.put(orderByField, value.get(orderByField, locale)); } @@ -342,12 +352,12 @@ public final class EntityUtil { } /** - *returns the values in the order specified + * returns the values in the order specified * - *@param values List of GenericValues - *@param orderBy The fields of the named entity to order the query by; - * optionally add a " ASC" for ascending or " DESC" for descending - *@return List of GenericValue's in the proper order + * @param values List of GenericValues + * @param orderBy The fields of the named entity to order the query by; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue's in the proper order */ public static <T extends GenericEntity> List<T> orderBy(Collection<T> values, List<String> orderBy) { if (values == null) return null; @@ -372,15 +382,17 @@ public final class EntityUtil { */ @Deprecated public static List<GenericValue> getRelated(String relationName, List<GenericValue> values) throws GenericEntityException { - Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", GenericValue.getStackTraceAsString()); + Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", + GenericValue.getStackTraceAsString()); return getRelated(relationName, null, values, false); } - public static List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> fields, List<GenericValue> values, boolean useCache) throws GenericEntityException { + public static List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> fields, List<GenericValue> values, + boolean useCache) throws GenericEntityException { if (values == null) return null; List<GenericValue> result = new LinkedList<>(); - for (GenericValue value: values) { + for (GenericValue value : values) { result.addAll(value.getRelated(relationName, fields, null, useCache)); } return result; @@ -400,29 +412,33 @@ public final class EntityUtil { return values.stream().filter(value -> !condition.entityMatches(value)).collect(toList()); } - public static List<GenericValue> findDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) throws GenericEntityException { + public static List<GenericValue> findDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) + throws GenericEntityException { return findDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp()); } - public static List<GenericValue> findDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search, Timestamp now) throws GenericEntityException { + public static List<GenericValue> findDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search, + Timestamp now) throws GenericEntityException { EntityCondition searchCondition = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition(search), EntityUtil.getFilterByDateExpr(now))); return EntityQuery.use(delegator).from(entityName).where(searchCondition).orderBy("-fromDate").queryList(); } - public static GenericValue newDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) throws GenericEntityException { + public static GenericValue newDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) + throws GenericEntityException { return newDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp()); } - public static GenericValue newDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> find, Timestamp now) throws GenericEntityException { + public static GenericValue newDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> find, Timestamp now) + throws GenericEntityException { Map<String, Object> search; List<GenericValue> entities = findDatedInclusionEntity(delegator, entityName, find, now); if (UtilValidate.isNotEmpty(entities)) { search = null; - for (GenericValue entity: entities) { + for (GenericValue entity : entities) { if (now.equals(entity.get("fromDate"))) { search = new HashMap<>(); - for (Map.Entry<String, ? super Object> entry: entity.getPrimaryKey().entrySet()) { + for (Map.Entry<String, ? super Object> entry : entity.getPrimaryKey().entrySet()) { search.put(entry.getKey(), entry.getValue()); } entity.remove("thruDate"); @@ -451,13 +467,15 @@ public final class EntityUtil { } } - public static void delDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) throws GenericEntityException { + public static void delDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search) + throws GenericEntityException { delDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp()); } - public static void delDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search, Timestamp now) throws GenericEntityException { + public static void delDatedInclusionEntity(Delegator delegator, String entityName, Map<String, ? extends Object> search, Timestamp now) + throws GenericEntityException { List<GenericValue> entities = findDatedInclusionEntity(delegator, entityName, search, now); - for (GenericValue entity: entities) { + for (GenericValue entity : entities) { entity.set("thruDate", now); entity.store(); } @@ -524,8 +542,8 @@ public final class EntityUtil { } /** - * @param iter EntityListIterator - * @param viewIndex + * @param iter EntityListIterator + * @param viewIndex * @param viewSize * @return PagedList object with a subset of data items from EntityListIterator based on viewIndex and viewSize * @throws GenericEntityException @@ -551,6 +569,7 @@ public final class EntityUtil { /** * For a entityName return the primary keys path that identify it * like entityName/pkValue1/pkValue2/../pkValueN + * * @param delegator * @param entityName * @param context @@ -559,9 +578,11 @@ public final class EntityUtil { public static String entityToPath(Delegator delegator, String entityName, Map<String, Object> context) { return entityToPath(delegator.makeValidValue(entityName, context)); } + /** * For a entityName return the primary keys path that identify it * like entityName/pkValue1/pkValue2/../pkValueN + * * @param gv * @return */ @@ -576,11 +597,12 @@ public final class EntityUtil { /** * Form a entityName and primary keys path * convert it to a Map contains all pkValue : - * entityName/pkValue1/pkValue2/../pkValueN - * -> [pkName1: pkValue1, - * pkName2, pkValue2, - * ..., - * pkNameN: pkValueN] + * entityName/pkValue1/pkValue2/../pkValueN + * -> [pkName1: pkValue1, + * pkName2, pkValue2, + * ..., + * pkNameN: pkValueN] + * * @param modelEntity * @param path * @return @@ -591,7 +613,7 @@ public final class EntityUtil { LinkedList<String> pkValues = new LinkedList<>(Arrays.asList(path.split("/"))); List<String> pkFieldNames = modelEntity.getPkFieldNames(); if (pkFieldNames.size() != pkValues.size()) { - throw new GenericEntityException ("Identification path failed "); + throw new GenericEntityException("Identification path failed "); } Map<String, Object> pkValuesMap = new HashMap<>(); for (String pkName : modelEntity.getPkFieldNames()) { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtilProperties.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtilProperties.java index 5b525b2..5af8014 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtilProperties.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityUtilProperties.java @@ -47,7 +47,7 @@ import org.apache.ofbiz.entity.GenericValue; @SuppressWarnings("serial") public final class EntityUtilProperties implements Serializable { - public final static String MODULE = EntityUtilProperties.class.getName(); + private static final String MODULE = EntityUtilProperties.class.getName(); private EntityUtilProperties() { } diff --git a/framework/entityext/src/main/java/org/apache/ofbiz/entityext/synchronization/EntitySyncContext.java b/framework/entityext/src/main/java/org/apache/ofbiz/entityext/synchronization/EntitySyncContext.java index c80d48c..16ec26a 100644 --- a/framework/entityext/src/main/java/org/apache/ofbiz/entityext/synchronization/EntitySyncContext.java +++ b/framework/entityext/src/main/java/org/apache/ofbiz/entityext/synchronization/EntitySyncContext.java @@ -759,9 +759,9 @@ public class EntitySyncContext { setSplitStartTime(); // total the rows saved so far, and gather some info about them before saving - this.totalRowsPerSplit = this.toCreateInserted + this.toCreateNotUpdated + this.toCreateUpdated + - this.toStoreInserted + this.toStoreNotUpdated + this.toStoreUpdated + - this.toRemoveAlreadyDeleted + this.toRemoveDeleted; + this.totalRowsPerSplit = this.toCreateInserted + this.toCreateNotUpdated + this.toCreateUpdated + + this.toStoreInserted + this.toStoreNotUpdated + this.toStoreUpdated + + this.toRemoveAlreadyDeleted + this.toRemoveDeleted; if (this.totalRowsPerSplit < this.perSplitMinItems) { this.perSplitMinItems = this.totalRowsPerSplit; } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/MiniLangRuntimeException.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/MiniLangRuntimeException.java index b4b2e75..1108b35 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/MiniLangRuntimeException.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/MiniLangRuntimeException.java @@ -19,7 +19,7 @@ package org.apache.ofbiz.minilang; /** - * Thrown to indicate a Mini-language run-time error. + * Thrown to indicate a Mini-language run-time error. */ @SuppressWarnings("serial") public class MiniLangRuntimeException extends MiniLangException { 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 29d9320..bc1716b 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 @@ -75,20 +75,25 @@ import org.w3c.dom.Element; * (see <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html" target="_blank">ServiceLoader</a>) * </li> * </ul> + * * @see <a href="https://cwiki.apache.org/confluence/display/OFBIZ/Mini+Language+-+minilang+-+simple-method+-+Reference">Mini-language Reference</a> */ public final class SimpleMethod extends MiniLangElement { private static final String MODULE = SimpleMethod.class.getName(); - 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 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 = UtilCache.createUtilCache("minilang.SimpleMethodsDirect", 0, 0); - private static final UtilCache<String, SimpleMethod> simpleMethodsResourceCache = UtilCache.createUtilCache("minilang.SimpleMethodsResource", 0, 0); + private static final UtilCache<String, Map<String, SimpleMethod>> simpleMethodsDirectCache = + UtilCache.createUtilCache("minilang.SimpleMethodsDirect", 0, 0); + private static final UtilCache<String, SimpleMethod> simpleMethodsResourceCache = + UtilCache.createUtilCache("minilang.SimpleMethodsResource", 0, 0); static { Map<String, MethodOperation.Factory<MethodOperation>> mapFactories = new HashMap<>(); - Iterator<MethodOperation.Factory<MethodOperation>> it = UtilGenerics.cast(ServiceLoader.load(MethodOperation.Factory.class, SimpleMethod.class.getClassLoader()).iterator()); + Iterator<MethodOperation.Factory<MethodOperation>> it = UtilGenerics.cast(ServiceLoader.load(MethodOperation.Factory.class, + SimpleMethod.class.getClassLoader()).iterator()); while (it.hasNext()) { MethodOperation.Factory<MethodOperation> factory = it.next(); mapFactories.put(factory.getName(), factory); @@ -96,6 +101,70 @@ public final class SimpleMethod extends MiniLangElement { methodOperationFactories = Collections.unmodifiableMap(mapFactories); } + private final String defaultErrorCode; + private final String defaultSuccessCode; + private final String eventErrorMessageListName; + private final String eventErrorMessageName; + private final String eventEventMessageListName; + private final String eventEventMessageName; + private final String eventRequestName; + private final String eventResponseCodeName; + private final String eventResponseName; + private final String eventSessionName; + private final String fromLocation; + private final boolean loginRequired; + private final String methodName; + private final List<MethodOperation> methodOperations; + private final String serviceErrorMessageListName; + private final String serviceErrorMessageMapName; + private final String serviceErrorMessageName; + private final String serviceResponseMessageName; + private final String serviceSuccessMessageListName; + private final String serviceSuccessMessageName; + private final String shortDescription; + private final boolean useTransaction; + public SimpleMethod(Element simpleMethodElement, String fromLocation) throws MiniLangException { + super(simpleMethodElement, null); + if (MiniLangValidate.validationOn()) { + String locationMsg = " File = ".concat(fromLocation); + if (simpleMethodElement.getAttribute("method-name").isEmpty()) { + MiniLangValidate.handleError("Element must include the \"method-name\" attribute.".concat(locationMsg), null, simpleMethodElement); + } + for (int i = 0; i < DEPRECATED_ATTRIBUTES.length; i++) { + if (!simpleMethodElement.getAttribute(DEPRECATED_ATTRIBUTES[i]).isEmpty()) { + MiniLangValidate.handleError("Attribute \"" + DEPRECATED_ATTRIBUTES[i] + "\" is deprecated (no replacement)." + locationMsg, + null, simpleMethodElement); + } + } + } + boolean elementModified = autoCorrect(simpleMethodElement); + if (elementModified && MiniLangUtil.autoCorrectOn()) { + MiniLangUtil.flagDocumentAsCorrected(simpleMethodElement); + } + this.fromLocation = fromLocation; + methodName = simpleMethodElement.getAttribute("method-name"); + shortDescription = simpleMethodElement.getAttribute("short-description"); + defaultErrorCode = UtilXml.elementAttribute(simpleMethodElement, "default-error-code", "error"); + defaultSuccessCode = UtilXml.elementAttribute(simpleMethodElement, "default-success-code", "success"); + eventRequestName = UtilXml.elementAttribute(simpleMethodElement, "event-request-object-name", "request"); + eventSessionName = UtilXml.elementAttribute(simpleMethodElement, "event-session-object-name", "session"); + eventResponseName = UtilXml.elementAttribute(simpleMethodElement, "event-response-object-name", "response"); + eventResponseCodeName = UtilXml.elementAttribute(simpleMethodElement, "event-response-code-name", "_response_code_"); + eventErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-name", "_error_message_"); + eventErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-list-name", "_error_message_list_"); + eventEventMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-name", "_event_message_"); + eventEventMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-list-name", "_event_message_list_"); + serviceResponseMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-response-message-name", "responseMessage"); + serviceErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-name", "errorMessage"); + serviceErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-list-name", "errorMessageList"); + serviceErrorMessageMapName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-map-name", "errorMessageMap"); + serviceSuccessMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-name", "successMessage"); + serviceSuccessMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-list-name", "successMessageList"); + loginRequired = !"false".equals(simpleMethodElement.getAttribute("login-required")); + useTransaction = !"false".equals(simpleMethodElement.getAttribute("use-transaction")); + methodOperations = Collections.unmodifiableList(readOperations(simpleMethodElement, this)); + } + // This method is needed only during the v1 to v2 transition private static boolean autoCorrect(Element element) { boolean elementModified = false; @@ -210,6 +279,7 @@ public final class SimpleMethod extends MiniLangElement { * The ordering in the List is the same as the XML file. * <p>This method is used by unit test framework to run tests in the order they appear in the XML file. * Method caching is bypassed since the methods are executed only once.</p> + * * @param xmlResource * @param loader * @return @@ -242,7 +312,8 @@ public final class SimpleMethod extends MiniLangElement { methodOperations.add(methodOp); DeprecatedOperation depOp = methodOp.getClass().getAnnotation(DeprecatedOperation.class); if (depOp != null) { - MiniLangValidate.handleError("The " + nodeName + " operation has been deprecated in favor of the " + depOp.value() + " operation", simpleMethod, curOperElem); + MiniLangValidate.handleError("The " + nodeName + " operation has been deprecated in favor of the " + depOp.value() + + " operation", simpleMethod, curOperElem); } } } @@ -250,15 +321,18 @@ public final class SimpleMethod extends MiniLangElement { return methodOperations; } - public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response) throws MiniLangException { + public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response) + throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, null)); } - public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { + public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response, + ClassLoader loader) throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, loader)); } - public static String runSimpleEvent(URL xmlURL, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { + public static String runSimpleEvent(URL xmlURL, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) + throws MiniLangException { return runSimpleMethod(xmlURL, methodName, new MethodContext(request, response, loader)); } @@ -279,19 +353,22 @@ public final class SimpleMethod extends MiniLangElement { return simpleMethod.exec(methodContext); } - public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context) throws MiniLangException { + public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, + Map<String, ? extends Object> context) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, null); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } - public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { + public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, + Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } - public static Map<String, Object> runSimpleService(URL xmlURL, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { + public static Map<String, Object> runSimpleService(URL xmlURL, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, + ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlURL, methodName, methodContext); return methodContext.getResults(); @@ -299,7 +376,8 @@ public final class SimpleMethod extends MiniLangElement { /** * Execs the given operations returning true if all return true, or returning false and stopping if any return false. - * @throws MiniLangException + * + * @throws MiniLangException */ public static boolean runSubOps(List<MethodOperation> methodOperations, MethodContext methodContext) throws MiniLangException { Assert.notNull("methodOperations", methodOperations, "methodContext", methodContext); @@ -311,102 +389,64 @@ public final class SimpleMethod extends MiniLangElement { return true; } - private final String defaultErrorCode; - private final String defaultSuccessCode; - private final String eventErrorMessageListName; - private final String eventErrorMessageName; - private final String eventEventMessageListName; - private final String eventEventMessageName; - private final String eventRequestName; - private final String eventResponseCodeName; - private final String eventResponseName; - private final String eventSessionName; - private final String fromLocation; - private final boolean loginRequired; - private final String methodName; - private final List<MethodOperation> methodOperations; - private final String serviceErrorMessageListName; - private final String serviceErrorMessageMapName; - private final String serviceErrorMessageName; - private final String serviceResponseMessageName; - private final String serviceSuccessMessageListName; - private final String serviceSuccessMessageName; - private final String shortDescription; - private final boolean useTransaction; - - public SimpleMethod(Element simpleMethodElement, String fromLocation) throws MiniLangException { - super(simpleMethodElement, null); - if (MiniLangValidate.validationOn()) { - String locationMsg = " File = ".concat(fromLocation); - if (simpleMethodElement.getAttribute("method-name").isEmpty()) { - MiniLangValidate.handleError("Element must include the \"method-name\" attribute.".concat(locationMsg), null, simpleMethodElement); - } - for (int i = 0; i < DEPRECATED_ATTRIBUTES.length; i++) { - if (!simpleMethodElement.getAttribute(DEPRECATED_ATTRIBUTES[i]).isEmpty()) { - MiniLangValidate.handleError("Attribute \"" + DEPRECATED_ATTRIBUTES[i] + "\" is deprecated (no replacement)." + locationMsg, null, simpleMethodElement); - } - } - } - boolean elementModified = autoCorrect(simpleMethodElement); - if (elementModified && MiniLangUtil.autoCorrectOn()) { - MiniLangUtil.flagDocumentAsCorrected(simpleMethodElement); + private static void addMessage(MethodContext methodContext, String messageListName, String message) { + List<String> messages = methodContext.getEnv(messageListName); + if (messages == null) { + messages = new LinkedList<>(); + methodContext.putEnv(messageListName, messages); } - this.fromLocation = fromLocation; - methodName = simpleMethodElement.getAttribute("method-name"); - shortDescription = simpleMethodElement.getAttribute("short-description"); - defaultErrorCode = UtilXml.elementAttribute(simpleMethodElement, "default-error-code", "error"); - defaultSuccessCode = UtilXml.elementAttribute(simpleMethodElement, "default-success-code", "success"); - eventRequestName = UtilXml.elementAttribute(simpleMethodElement, "event-request-object-name", "request"); - eventSessionName = UtilXml.elementAttribute(simpleMethodElement, "event-session-object-name", "session"); - eventResponseName = UtilXml.elementAttribute(simpleMethodElement, "event-response-object-name", "response"); - eventResponseCodeName = UtilXml.elementAttribute(simpleMethodElement, "event-response-code-name", "_response_code_"); - eventErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-name", "_error_message_"); - eventErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-list-name", "_error_message_list_"); - eventEventMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-name", "_event_message_"); - eventEventMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-list-name", "_event_message_list_"); - serviceResponseMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-response-message-name", "responseMessage"); - serviceErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-name", "errorMessage"); - serviceErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-list-name", "errorMessageList"); - serviceErrorMessageMapName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-map-name", "errorMessageMap"); - serviceSuccessMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-name", "successMessage"); - serviceSuccessMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-list-name", "successMessageList"); - loginRequired = !"false".equals(simpleMethodElement.getAttribute("login-required")); - useTransaction = !"false".equals(simpleMethodElement.getAttribute("use-transaction")); - methodOperations = Collections.unmodifiableList(readOperations(simpleMethodElement, this)); + messages.add(message); + } + + private static String getDelegatorEnvName() { + return "delegator"; + } + + private static String getDispatcherEnvName() { + return "dispatcher"; + } + + private static String getParameterMapName() { + return "parameters"; + } + + private static String getSecurityEnvName() { + return "security"; + } + + public static String getUserLoginEnvName() { + return "userLogin"; } public void addErrorMessage(MethodContext methodContext, String message) { - String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventErrorMessageListName() : getServiceErrorMessageListName(); + String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventErrorMessageListName() + : getServiceErrorMessageListName(); addMessage(methodContext, messageListName, message); } public void addMessage(MethodContext methodContext, String message) { - String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventEventMessageListName() : getServiceSuccessMessageListName(); + String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventEventMessageListName() + : getServiceSuccessMessageListName(); addMessage(methodContext, messageListName, message); } - private static void addMessage(MethodContext methodContext, String messageListName, String message) { - List<String> messages = methodContext.getEnv(messageListName); - if (messages == null) { - messages = new LinkedList<>(); - methodContext.putEnv(messageListName, messages); - } - messages.add(message); - } - - /** Execute the Simple Method operations */ + /** + * Execute the Simple Method operations + */ public String exec(MethodContext methodContext) throws MiniLangException { if (methodContext.isTraceOn()) { - outputTraceMessage(methodContext, "Begin simple-method. Script is running as " + (methodContext.getMethodType() == MethodContext.EVENT ? "an event." : "a service.")); + outputTraceMessage(methodContext, "Begin simple-method. Script is running as " + (methodContext.getMethodType() == MethodContext.EVENT + ? "an event." : "a service.")); } Locale locale = methodContext.getLocale(); GenericValue userLogin = methodContext.getUserLogin(); if (loginRequired) { if (userLogin == null) { - Map<String, Object> messageMap = UtilMisc.<String, Object> toMap("shortDescription", shortDescription); - String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.must_logged_process", messageMap, locale) + "."; + Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("shortDescription", shortDescription); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "simpleMethod.must_logged_process", messageMap, locale) + "."; if (methodContext.isTraceOn()) { - outputTraceMessage(methodContext, "login-required attribute set to \"true\" but UserLogin GenericValue was not found, returning error message:", errMsg); + outputTraceMessage(methodContext, + "login-required attribute set to \"true\" but UserLogin GenericValue was not found, returning error message:", errMsg); } return returnError(methodContext, errMsg); } @@ -437,7 +477,7 @@ public final class SimpleMethod extends MiniLangElement { try { beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e) { - String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_begin_transaction", locale) + ": " + e.getMessage(); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "simpleMethod.error_begin_transaction", locale) + ": " + e.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while beginning a transaction, returning error message:", errMsg); } @@ -454,7 +494,7 @@ public final class SimpleMethod extends MiniLangElement { finished = runSubOps(methodOperations, methodContext); } catch (Throwable t) { // make SURE nothing gets thrown through - String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_running", locale) + ": " + t.getMessage(); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "simpleMethod.error_running", locale) + ": " + t.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while running sub-elements, error message was:", errMsg); } @@ -495,7 +535,8 @@ public final class SimpleMethod extends MiniLangElement { if (UtilValidate.isEmpty(response)) { if (forceError) { // override response code, always use error code - Debug.logInfo("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", MODULE); + Debug.logInfo("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + + "]", MODULE); response = defaultErrorCode; } else { Debug.logInfo("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", MODULE); @@ -541,12 +582,14 @@ public final class SimpleMethod extends MiniLangElement { if (forceError) { // override response code, always use error code if (Debug.verboseOn()) { - Debug.logVerbose("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", MODULE); + Debug.logVerbose("No response code string found, but error messages found so assuming error; returning code [" + + defaultErrorCode + "]", MODULE); } response = defaultErrorCode; } else { if (Debug.verboseOn()) { - Debug.logVerbose("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", MODULE); + Debug.logVerbose("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", + MODULE); } response = defaultSuccessCode; } @@ -579,7 +622,8 @@ public final class SimpleMethod extends MiniLangElement { } // rollback here passing beganTransaction to either rollback, or set rollback only try { - TransactionUtil.rollback(beganTransaction, "Error in simple-method [" + this.getShortDescription() + "]: " + summaryErrorStringBuffer, null); + TransactionUtil.rollback(beganTransaction, "Error in simple-method [" + this.getShortDescription() + "]: " + + summaryErrorStringBuffer, null); } catch (GenericTransactionException e) { String errMsg = "Error trying to rollback transaction, could not process method: " + e.getMessage(); if (methodContext.isTraceOn()) { @@ -623,14 +667,6 @@ public final class SimpleMethod extends MiniLangElement { return this.defaultSuccessCode; } - private static String getDelegatorEnvName() { - return "delegator"; - } - - private static String getDispatcherEnvName() { - return "dispatcher"; - } - public String getEventErrorMessageListName() { return this.eventErrorMessageListName; } @@ -684,14 +720,6 @@ public final class SimpleMethod extends MiniLangElement { return this.methodOperations; } - private static String getParameterMapName() { - return "parameters"; - } - - private static String getSecurityEnvName() { - return "security"; - } - public String getServiceErrorMessageListName() { return this.serviceErrorMessageListName; } @@ -725,10 +753,6 @@ public final class SimpleMethod extends MiniLangElement { return this; } - public static String getUserLoginEnvName() { - return "userLogin"; - } - public boolean getUseTransaction() { return this.useTransaction; } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/ValidationException.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/ValidationException.java index ede60d4..17b8aeb 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/ValidationException.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/ValidationException.java @@ -21,7 +21,7 @@ package org.apache.ofbiz.minilang; import org.w3c.dom.Element; /** - * Thrown to indicate that a Mini-language element is invalid. + * Thrown to indicate that a Mini-language element is invalid. */ @SuppressWarnings("serial") public class ValidationException extends MiniLangException { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CombinedCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CombinedCondition.java index bad8783..1a930ba 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CombinedCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CombinedCondition.java @@ -61,7 +61,7 @@ public abstract class CombinedCondition extends MiniLangElement implements Condi } /** - * A <and> element factory. + * A <and> element factory. */ public static final class AndConditionFactory extends ConditionalFactory<CombinedCondition> { @Override @@ -92,7 +92,7 @@ public abstract class CombinedCondition extends MiniLangElement implements Condi } /** - * A <not> element factory. + * A <not> element factory. */ public static final class NotConditionFactory extends ConditionalFactory<CombinedCondition> { @Override @@ -124,7 +124,7 @@ public abstract class CombinedCondition extends MiniLangElement implements Condi } /** - * A <or> element factory. + * A <or> element factory. */ public static final class OrConditionFactory extends ConditionalFactory<CombinedCondition> { @Override @@ -155,7 +155,7 @@ public abstract class CombinedCondition extends MiniLangElement implements Condi } /** - * A <xor> element factory. + * A <xor> element factory. */ public static final class XorConditionFactory extends ConditionalFactory<CombinedCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Compare.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Compare.java index 0cfd0b6..d0afe93 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Compare.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Compare.java @@ -132,8 +132,8 @@ public abstract class Compare { Object convertedLvalue = MiniLangUtil.convertType(lValue, type, locale, timeZone, format); Object convertedRvalue = MiniLangUtil.convertType(rValue, type, locale, timeZone, format); assertValuesNotNull(convertedLvalue, convertedRvalue); - if (convertedLvalue instanceof Comparable && - convertedRvalue instanceof Comparable) { + if (convertedLvalue instanceof Comparable + && convertedRvalue instanceof Comparable) { Comparable<Object> comparable = UtilGenerics.cast(convertedLvalue); return comparable.compareTo(convertedRvalue) > 0; } @@ -148,8 +148,8 @@ public abstract class Compare { Object convertedLvalue = MiniLangUtil.convertType(lValue, type, locale, timeZone, format); Object convertedRvalue = MiniLangUtil.convertType(rValue, type, locale, timeZone, format); assertValuesNotNull(convertedLvalue, convertedRvalue); - if (convertedLvalue instanceof Comparable && - convertedRvalue instanceof Comparable) { + if (convertedLvalue instanceof Comparable + && convertedRvalue instanceof Comparable) { Comparable<Object> comparable = UtilGenerics.cast(convertedLvalue); return comparable.compareTo(convertedRvalue) >= 0; } @@ -206,8 +206,8 @@ public abstract class Compare { Object convertedLvalue = MiniLangUtil.convertType(lValue, type, locale, timeZone, format); Object convertedRvalue = MiniLangUtil.convertType(rValue, type, locale, timeZone, format); assertValuesNotNull(convertedLvalue, convertedRvalue); - if (convertedLvalue instanceof Comparable && - convertedRvalue instanceof Comparable) { + if (convertedLvalue instanceof Comparable + && convertedRvalue instanceof Comparable) { Comparable<Object> comparable = UtilGenerics.cast(convertedLvalue); return comparable.compareTo(convertedRvalue) <= 0; } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareCondition.java index c7b1485..02251bc 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareCondition.java @@ -188,7 +188,7 @@ public final class CompareCondition extends MethodOperation implements Condition } /** - * A <if-compare> element factory. + * A <if-compare> element factory. */ public static final class CompareConditionFactory extends ConditionalFactory<CompareCondition> implements Factory<CompareCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareFieldCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareFieldCondition.java index 42a5920..f9ea7f0 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareFieldCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/CompareFieldCondition.java @@ -199,7 +199,7 @@ public final class CompareFieldCondition extends MethodOperation implements Cond } /** - * A <if-compare-field> element factory. + * A <if-compare-field> element factory. */ public static final class CompareFieldConditionFactory extends ConditionalFactory<CompareFieldCondition> implements Factory<CompareFieldCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Conditional.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Conditional.java index cad644c..3aaaaef 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Conditional.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/Conditional.java @@ -26,7 +26,7 @@ import org.apache.ofbiz.minilang.method.MethodContext; */ public interface Conditional { - public boolean checkCondition(MethodContext methodContext) throws MiniLangException; + boolean checkCondition(MethodContext methodContext) throws MiniLangException; - public void prettyPrint(StringBuilder messageBuffer, MethodContext methodContext); + void prettyPrint(StringBuilder messageBuffer, MethodContext methodContext); } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/EmptyCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/EmptyCondition.java index 0542dea..a7f27e1 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/EmptyCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/EmptyCondition.java @@ -117,7 +117,7 @@ public final class EmptyCondition extends MethodOperation implements Conditional } /** - * A <if-empty> element factory. + * A <if-empty> element factory. */ public static final class EmptyConditionFactory extends ConditionalFactory<EmptyCondition> implements Factory<EmptyCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/HasPermissionCondition.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/HasPermissionCondition.java index bdaccee..d05f9fa 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/HasPermissionCondition.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/HasPermissionCondition.java @@ -142,7 +142,7 @@ public final class HasPermissionCondition extends MethodOperation implements Con } /** - * A <if-has-permission> element factory. + * A <if-has-permission> element factory. */ public static final class HasPermissionConditionFactory extends ConditionalFactory<HasPermissionCondition> implements Factory<HasPermissionCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/MasterIf.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/MasterIf.java index 5810302..d07f7ce 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/MasterIf.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/conditional/MasterIf.java @@ -121,7 +121,7 @@ public final class MasterIf extends MethodOperation { } /** - * A <if> element factory. + * A <if> element factory. */ public static final class MasterIfFactory implements Factory<MasterIf> { @Override 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 b95adbc..7532827 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 @@ -156,7 +156,7 @@ public final class ValidateMethodCondition extends MethodOperation implements Co } /** - * A <if-validate-method> element factory. + * A <if-validate-method> element factory. */ public static final class ValidateMethodConditionFactory extends ConditionalFactory<ValidateMethodCondition> implements Factory<ValidateMethodCondition> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/CheckPermission.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/CheckPermission.java index 1486ffa..cda3db4 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/CheckPermission.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/CheckPermission.java @@ -116,7 +116,7 @@ public final class CheckPermission extends MethodOperation { } /** - * A <check-permission> element factory. + * A <check-permission> element factory. */ public static final class CheckPermissionFactory implements Factory<CheckPermission> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfInstanceOf.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfInstanceOf.java index 76b90c9..ace6d0f 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfInstanceOf.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfInstanceOf.java @@ -118,7 +118,7 @@ public final class IfInstanceOf extends MethodOperation { } /** - * A <if-instance-of> element factory. + * A <if-instance-of> element factory. */ public static final class IfInstanceOfFactory implements Factory<IfInstanceOf> { @Override diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfNotEmpty.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfNotEmpty.java index 6c13b3d..69bf72c 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfNotEmpty.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/ifops/IfNotEmpty.java @@ -87,7 +87,7 @@ public final class IfNotEmpty extends MethodOperation { } /** - * A <if-not-empty> element factory. + * A <if-not-empty> element factory. */ public static final class IfNotEmptyFactory implements Factory<IfNotEmpty> { @Override 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 902ac6f..7a18c56 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 @@ -92,12 +92,12 @@ public class MiniLangTests extends OFBizTestCase { } public void testFieldToResultOperation() throws Exception { - String simpleMethodXml = "<simple-method name=\"testFieldToResult\">" + - " <set field=\"resultValue\" value=\"someResultValue\"/>" + - " <set field=\"result1\" value=\"dynamicResultName\"/>" + - " <field-to-result field=\"resultValue\" result-name=\"constantResultName\"/>" + - " <field-to-result field=\"resultValue\" result-name=\"${result1}\"/>" + - "</simple-method>"; + String simpleMethodXml = "<simple-method name=\"testFieldToResult\">" + + " <set field=\"resultValue\" value=\"someResultValue\"/>" + + " <set field=\"result1\" value=\"dynamicResultName\"/>" + + " <field-to-result field=\"resultValue\" result-name=\"constantResultName\"/>" + + " <field-to-result field=\"resultValue\" result-name=\"${result1}\"/>" + + "</simple-method>"; SimpleMethod methodToTest = createSimpleMethod(simpleMethodXml); MethodContext context = createServiceMethodContext(); String result = methodToTest.exec(context); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/GenericAbstractDispatcher.java b/framework/service/src/main/java/org/apache/ofbiz/service/GenericAbstractDispatcher.java index f71b74e..f17d1c3 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/GenericAbstractDispatcher.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/GenericAbstractDispatcher.java @@ -38,7 +38,7 @@ import org.apache.ofbiz.service.job.JobManagerException; */ public abstract class GenericAbstractDispatcher implements LocalDispatcher { - public static final String MODULE = GenericAbstractDispatcher.class.getName(); + protected static final String MODULE = GenericAbstractDispatcher.class.getName(); protected DispatchContext ctx = null; protected ServiceDispatcher dispatcher = null; diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ModelService.java b/framework/service/src/main/java/org/apache/ofbiz/service/ModelService.java index 3513b4f..9a8be40 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ModelService.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ModelService.java @@ -462,7 +462,6 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } return nameList; } - /** * Creates a map of service IN parameters using Name as key and Type as value. * Skips internal parameters @@ -623,12 +622,12 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali Debug.logVerbose("[ModelService.validate] : required fields - " + requiredNames, MODULE); } if (Debug.verboseOn()) { - Debug.logVerbose("[ModelService.validate] : {" + name + "} : (" + mode + ") Required - " + - requiredTest.size() + " / " + requiredInfo.size(), MODULE); + Debug.logVerbose("[ModelService.validate] : {" + name + "} : (" + mode + ") Required - " + + requiredTest.size() + " / " + requiredInfo.size(), MODULE); } if (Debug.verboseOn()) { - Debug.logVerbose("[ModelService.validate] : {" + name + "} : (" + mode + ") Optional - " + - optionalTest.size() + " / " + optionalInfo.size(), MODULE); + Debug.logVerbose("[ModelService.validate] : {" + name + "} : (" + mode + ") Optional - " + + optionalTest.size() + " / " + optionalInfo.size(), MODULE); } } try { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ModelServiceReader.java b/framework/service/src/main/java/org/apache/ofbiz/service/ModelServiceReader.java index 3e1894b..22b0dc5 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ModelServiceReader.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ModelServiceReader.java @@ -137,8 +137,8 @@ public class ModelServiceReader implements Serializable { // check to see if service with same name has already been read if (modelServices.containsKey(serviceName)) { - Debug.logWarning("Service " + serviceName + " is defined more than once, " + - "most recent will over-write previous definition(s)", MODULE); + Debug.logWarning("Service " + serviceName + " is defined more than once, " + + "most recent will over-write previous definition(s)", MODULE); } ModelService service = createModelService(curServiceElement, resourceLocation); 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 3367498..e55157b 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 @@ -287,8 +287,8 @@ public final class ServiceDispatcher { if (Debug.verboseOn() || modelService.debug) { if (Debug.verboseOn()) { - Debug.logVerbose("[ServiceDispatcher.runSync] : invoking service " + modelService.name + " [" + modelService.location + - "/" + modelService.invoke + "] (" + modelService.engineName + ")", MODULE); + Debug.logVerbose("[ServiceDispatcher.runSync] : invoking service " + modelService.name + " [" + modelService.location + + "/" + modelService.invoke + "] (" + modelService.engineName + ")", MODULE); } } @@ -659,8 +659,8 @@ public final class ServiceDispatcher { } if (Debug.verboseOn() || service.debug) { if (Debug.verboseOn()) { - Debug.logVerbose("[ServiceDispatcher.runAsync] : preparing service " + service.name + " [" + service.location + "/" + service.invoke + - "] (" + service.engineName + ")", MODULE); + Debug.logVerbose("[ServiceDispatcher.runAsync] : preparing service " + service.name + " [" + service.location + "/" + service.invoke + + "] (" + service.engineName + ")", 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 dacf6fc..91926ba 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 @@ -57,13 +57,13 @@ public final class ServiceUtil { /** A little short-cut method to check to see if a service returned an error */ public static boolean isError(Map<String, ? extends Object> results) { - return !(results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) && - ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE)); + return !(results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) + && ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE)); } public static boolean isFailure(Map<String, ? extends Object> results) { - return !(results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) && - ModelService.RESPOND_FAIL.equals(results.get(ModelService.RESPONSE_MESSAGE)); + return !(results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) + && ModelService.RESPOND_FAIL.equals(results.get(ModelService.RESPONSE_MESSAGE)); } /** A little short-cut method to check to see if a service was successful (neither error or failed) */ diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressionWorker.java b/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressionWorker.java index c4ad3f6..b5a72df 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressionWorker.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressionWorker.java @@ -32,28 +32,28 @@ import org.apache.ofbiz.entity.util.EntityQuery; /** TemporalExpression persistence worker. */ public final class TemporalExpressionWorker { - public final static String MODULE = TemporalExpressionWorker.class.getName(); + private static final String MODULE = TemporalExpressionWorker.class.getName(); // Temporal expression type constants - private final static String DateRange = "DATE_RANGE"; - private final static String DayInMonth = "DAY_IN_MONTH"; - private final static String DayOfMonthRange = "DAY_OF_MONTH_RANGE"; - private final static String DayOfWeekRange = "DAY_OF_WEEK_RANGE"; - private final static String Difference = "DIFFERENCE"; - private final static String Frequency = "FREQUENCY"; - private final static String HourRange = "HOUR_RANGE"; - private final static String Intersection = "INTERSECTION"; - private final static String MinuteRange = "MINUTE_RANGE"; - private final static String MonthRange = "MONTH_RANGE"; - private final static String Substitution = "SUBSTITUTION"; - private final static String Union = "UNION"; - private final static String ExpressionTypeList[] = {DateRange, DayInMonth, DayOfMonthRange, DayOfWeekRange, - Difference, Frequency, HourRange, Intersection, MinuteRange, MonthRange, Substitution, Union}; + private static final String DATE_RANGE = "DATE_RANGE"; + private static final String DAY_IN_MONTH = "DAY_IN_MONTH"; + private static final String DAY_OF_MONTH_RANGE = "DAY_OF_MONTH_RANGE"; + private static final String DAY_OF_WEEK_RANGE = "DAY_OF_WEEK_RANGE"; + private static final String DIFFERENCE = "DIFFERENCE"; + private static final String FREQUENCY = "FREQUENCY"; + private static final String HOUR_RANGE = "HOUR_RANGE"; + private static final String INTERSECTION = "INTERSECTION"; + private static final String MINUTE_RANGE = "MINUTE_RANGE"; + private static final String MONTH_RANGE = "MONTH_RANGE"; + private static final String SUBSTITUTION = "SUBSTITUTION"; + private static final String UNION = "UNION"; + private static final String EXP_TYPE_LIST[] = {DATE_RANGE, DAY_IN_MONTH, DAY_OF_MONTH_RANGE, DAY_OF_WEEK_RANGE, + DIFFERENCE, FREQUENCY, HOUR_RANGE, INTERSECTION, MINUTE_RANGE, MONTH_RANGE, SUBSTITUTION, UNION}; // Temporal expression assoc type constants - private final static String INCLUDE = "INCLUDE"; - private final static String EXCLUDE = "EXCLUDE"; - private final static String SUBSTITUTE = "SUBSTITUTE"; + private static final String INCLUDE = "INCLUDE"; + private static final String EXCLUDE = "EXCLUDE"; + private static final String SUBSTITUTE = "SUBSTITUTE"; private TemporalExpressionWorker() { } @@ -90,15 +90,15 @@ public final class TemporalExpressionWorker { public static TemporalExpression makeTemporalExpression(Delegator delegator, GenericValue exprValue) throws GenericEntityException { String tempExprId = exprValue.getString("tempExprId"); String tempExprTypeId = exprValue.getString("tempExprTypeId"); - if (DateRange.equals(tempExprTypeId)) { + if (DATE_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.DateRange(exprValue.getTimestamp("date1"), exprValue.getTimestamp("date2"))); - } else if (DayInMonth.equals(tempExprTypeId)) { + } else if (DAY_IN_MONTH.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.DayInMonth(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (DayOfMonthRange.equals(tempExprTypeId)) { + } else if (DAY_OF_MONTH_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.DayOfMonthRange(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (DayOfWeekRange.equals(tempExprTypeId)) { + } else if (DAY_OF_WEEK_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.DayOfWeekRange(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (Difference.equals(tempExprTypeId)) { + } else if (DIFFERENCE.equals(tempExprTypeId)) { List<GenericValue> childExpressions = EntityQuery.use(delegator).from("TemporalExpressionAssoc").where("fromTempExprId", tempExprId).cache(true).queryList(); GenericValue inclAssoc = null; GenericValue exclAssoc = null; @@ -112,17 +112,17 @@ public final class TemporalExpressionWorker { if (inclAssoc != null && exclAssoc != null) { return setExpressionId(exprValue, new TemporalExpressions.Difference(getTemporalExpression(delegator, inclAssoc.getString("toTempExprId")), getTemporalExpression(delegator, exclAssoc.getString("toTempExprId")))); } - } else if (Frequency.equals(tempExprTypeId)) { + } else if (FREQUENCY.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.Frequency(exprValue.getTimestamp("date1"), exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (HourRange.equals(tempExprTypeId)) { + } else if (HOUR_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.HourRange(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (Intersection.equals(tempExprTypeId)) { + } else if (INTERSECTION.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.Intersection(getChildExpressions(delegator, tempExprId))); - } else if (MinuteRange.equals(tempExprTypeId)) { + } else if (MINUTE_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.MinuteRange(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (MonthRange.equals(tempExprTypeId)) { + } else if (MONTH_RANGE.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.MonthRange(exprValue.getLong("integer1").intValue(), exprValue.getLong("integer2").intValue())); - } else if (Substitution.equals(tempExprTypeId)) { + } else if (SUBSTITUTION.equals(tempExprTypeId)) { List<GenericValue> childExpressions = EntityQuery.use(delegator).from("TemporalExpressionAssoc").where("fromTempExprId", tempExprId).cache(true).queryList(); GenericValue inclAssoc = null; GenericValue exclAssoc = null; @@ -139,7 +139,7 @@ public final class TemporalExpressionWorker { if (inclAssoc != null && exclAssoc != null && substAssoc != null) { return setExpressionId(exprValue, new TemporalExpressions.Substitution(getTemporalExpression(delegator, inclAssoc.getString("toTempExprId")), getTemporalExpression(delegator, exclAssoc.getString("toTempExprId")), getTemporalExpression(delegator, substAssoc.getString("toTempExprId")))); } - } else if (Union.equals(tempExprTypeId)) { + } else if (UNION.equals(tempExprTypeId)) { return setExpressionId(exprValue, new TemporalExpressions.Union(getChildExpressions(delegator, tempExprId))); } return TemporalExpressions.NullExpression; @@ -163,6 +163,6 @@ public final class TemporalExpressionWorker { } public static String[] getExpressionTypeList() { - return ExpressionTypeList.clone(); + return EXP_TYPE_LIST.clone(); } } 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 5e3df79..bc70ee2 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 @@ -95,7 +95,7 @@ public final class ServiceConfigUtil { /** * Returns the default service engine configuration (named "default"). - * @throws GenericConfigException + * @throws GenericConfigException */ public static ServiceEngine getServiceEngine() throws GenericConfigException { return getServiceConfig().getServiceEngine(engine); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/eca/ServiceEcaCondition.java b/framework/service/src/main/java/org/apache/ofbiz/service/eca/ServiceEcaCondition.java index 2d4927e..3d6bfa1 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/eca/ServiceEcaCondition.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/eca/ServiceEcaCondition.java @@ -125,8 +125,8 @@ public class ServiceEcaCondition implements java.io.Serializable { Boolean conditionReply = Boolean.FALSE; if (ServiceUtil.isError(conditionServiceResult)) { - Debug.logError("Error in condition-service : " + - ServiceUtil.getErrorMessage(conditionServiceResult), MODULE); + Debug.logError("Error in condition-service : " + + ServiceUtil.getErrorMessage(conditionServiceResult), MODULE); } else { conditionReply = (Boolean) conditionServiceResult.get("conditionReply"); } 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 ac2e7db..0148b12 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 @@ -283,13 +283,13 @@ public final class EntityAutoEngine extends GenericAsyncEngine { newEntity.set(pkFieldName, pkValue); } } else { - throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the create invoke option: " + - "could not find a valid combination of primary key settings to do a known create operation; options include: " + - "1. a single OUT pk for primary auto-sequencing, " + - "2. a single INOUT pk for primary auto-sequencing with optional override, " + - "3. a 2-part pk with one part IN (existing primary pk) and one part OUT (the secondary pk to sub-sequence), " + - "4. a N-part pk with N-1 part IN and one party OUT only (missing pk is a sub-sequence mainly for entity assoc), " + - "5. all pk fields are IN for a manually specified primary key"); + throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the create invoke option: " + + "could not find a valid combination of primary key settings to do a known create operation; options include: " + + "1. a single OUT pk for primary auto-sequencing, " + + "2. a single INOUT pk for primary auto-sequencing with optional override, " + + "3. a 2-part pk with one part IN (existing primary pk) and one part OUT (the secondary pk to sub-sequence), " + + "4. a N-part pk with N-1 part IN and one party OUT only (missing pk is a sub-sequence mainly for entity assoc), " + + "5. all pk fields are IN for a manually specified primary key"); } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericEngine.java index ed658d0..4a8e64b 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericEngine.java @@ -29,8 +29,8 @@ import org.apache.ofbiz.service.ModelService; */ public interface GenericEngine { - public static final int ASYNC_MODE = 22; - public static final int SYNC_MODE = 21; + int ASYNC_MODE = 22; + int SYNC_MODE = 21; /** * Run the service synchronously and return the result. @@ -41,7 +41,7 @@ public interface GenericEngine { * @return Map of name, value pairs composing the result. * @throws GenericServiceException */ - public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; + Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; /** * Run the service synchronously and IGNORE the result. @@ -51,7 +51,7 @@ public interface GenericEngine { * @param context Map of name, value pairs composing the context. * @throws GenericServiceException */ - public void runSyncIgnore(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; + void runSyncIgnore(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; /** * Run the service asynchronously, passing an instance of GenericRequester that will receive the result. @@ -63,7 +63,7 @@ public interface GenericEngine { * @param persist True for store/run; False for run. * @throws GenericServiceException */ - public void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) + void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) throws GenericServiceException; /** @@ -75,7 +75,7 @@ public interface GenericEngine { * @param persist True for store/run; False for run. * @throws GenericServiceException */ - public void runAsync(String localName, ModelService modelService, Map<String, Object> context, boolean persist) throws GenericServiceException; + void runAsync(String localName, ModelService modelService, Map<String, Object> context, boolean persist) throws GenericServiceException; /** * Send the service callbacks @@ -84,8 +84,8 @@ public interface GenericEngine { * @param mode Service mode (sync or async) * @throws GenericServiceException */ - public void sendCallbacks(ModelService modelService, Map<String, Object> context, int mode) throws GenericServiceException; - public void sendCallbacks(ModelService modelService, Map<String, Object> context, Map<String, Object> result, int mode) throws GenericServiceException; - public void sendCallbacks(ModelService modelService, Map<String, Object> context, Throwable t, int mode) throws GenericServiceException; + void sendCallbacks(ModelService modelService, Map<String, Object> context, int mode) throws GenericServiceException; + void sendCallbacks(ModelService modelService, Map<String, Object> context, Map<String, Object> result, int mode) throws GenericServiceException; + void sendCallbacks(ModelService modelService, Map<String, Object> context, Throwable t, int mode) throws GenericServiceException; } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/jms/GenericMessageListener.java b/framework/service/src/main/java/org/apache/ofbiz/service/jms/GenericMessageListener.java index e8157cf..8fc5cd3 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/jms/GenericMessageListener.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/jms/GenericMessageListener.java @@ -31,24 +31,24 @@ public interface GenericMessageListener extends MessageListener { * Shutdown the listener and all connection(s). * @throws GenericServiceException */ - public void close() throws GenericServiceException; + void close() throws GenericServiceException; /** * Start the listener and all connection(s). * @throws GenericServiceException */ - public void load() throws GenericServiceException; + void load() throws GenericServiceException; /** * Refresh the connection. * @throws GenericServiceException */ - public void refresh() throws GenericServiceException; + void refresh() throws GenericServiceException; /** * Indicator if a connection is present. * @return true if connectio is present. */ - public boolean isConnected(); + boolean isConnected(); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/job/AbstractJob.java b/framework/service/src/main/java/org/apache/ofbiz/service/job/AbstractJob.java index e97d411..2578120 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/job/AbstractJob.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/job/AbstractJob.java @@ -116,7 +116,7 @@ public abstract class AbstractJob implements Job { return (Date) startTime.clone(); } - /* + /* * Returns JobPriority.NORMAL, the default setting */ @Override diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/job/JobPoller.java b/framework/service/src/main/java/org/apache/ofbiz/service/job/JobPoller.java index aaf7dae..90fe414 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/job/JobPoller.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/job/JobPoller.java @@ -65,22 +65,22 @@ public final class JobPoller implements ServiceConfigListener { try { ThreadPool threadPool = ServiceConfigUtil.getServiceEngine(ServiceConfigUtil.getEngine()).getThreadPool(); return new ThreadPoolExecutor( - threadPool.getMinThreads(), - threadPool.getMaxThreads(), + threadPool.getMinThreads(), + threadPool.getMaxThreads(), threadPool.getTtl(), - TimeUnit.MILLISECONDS, - new PriorityBlockingQueue<>(threadPool.getJobs(), createPriorityComparator()), - new JobInvokerThreadFactory(), + TimeUnit.MILLISECONDS, + new PriorityBlockingQueue<>(threadPool.getJobs(), createPriorityComparator()), + new JobInvokerThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } catch (GenericConfigException e) { Debug.logError(e, "Exception thrown while getting <thread-pool> model, using default <thread-pool> values: ", MODULE); return new ThreadPoolExecutor( - ThreadPool.MIN_THREADS, - ThreadPool.MAX_THREADS, + ThreadPool.MIN_THREADS, + ThreadPool.MAX_THREADS, ThreadPool.THREAD_TTL, - TimeUnit.MILLISECONDS, - new PriorityBlockingQueue<>(ThreadPool.QUEUE_SIZE, createPriorityComparator()), - new JobInvokerThreadFactory(), + TimeUnit.MILLISECONDS, + new PriorityBlockingQueue<>(ThreadPool.QUEUE_SIZE, createPriorityComparator()), + new JobInvokerThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } } 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 0def753..0a1c06a 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 @@ -387,7 +387,7 @@ public class PersistedServiceJob extends GenericServiceJob { return new Date(startTime); } - /* + /* * Returns the priority stored in the JobSandbox.priority field, if no value is present * then it defaults to AbstractJob.getPriority() */ diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/job/PurgeJob.java b/framework/service/src/main/java/org/apache/ofbiz/service/job/PurgeJob.java index dc30d59..11c1729 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/job/PurgeJob.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/job/PurgeJob.java @@ -58,7 +58,7 @@ public class PurgeJob extends AbstractJob implements Serializable { } } - /* + /* * Returns JobPriority.LOW */ @Override diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/rmi/ExampleRemoteClient.java b/framework/service/src/main/java/org/apache/ofbiz/service/rmi/ExampleRemoteClient.java index cd037aa..03ab35d 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/rmi/ExampleRemoteClient.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/rmi/ExampleRemoteClient.java @@ -49,7 +49,7 @@ import org.apache.ofbiz.service.GenericServiceException; public class ExampleRemoteClient { private static final String MODULE = ExampleRemoteClient.class.getName(); - protected final static String RMI_URL = "rmi://localhost:1099/RMIDispatcher"; // change to match the remote server + protected static final String RMI_URL = "rmi://localhost:1099/RMIDispatcher"; // change to match the remote server protected RemoteDispatcher rd = null; public ExampleRemoteClient() { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTestServices.java b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTestServices.java index fc6433a..3e3ba43 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTestServices.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/test/ServiceEngineTestServices.java @@ -54,17 +54,20 @@ public class ServiceEngineTestServices { Map<String, Object> threadBResult = threadBWaiter.waitForResult(); List<Object> errorList = new LinkedList<>(); if (ServiceUtil.isError(threadAResult)) { - errorList.add(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockThreadA", UtilMisc.toMap("errorString", ServiceUtil.getErrorMessage(threadAResult)), locale)); + errorList.add(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockThreadA", UtilMisc.toMap("errorString", + ServiceUtil.getErrorMessage(threadAResult)), locale)); } if (ServiceUtil.isError(threadBResult)) { - errorList.add(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockThreadB", UtilMisc.toMap("errorString", ServiceUtil.getErrorMessage(threadBResult)), locale)); + errorList.add(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockThreadB", UtilMisc.toMap("errorString", + ServiceUtil.getErrorMessage(threadBResult)), locale)); } if (errorList.size() > 0) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockRetry", locale), errorList, null, null); } } catch (Exception e) { Debug.logError(e, "Error running deadlock test services: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockError", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockError", UtilMisc.toMap("errorString", + e.toString()), locale)); } return ServiceUtil.returnSuccess(); @@ -90,18 +93,22 @@ public class ServiceEngineTestServices { Debug.logInfo("In testServiceDeadLockRetryThreadA done with updating SVCLRT_B, updating SVCLRT_AONLY", MODULE); GenericValue testingTypeAOnly = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVCLRT_AONLY").queryOne(); - testingTypeAOnly.set("description", "New description for SVCLRT_AONLY; this is only changed by thread A so if it doesn't match something happened to thread A!"); + testingTypeAOnly.set("description", "New description for SVCLRT_AONLY; this is only changed by thread A so if it doesn't match " + + "something happened to thread A!"); testingTypeAOnly.store(); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running dead lock test thread A: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineExceptionThreadA", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineExceptionThreadA", UtilMisc.toMap( + "errorString", e.toString()), locale)); } catch (InterruptedException e) { Debug.logError(e, "Wait Interrupted Exception running dead lock test thread A: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineWaitInterruptedExceptionThreadA", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineWaitInterruptedExceptionThreadA", + UtilMisc.toMap("errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceDeadLockRetryThreadB(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -122,14 +129,17 @@ public class ServiceEngineTestServices { Debug.logInfo("In testServiceDeadLockRetryThreadA done with updating SVCLRT_A, updating SVCLRT_BONLY", MODULE); GenericValue testingTypeAOnly = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVCLRT_BONLY").queryOne(); - testingTypeAOnly.set("description", "New description for SVCLRT_BONLY; this is only changed by thread B so if it doesn't match something happened to thread B!"); + testingTypeAOnly.set("description", "New description for SVCLRT_BONLY; this is only changed by thread B so if it doesn't match " + + "something happened to thread B!"); testingTypeAOnly.store(); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running dead lock test thread B: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineExceptionThreadB", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineExceptionThreadB", UtilMisc.toMap( + "errorString", e.toString()), locale)); } catch (InterruptedException e) { Debug.logError(e, "Wait Interrupted Exception running dead lock test thread B: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineWaitInterruptedExceptionThreadB", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineWaitInterruptedExceptionThreadB", + UtilMisc.toMap("errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); @@ -159,18 +169,21 @@ public class ServiceEngineTestServices { } } catch (Exception e) { Debug.logError(e, "Error running deadlock test services: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockError", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestDeadLockError", UtilMisc.toMap("errorString", + e.toString()), locale)); } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceLockWaitTimeoutRetryGrabber(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); try { // grab entity SVCLWTRT by changing, then wait a LONG time, ie more than the wait timeout GenericValue testingType = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVCLWTRT").queryOne(); - testingType.set("description", "New description for SVCLWTRT from the GRABBER service, this should be replaced by Waiter service in the service engine auto-retry"); + testingType.set("description", "New description for SVCLWTRT from the GRABBER service, this should be replaced by Waiter service in the" + + " service engine auto-retry"); testingType.store(); Debug.logInfo("In testServiceLockWaitTimeoutRetryGrabber just updated SVCLWTRT, beginning wait", MODULE); @@ -180,14 +193,17 @@ public class ServiceEngineTestServices { Thread.sleep(4 * 1000); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running lock wait timeout test Grabber thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryGrabber", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryGrabber", UtilMisc.toMap( + "errorString", e.toString()), locale)); } catch (InterruptedException e) { Debug.logError(e, "Wait Interrupted Exception running lock wait timeout test Grabber thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryGrabber", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryGrabber", UtilMisc.toMap( + "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceLockWaitTimeoutRetryWaiter(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -205,10 +221,12 @@ public class ServiceEngineTestServices { Debug.logInfo("In testServiceLockWaitTimeoutRetryWaiter successfully updated SVCLWTRT", MODULE); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running lock wait timeout test Waiter thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryWaiter", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryWaiter", UtilMisc.toMap( + "errorString", e.toString()), locale)); } catch (InterruptedException e) { Debug.logError(e, "Wait Interrupted Exception running lock wait timeout test Waiter thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryWaiter", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryWaiter", UtilMisc.toMap( + "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); @@ -221,14 +239,14 @@ public class ServiceEngineTestServices { * testServiceLockWaitTimeoutRetryCantRecoverWaiter would NOT be able to recover because it would try again * given the new transaction and all, but the lock for the waiting thread would still be there... so it will fail * repeatedly. - * + * <p> * TODO: there's got to be some way to do this, but how?!? :( - * + * <p> * NOTE: maybe this will work: create a list that the service engine maintains of services it will run after the * current service run is complete, and AFTER it has committed or rolled back its transaction; if a service finds * it has a lock wait timeout, add itself to the list for its parent service (somehow...) and off we go! * - * @param dctx the dispatch context + * @param dctx the dispatch context * @param context the context * @return returns the results of the service execution */ @@ -239,27 +257,34 @@ public class ServiceEngineTestServices { try { // grab entity SVCLWTRTCR by changing, then wait a LONG time, ie more than the wait timeout GenericValue testingType = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVCLWTRTCR").queryOne(); - testingType.set("description", "New description for SVCLWTRTCR from Lock Wait Timeout Lock GRABBER, this should be replaced by the one in the Waiter service."); + testingType.set("description", "New description for SVCLWTRTCR from Lock Wait Timeout Lock GRABBER, this should be replaced by the one " + + "in the Waiter service."); testingType.store(); - Debug.logInfo("In testServiceLockWaitTimeoutRetryCantRecover (grabber) just updated SVCLWTRTCR, running sub-service in own transaction", MODULE); - // timeout is 5 seconds so it is longer than the tx timeout for this service, so will fail quickly; with this transaction keeping a lock on the record and that one trying to get it, bam we cause the error + Debug.logInfo("In testServiceLockWaitTimeoutRetryCantRecover (grabber) just updated SVCLWTRTCR, running sub-service in own transaction", + MODULE); + // timeout is 5 seconds so it is longer than the tx timeout for this service, so will fail quickly; with this transaction keeping a + // lock on the record and that one trying to get it, bam we cause the error Map<String, Object> waiterResult = dispatcher.runSync("testServiceLockWaitTimeoutRetryCantRecoverWaiter", null, 5, true); if (ServiceUtil.isError(waiterResult)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryCantRecoverWaiter", locale), null, null, waiterResult); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockWaitTimeoutRetryCantRecoverWaiter", locale), + null, null, waiterResult); } - Debug.logInfo("In testServiceLockWaitTimeoutRetryCantRecover (grabber) successfully finished running sub-service in own transaction", MODULE); + Debug.logInfo("In testServiceLockWaitTimeoutRetryCantRecover (grabber) successfully finished running sub-service in own transaction", + MODULE); } catch (GenericServiceException e) { String errMsg = "Error running deadlock test services: " + e.toString(); Debug.logError(e, errMsg, MODULE); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running lock wait timeout test main/Grabber thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryGrabber", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryGrabber", UtilMisc.toMap( + "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceLockWaitTimeoutRetryCantRecoverWaiter(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -268,13 +293,15 @@ public class ServiceEngineTestServices { // TRY grab entity SVCLWTRTCR by looking up and changing, should get a lock wait timeout exception because of the Grabber thread GenericValue testingType = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVCLWTRTCR").queryOne(); - testingType.set("description", "New description for SVCLWTRTCR from Lock Wait Timeout Lock Waiter, this is the value that should be there."); + testingType.set("description", "New description for SVCLWTRTCR from Lock Wait Timeout Lock Waiter, this is the value that should be " + + "there."); testingType.store(); Debug.logInfo("In testServiceLockWaitTimeoutRetryCantRecoverWaiter successfully updated SVCLWTRTCR", MODULE); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception running lock wait timeout test Waiter thread: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryWaiter", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestLockInterruptedExceptionRetryWaiter", UtilMisc.toMap( + "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); @@ -282,45 +309,55 @@ public class ServiceEngineTestServices { // ================================================== - public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParentErrorCatchWrapper(DispatchContext dctx, Map<String, ? extends Object> context) { + public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParentErrorCatchWrapper(DispatchContext dctx, Map<String, ? + extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); try { Map<String, Object> resultMap = dispatcher.runSync("testServiceOwnTxSubServiceAfterSetRollbackOnlyInParent", null, 60, true); if (ServiceUtil.isError(resultMap)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestOwnTxSubServiceAfterSetRollbackOnlyInParentErrorCatchWrapper", locale), null, null, resultMap); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ServiceTestOwnTxSubServiceAfterSetRollbackOnlyInParentErrorCatchWrapper", locale), null, null, resultMap); } } catch (GenericServiceException e) { - String errMsg = "This is the expected error running sub-service with own tx after the parent has set rollback only, logging and ignoring: " + e.toString(); + String errMsg = "This is the expected error running sub-service with own tx after the parent has set rollback only, logging and " + + "ignoring: " + e.toString(); Debug.logError(e, errMsg, MODULE); } return ServiceUtil.returnSuccess(); } - public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParent(DispatchContext dctx, Map<String, ? extends Object> context) { + + public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParent(DispatchContext dctx, + Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); try { // change the SVC_SRBO value first to test that the rollback really does revert/reset GenericValue testingType = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "SVC_SRBO").queryOne(); - testingType.set("description", "New description for SVC_SRBO; this should be reset on the rollback, if this is in the db then the test failed"); + testingType.set("description", "New description for SVC_SRBO; this should be reset on the rollback, if this is in the db then the test " + + "failed"); testingType.store(); TransactionUtil.setRollbackOnly("Intentionally setting rollback only for testing purposes", null); Map<String, Object> resultMap = dispatcher.runSync("testServiceOwnTxSubServiceAfterSetRollbackOnlyInParentSubService", null, 60, true); if (ServiceUtil.isError(resultMap)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestOwnTxSubServiceAfterSetRollbackOnlyInParent", locale), null, null, resultMap); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestOwnTxSubServiceAfterSetRollbackOnlyInParent", + locale), null, null, resultMap); } } catch (Exception e) { Debug.logError(e, "Error running sub-service with own tx: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestOwnTxError", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestOwnTxError", UtilMisc.toMap("errorString", e.toString()) + , locale)); } return ServiceUtil.returnSuccess(); } - public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParentSubService(DispatchContext dctx, Map<String, ? extends Object> context) { + + public static Map<String, Object> testServiceOwnTxSubServiceAfterSetRollbackOnlyInParentSubService(DispatchContext dctx, Map<String, ? + extends Object> context) { // this service doesn't actually have to do anything, the problem was in just pausing and resuming the transaciton with setRollbackOnly return ServiceUtil.returnSuccess(); } @@ -335,13 +372,17 @@ public class ServiceEngineTestServices { // this will return an error, but we'll ignore the result dispatcher.runSync("testServiceEcaGlobalEventExecToRollback", null, 60, true); } catch (GenericServiceException e) { - Debug.logError(e, "Error calling sub-service, it should return an error but not throw an exception, so something went wrong: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestSubServiceError", UtilMisc.toMap("errorString", e.toString()), locale)); + Debug.logError(e, + "Error calling sub-service, it should return an error but not throw an exception, so something went wrong: " + e.toString(), + MODULE); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestSubServiceError", UtilMisc.toMap("errorString", + e.toString()), locale)); } // this service doesn't actually have to do anything, just a placeholder for ECA rules, this one should commit return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceEcaGlobalEventExecOnCommit(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -351,16 +392,19 @@ public class ServiceEngineTestServices { testingType.store(); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineError", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineError", UtilMisc.toMap("errorString", + e.toString()), locale)); } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> testServiceEcaGlobalEventExecToRollback(DispatchContext dctx, Map<String, ? extends Object> context) { // this service doesn't actually have to do anything, just a placeholder for ECA rules, this one should rollback Locale locale = (Locale) context.get("locale"); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestRollback", locale)); } + public static Map<String, Object> testServiceEcaGlobalEventExecOnRollback(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -370,7 +414,8 @@ public class ServiceEngineTestServices { testingType.store(); } catch (GenericEntityException e) { Debug.logError(e, "Entity Engine Exception: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineError", UtilMisc.toMap("errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceTestEntityEngineError", UtilMisc.toMap("errorString", + e.toString()), locale)); } return ServiceUtil.returnSuccess(); 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 612aba7..72a53d4 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 @@ -29,7 +29,7 @@ import org.apache.ofbiz.service.testtools.OFBizTestCase; public class ServiceSOAPTests extends OFBizTestCase { - public final static String MODULE = ServiceSOAPTests.class.getName(); + private static final String MODULE = ServiceSOAPTests.class.getName(); public ServiceSOAPTests(String name) { super(name); diff --git a/framework/start/src/main/java/org/apache/ofbiz/base/start/Start.java b/framework/start/src/main/java/org/apache/ofbiz/base/start/Start.java index 40d19dd..f2274f0 100644 --- a/framework/start/src/main/java/org/apache/ofbiz/base/start/Start.java +++ b/framework/start/src/main/java/org/apache/ofbiz/base/start/Start.java @@ -50,7 +50,7 @@ public final class Start { private final AtomicReference<ServerState> serverState = new AtomicReference<>(ServerState.STARTING); // Singleton, do not change - private static final Start instance = new Start(); + private static final Start INSTANCE = new Start(); private Start() { } @@ -73,21 +73,21 @@ public final class Start { CommandType commandType = CommandType.valueOf(ofbizCommands); if (!commandType.equals(CommandType.HELP)) { - instance.config = StartupControlPanel.init(ofbizCommands); + INSTANCE.config = StartupControlPanel.init(ofbizCommands); } switch (commandType) { case HELP: StartupCommandUtil.printOfbizStartupHelp(System.out); break; case STATUS: - System.out.println("Current Status : " + AdminClient.requestStatus(instance.config)); + System.out.println("Current Status : " + AdminClient.requestStatus(INSTANCE.config)); break; case SHUTDOWN: - System.out.println("Shutting down server : " + AdminClient.requestShutdown(instance.config)); + System.out.println("Shutting down server : " + AdminClient.requestShutdown(INSTANCE.config)); break; case START: try { - StartupControlPanel.start(instance.config, instance.serverState, ofbizCommands, instance.loader); + StartupControlPanel.start(INSTANCE.config, INSTANCE.serverState, ofbizCommands, INSTANCE.loader); } catch (StartupException e) { StartupControlPanel.fullyTerminateSystem(e); } @@ -99,7 +99,7 @@ public final class Start { * Returns the <code>Start</code> instance. */ public static Start getInstance() { - return instance; + return INSTANCE; } /** @@ -150,8 +150,7 @@ public final class Start { /** * Determines the type of command from a list of command-line commands - * - * @param ofbizCommands the list of parsed command-line arguments which cannot be {@code null} + * @param ofbizCommands the list of parsed command-line arguments which cannot be {@code null} * @return the corresponding command type. */ static CommandType valueOf(List<StartupCommand> ofbizCommands) { 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 199a11b..9a1f02e 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 @@ -52,7 +52,7 @@ public class SimpleMethodTest extends OFBizTestCase { /** * Tests of Simple Method * @param caseName test case name - * @param mainElement DOM main element + * @param mainElement DOM main element */ public SimpleMethodTest(String caseName, Element mainElement) { this(caseName, mainElement.getAttribute("location"), mainElement.getAttribute("name")); 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 6b5511b..92a6d24 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 @@ -146,8 +146,8 @@ public class TestRunContainer implements Container { private static void logTestSuiteResults(TestSuite suite, TestResult results) { Debug.logInfo("[JUNIT] Results for test suite: " + suite.getName(), MODULE); - Debug.logInfo("[JUNIT] Pass: " + results.wasSuccessful() + " | # Tests: " + results.runCount() + " | # Failed: " + - results.failureCount() + " # Errors: " + results.errorCount(), MODULE); + Debug.logInfo("[JUNIT] Pass: " + results.wasSuccessful() + " | # Tests: " + results.runCount() + " | # Failed: " + + results.failureCount() + " # Errors: " + results.errorCount(), MODULE); if (Debug.importantOn() && !results.wasSuccessful()) { Debug.logInfo("[JUNIT] ----------------------------- ERRORS ----------------------------- [JUNIT]", MODULE); logErrorsOrFailures(results.errors()); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java index 4873af7..a71580b 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ContextFilter.java @@ -171,10 +171,10 @@ public class ContextFilter implements Filter { request.setAttribute("userTenantId", tenantId); } - // NOTE DEJ20101130: do NOT always put the delegator name in the user's session because the user may - // have logged in and specified a tenant, and even if no Tenant record with a matching domainName field - // is found this will change the user's delegator back to the base one instead of the one for the - // tenant specified on login + // NOTE DEJ20101130: do NOT always put the delegator name in the user's session because the user may + // have logged in and specified a tenant, and even if no Tenant record with a matching domainName field + // is found this will change the user's delegator back to the base one instead of the one for the + // tenant specified on login // httpRequest.getSession().setAttribute("delegatorName", delegator.getDelegatorName()); } catch (GenericEntityException e) { Debug.logWarning(e, "Unable to get Tenant", MODULE); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ControlActivationEventListener.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ControlActivationEventListener.java index 27e7e5d..2315cb6 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ControlActivationEventListener.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ControlActivationEventListener.java @@ -48,7 +48,7 @@ public class ControlActivationEventListener implements HttpSessionActivationList public static String showSessionId(HttpSession session) { boolean showSessionIdInLog = UtilProperties.propertyValueEqualsIgnoreCase("requestHandler", "show-sessionId-in-log", "Y"); if (showSessionIdInLog) { - return " sessionId=" + session.getId(); + return " sessionId=" + session.getId(); } return " hidden sessionId by default."; } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/JWTManager.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/JWTManager.java index 4b5fc6f..30d239c 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/JWTManager.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/JWTManager.java @@ -269,7 +269,7 @@ public class JWTManager { * @param delegator * @param jwtToken * @param keySalt - * @return Map of the claims contained in the token or an error + * @return Map of the claims contained in the token or an error */ public static Map<String, Object> validateToken(Delegator delegator, String jwtToken, String keySalt) { return validateToken(jwtToken, JWTManager.getJWTKey(delegator, keySalt)); 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 ee66b27..788346a 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 @@ -389,8 +389,8 @@ public final class LoginWorker { */ public static String login(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); - // Prevent session fixation by making Tomcat generate a new jsessionId (ultimately put in cookie). - if (!session.isNew()) { // Only do when really signing in. + // Prevent session fixation by making Tomcat generate a new jsessionId (ultimately put in cookie). + if (!session.isNew()) { // Only do when really signing in. request.changeSessionId(); } Delegator delegator = (Delegator) request.getAttribute("delegator"); @@ -941,9 +941,9 @@ public final class LoginWorker { String serverId = (String) request.getServletContext().getAttribute("_serverId"); String applicationName = UtilHttp.getApplicationName(request); Optional<WebappInfo> webappInfo = WEBAPPS.getWebappInfo(serverId, applicationName); - if (userLogin != null && + if (userLogin != null // When using an empty mountpoint, ie using root as mountpoint. Beware: works only for 1 webapp! - webappInfo.map(WebappInfo::isAutologinCookieUsed).orElse(!webappInfo.isPresent())) { + && webappInfo.map(WebappInfo::isAutologinCookieUsed).orElse(!webappInfo.isPresent())) { Cookie autoLoginCookie = new Cookie(getAutoLoginCookieName(request), userLogin.getString("userLoginId")); autoLoginCookie.setMaxAge(60 * 60 * 24 * 365); autoLoginCookie.setDomain(EntityUtilProperties.getPropertyValue("url", "cookie.domain", delegator)); @@ -1311,8 +1311,8 @@ public final class LoginWorker { Debug.logWarning(e, "Unable to refresh UserLogin", MODULE); } } - return (userLogin.get("hasLoggedOut") != null ? - "Y".equalsIgnoreCase(userLogin.getString("hasLoggedOut")) : false); + return (userLogin.get("hasLoggedOut") != null + ? "Y".equalsIgnoreCase(userLogin.getString("hasLoggedOut")) : false); } /** diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ProtectViewWorker.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ProtectViewWorker.java index f83c1c9..3fa32c3 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ProtectViewWorker.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ProtectViewWorker.java @@ -41,7 +41,7 @@ import org.apache.ofbiz.entity.util.EntityQuery; */ public final class ProtectViewWorker { - private final static String MODULE = ProtectViewWorker.class.getName(); + private static final String MODULE = ProtectViewWorker.class.getName(); private static final String resourceWebapp = "WebappUiLabels"; private static final Map<String, Long> hitsByViewAccessed = new ConcurrentHashMap<>(); private static final Map<String, Long> durationByViewAccessed = new ConcurrentHashMap<>(); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/RequestHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/RequestHandler.java index c8d30ea..cca5015 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/RequestHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/RequestHandler.java @@ -89,15 +89,6 @@ public class RequestHandler { private final List<String> hostHeadersAllowed; private ControllerConfig ccfg; - public static RequestHandler getRequestHandler(ServletContext servletContext) { - RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_"); - if (rh == null) { - rh = new RequestHandler(servletContext); - servletContext.setAttribute("_REQUEST_HANDLER_", rh); - } - return rh; - } - private RequestHandler(ServletContext context) { // init the ControllerConfig, but don't save it anywhere, just load it into the cache this.controllerConfigURL = ConfigXMLReader.getControllerConfigURL(context); @@ -116,14 +107,13 @@ public class RequestHandler { } - public ConfigXMLReader.ControllerConfig getControllerConfig() { - try { - return ConfigXMLReader.getControllerConfig(this.controllerConfigURL); - } catch (WebAppConfigurationException e) { - // FIXME: controller.xml errors should throw an exception. - Debug.logError(e, "Exception thrown while parsing controller.xml file: ", MODULE); + public static RequestHandler getRequestHandler(ServletContext servletContext) { + RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_"); + if (rh == null) { + rh = new RequestHandler(servletContext); + servletContext.setAttribute("_REQUEST_HANDLER_", rh); } - return null; + return rh; } /** @@ -131,7 +121,7 @@ public class RequestHandler { * Otherwise fall back to matching the {@code defaultReq} field in {@code ccfg}. * * @param ccfg The controller containing the current configuration - * @param req The HTTP request to match + * @param req The HTTP request to match * @return a collection of request maps which might be empty */ static Collection<RequestMap> resolveURI(ControllerConfig ccfg, HttpServletRequest req) { @@ -164,7 +154,7 @@ public class RequestHandler { * in that respective order. * * @param method the HTTP method to match - * @param rmaps the collection of request map candidates + * @param rmaps the collection of request map candidates * @return a request map {@code Optional} */ static Optional<RequestMap> resolveMethod(String method, Collection<RequestMap> rmaps) { @@ -188,12 +178,12 @@ public class RequestHandler { * <p>A segmented path can match request maps where the {@code uri} attribute * contains an URI template like in the {@code foo/bar/{baz}} example. * - * @param rMapMap the map associating URIs to a list of request maps corresponding to different HTTP methods - * @param request the HTTP request to match + * @param rMapMap the map associating URIs to a list of request maps corresponding to different HTTP methods + * @param request the HTTP request to match * @return a collection of request maps which might be empty but not {@code null} */ private static Collection<RequestMap> resolveTemplateURI(Map<String, List<RequestMap>> rMapMap, - HttpServletRequest request) { + HttpServletRequest request) { // Retrieve the request path without the leading '/' character. String path = request.getPathInfo().substring(1); MultivaluedHashMap<String, String> vars = new MultivaluedHashMap<>(); @@ -209,8 +199,162 @@ public class RequestHandler { return Collections.emptyList(); } + public static String getRequestUri(String path) { + List<String> pathInfo = StringUtil.split(path, "/"); + if (UtilValidate.isEmpty(pathInfo)) { + Debug.logWarning("Got nothing when splitting URI: " + path, MODULE); + return null; + } + if (pathInfo.get(0).indexOf('?') > -1) { + return pathInfo.get(0).substring(0, pathInfo.get(0).indexOf('?')); + } else { + return pathInfo.get(0); + } + } + + public static String getOverrideViewUri(String path) { + List<String> pathItemList = StringUtil.split(path, "/"); + if (pathItemList == null) { + return null; + } + pathItemList = pathItemList.subList(1, pathItemList.size()); + + String nextPage = null; + for (String pathItem : pathItemList) { + if (pathItem.indexOf('~') != 0) { + if (pathItem.indexOf('?') > -1) { + pathItem = pathItem.substring(0, pathItem.indexOf('?')); + } + nextPage = (nextPage == null ? pathItem : nextPage + "/" + pathItem); + } + } + return nextPage; + } + + private static void callRedirect(String url, HttpServletResponse resp, HttpServletRequest req, String statusCodeString) throws RequestHandlerException { + if (Debug.infoOn()) { + Debug.logInfo("Sending redirect to: [" + url + "]. " + showSessionId(req), MODULE); + } + // set the attributes in the session so we can access it. + Enumeration<String> attributeNameEnum = UtilGenerics.cast(req.getAttributeNames()); + Map<String, Object> reqAttrMap = new HashMap<>(); + Integer statusCode; + try { + statusCode = Integer.valueOf(statusCodeString); + } catch (NumberFormatException e) { + statusCode = 303; + } + while (attributeNameEnum.hasMoreElements()) { + String name = attributeNameEnum.nextElement(); + Object obj = req.getAttribute(name); + if (obj instanceof Serializable) { + if (obj instanceof Map) { + // See OFBIZ-750 and OFBIZ-11123 for cases where a value in an inner Map is not serializable + UtilMisc.makeMapSerializable(UtilGenerics.cast(obj)); + } + reqAttrMap.put(name, obj); + } + } + if (reqAttrMap.size() > 0) { + byte[] reqAttrMapBytes = UtilObject.getBytes(reqAttrMap); + if (reqAttrMapBytes != null) { + req.getSession().setAttribute("_REQ_ATTR_MAP_", StringUtil.toHexString(reqAttrMapBytes)); + } + } + + // send the redirect + try { + resp.setStatus(statusCode); + resp.setHeader("Location", url); + resp.setHeader("Connection", "close"); + } catch (IllegalStateException ise) { + throw new RequestHandlerException(ise.getMessage(), ise); + } + } + + private static void addNameValuePairToQueryString(StringBuilder queryString, String name, String value) { + if (UtilValidate.isNotEmpty(value)) { + if (queryString.length() > 1) { + queryString.append("&"); + } + String encodedName = UtilCodec.getEncoder("url").encode(name); + if (encodedName != null) { + queryString.append(encodedName); + queryString.append("="); + queryString.append(UtilCodec.getEncoder("url").encode(value)); + } + } + } + + public static String makeUrl(HttpServletRequest request, HttpServletResponse response, String url) { + return makeUrl(request, response, url, false, false, false); + } + + public static String makeUrl(HttpServletRequest request, HttpServletResponse response, String url, boolean fullPath, + boolean secure, boolean encode) { + RequestHandler rh = from(request); + return rh.makeLink(request, response, url, fullPath, secure, encode); + } + + private static String showSessionId(HttpServletRequest request) { + Delegator delegator = (Delegator) request.getAttribute("delegator"); + boolean showSessionIdInLog = EntityUtilProperties.propertyValueEqualsIgnoreCase("requestHandler", "show-sessionId-in-log", "Y", delegator); + if (showSessionIdInLog) { + return " sessionId=" + UtilHttp.getSessionId(request); + } + return " Hidden sessionId by default."; + } + + /** + * Checks that the request contains some valid certificates. + * + * @param request the request to verify + * @param validator the predicate applied the certificates found + * @return true if the request contains some valid certificates, otherwise false. + */ + static boolean checkCertificates(HttpServletRequest request, Predicate<X509Certificate[]> validator) { + return Stream.of("javax.servlet.request.X509Certificate", // 2.2 spec + "javax.net.ssl.peer_certificates") // 2.1 spec + .map(request::getAttribute) + .filter(Objects::nonNull) + .map(X509Certificate[].class::cast) + .peek(certs -> { + if (Debug.infoOn()) { + for (X509Certificate cert : certs) { + Debug.logInfo(cert.getSubjectX500Principal().getName(), MODULE); + } + } + }) + .map(validator::test) + .findFirst().orElseGet(() -> { + Debug.logWarning("Received no client certificates from browser", MODULE); + return false; + }); + } + + /** + * Retrieves the request handler which is stored inside an HTTP request. + * + * @param request the HTTP request containing the request handler + * @return a request handler or {@code null} when absent + * @throws NullPointerException when {@code request} or the servlet context is {@code null}. + */ + public static RequestHandler from(HttpServletRequest request) { + return UtilGenerics.cast(request.getServletContext().getAttribute("_REQUEST_HANDLER_")); + } + + public ConfigXMLReader.ControllerConfig getControllerConfig() { + try { + return ConfigXMLReader.getControllerConfig(this.controllerConfigURL); + } catch (WebAppConfigurationException e) { + // FIXME: controller.xml errors should throw an exception. + Debug.logError(e, "Exception thrown while parsing controller.xml file: ", MODULE); + } + return null; + } + public void doRequest(HttpServletRequest request, HttpServletResponse response, String chain, - GenericValue userLogin, Delegator delegator) throws RequestHandlerException, RequestHandlerExceptionAllowExternalRequests { + GenericValue userLogin, Delegator delegator) throws RequestHandlerException, RequestHandlerExceptionAllowExternalRequests { if (!hostHeadersAllowed.contains(request.getServerName())) { Debug.logError("Domain " + request.getServerName() + " not accepted to prevent host header injection." @@ -256,10 +400,13 @@ public class RequestHandler { if (rmaps.isEmpty()) { if (throwRequestHandlerExceptionOnMissingLocalRequest) { if (path.contains("/checkLogin/")) { - // Nested requests related with checkLogin uselessly clutter the log. There is nothing to worry about, better remove this wrong error message. + // Nested requests related with checkLogin uselessly clutter the log. There is nothing to worry about, better remove this wrong + // error message. return; } else if (path.contains("/images/") || path.contains("d.png")) { - if (Debug.warningOn()) Debug.logWarning("You should check if this request is really a problem or a false alarm: " + request.getRequestURL(), MODULE); + if (Debug.warningOn()) { + Debug.logWarning("You should check if this request is really a problem or a false alarm: " + request.getRequestURL(), MODULE); + } throw new RequestHandlerException(requestMissingErrorMessage); } else { throw new RequestHandlerException(requestMissingErrorMessage); @@ -317,7 +464,8 @@ public class RequestHandler { // If the request cannot be called, or is not defined, check and see if there is a default-request we can process if (!requestMap.securityDirectRequest) { if (ccfg.getDefaultRequest() == null || !ccfg.getRequestMapMap().get(ccfg.getDefaultRequest()).securityDirectRequest) { - // use the same message as if it was missing for security reasons, ie so can't tell if it is missing or direct request is not allowed + // use the same message as if it was missing for security reasons, ie so can't tell if it is missing or direct request is not + // allowed throw new RequestHandlerException(requestMissingErrorMessage); } else { requestMap = ccfg.getRequestMapMap().get(ccfg.getDefaultRequest()); @@ -326,14 +474,15 @@ public class RequestHandler { // Check if we SHOULD be secure and are not. boolean forwardedHTTPS = "HTTPS".equalsIgnoreCase(request.getHeader("X-Forwarded-Proto")); if (!request.isSecure() && !forwardedHTTPS && requestMap.securityHttps) { - // If the request method was POST then return an error to avoid problems with CSRF where the request - // may have come from another machine/program and had the same session ID but was not encrypted as it + // If the request method was POST then return an error to avoid problems with CSRF where the request + // may have come from another machine/program and had the same session ID but was not encrypted as it // should have been (we used to let it pass to not lose data since it was too late to protect that data anyway) if ("POST".equalsIgnoreCase(request.getMethod())) { // we can't redirect with the body parameters, and for better security from CSRF, just return an error message Locale locale = UtilHttp.getLocale(request); String errMsg = UtilProperties.getMessage("WebappUiLabels", "requestHandler.InsecureFormPostToSecureRequest", locale); - Debug.logError("Got an insecure (non HTTPS) form POST to a secure (HTTPS) request [" + requestMap.uri + "], returning error", MODULE); + Debug.logError("Got an insecure (non HTTPS) form POST to a secure (HTTPS) request [" + requestMap.uri + "], returning error", + MODULE); // see if HTTPS is enabled, if not then log a warning instead of throwing an exception Boolean enableHttps = null; @@ -351,8 +500,10 @@ public class RequestHandler { } if (Boolean.FALSE.equals(enableHttps)) { - Debug.logWarning("HTTPS is disabled for this site, so we can't tell if this was encrypted or not which means if a form was POSTed " - + "and it was not over HTTPS we don't know, but it would be vulnerable to an CSRF and other attacks: " + errMsg, MODULE); + Debug.logWarning("HTTPS is disabled for this site, so we can't tell if this was encrypted or not which means if a form was " + + "POSTed " + + "and it was not over HTTPS we don't know, but it would be vulnerable to an CSRF and other attacks: " + errMsg, + MODULE); } else { throw new RequestHandlerException(errMsg); } @@ -385,7 +536,7 @@ public class RequestHandler { Debug.logInfo("This is the first request in this visit." + showSessionId(request), MODULE); } session.setAttribute("_FIRST_VISIT_EVENTS_", "complete"); - for (ConfigXMLReader.Event event: ccfg.getFirstVisitEventList().values()) { + for (ConfigXMLReader.Event event : ccfg.getFirstVisitEventList().values()) { try { String returnString = this.runEvent(request, response, event, null, "firstvisit"); if (returnString == null || "none".equalsIgnoreCase(returnString)) { @@ -400,7 +551,7 @@ public class RequestHandler { } // Invoke the pre-processor (but NOT in a chain) - for (ConfigXMLReader.Event event: ccfg.getPreprocessorEventList().values()) { + for (ConfigXMLReader.Event event : ccfg.getPreprocessorEventList().values()) { try { String returnString = this.runEvent(request, response, event, null, "preprocessor"); if (returnString == null || "none".equalsIgnoreCase(returnString)) { @@ -453,7 +604,7 @@ public class RequestHandler { // Perform CSRF token check when request not on chain if (chain == null && originalRequestMap.securityCsrfToken) { - CsrfUtil.checkToken(request, path); + CsrfUtil.checkToken(request, path); } // Perform security check. @@ -482,10 +633,12 @@ public class RequestHandler { } } - // after security check but before running the event, see if a post-login redirect has completed and we have data from the pre-login request form to use now + // after security check but before running the event, see if a post-login redirect has completed and we have data from the pre-login + // request form to use now // we know this is the case if the _PREVIOUS_PARAM_MAP_ attribute is there, but the _PREVIOUS_REQUEST_ attribute has already been removed if (request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_FORM_") != null && request.getSession().getAttribute("_PREVIOUS_REQUEST_") == null) { - Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_FORM_"), String.class, Object.class); + Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_FORM_"), + String.class, Object.class); previousParamMap.forEach(request::setAttribute); // to avoid this data being included again, now remove the _PREVIOUS_PARAM_MAP_ attribute @@ -546,7 +699,8 @@ public class RequestHandler { if (eventReturnBasedRequestResponse != null) { //String eventReturnBasedResponse = requestResponse.value; if (Debug.verboseOn()) { - Debug.logVerbose("[Response Qualified]: " + eventReturnBasedRequestResponse.name + ", " + eventReturnBasedRequestResponse.type + ":" + eventReturnBasedRequestResponse.value + showSessionId(request), MODULE); + Debug.logVerbose("[Response Qualified]: " + eventReturnBasedRequestResponse.name + ", " + eventReturnBasedRequestResponse.type + + ":" + eventReturnBasedRequestResponse.value + showSessionId(request), MODULE); } // If error, then display more error messages: @@ -566,8 +720,11 @@ public class RequestHandler { Debug.logWarning("Could not find response in request [" + requestMap.uri + "] for event return [" + eventReturn + "]", MODULE); } - // Set the next view (don't use event return if success, default to nextView (which is set to eventReturn later if null); also even if success if it is a type "none" response ignore the nextView, ie use the eventReturn) - if (eventReturnBasedRequestResponse != null && (!"success".equals(eventReturnBasedRequestResponse.name) || "none".equals(eventReturnBasedRequestResponse.type))) nextRequestResponse = eventReturnBasedRequestResponse; + // Set the next view (don't use event return if success, default to nextView (which is set to eventReturn later if null); also even if + // success if it is a type "none" response ignore the nextView, ie use the eventReturn) + if (eventReturnBasedRequestResponse != null && (!"success".equals(eventReturnBasedRequestResponse.name) || "none".equals(eventReturnBasedRequestResponse.type))) { + nextRequestResponse = eventReturnBasedRequestResponse; + } // get the previous request info String previousRequest = (String) request.getSession().getAttribute("_PREVIOUS_REQUEST_"); @@ -580,13 +737,13 @@ public class RequestHandler { byte[] reqAttrMapBytes = StringUtil.fromHexString(preReqAttStr); Map<String, Object> preRequestMap = checkMap(UtilObject.getObject(reqAttrMapBytes), String.class, Object.class); if (UtilValidate.isNotEmpty(preRequestMap)) { - for (Map.Entry<String, Object> entry: preRequestMap.entrySet()) { + for (Map.Entry<String, Object> entry : preRequestMap.entrySet()) { String key = entry.getKey(); if ("_ERROR_MESSAGE_LIST_".equals(key) || "_ERROR_MESSAGE_MAP_".equals(key) || "_ERROR_MESSAGE_".equals(key) || "_WARNING_MESSAGE_LIST_".equals(key) || "_WARNING_MESSAGE_".equals(key) || "_EVENT_MESSAGE_LIST_".equals(key) || "_EVENT_MESSAGE_".equals(key)) { request.setAttribute(key, entry.getValue()); - } + } } } } @@ -598,16 +755,20 @@ public class RequestHandler { // if previous request exists, and a login just succeeded, do that now. if (previousRequest != null && loginPass != null && "TRUE".equalsIgnoreCase(loginPass)) { request.getSession().removeAttribute("_PREVIOUS_REQUEST_"); - // special case to avoid login/logout looping: if request was "logout" before the login, change to null for default success view; do the same for "login" to avoid going back to the same page + // special case to avoid login/logout looping: if request was "logout" before the login, change to null for default success view; do + // the same for "login" to avoid going back to the same page if ("logout".equals(previousRequest) || "/logout".equals(previousRequest) || "login".equals(previousRequest) || "/login".equals(previousRequest) || "checkLogin".equals(previousRequest) || "/checkLogin".equals(previousRequest) || "/checkLogin/login".equals(previousRequest)) { - Debug.logWarning("Found special _PREVIOUS_REQUEST_ of [" + previousRequest + "], setting to null to avoid problems, not running request again", MODULE); + Debug.logWarning("Found special _PREVIOUS_REQUEST_ of [" + previousRequest + "], setting to null to avoid problems, not running " + + "request again", MODULE); } else { if (Debug.infoOn()) { Debug.logInfo("[Doing Previous Request]: " + previousRequest + showSessionId(request), MODULE); } - // note that the previous form parameters are not setup (only the URL ones here), they will be found in the session later and handled when the old request redirect comes back - Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_URL_"), String.class, Object.class); + // note that the previous form parameters are not setup (only the URL ones here), they will be found in the session later and + // handled when the old request redirect comes back + Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_URL_"), + String.class, Object.class); String queryString = UtilHttp.urlEncodeArgs(previousParamMap, false); String redirectTarget = previousRequest; if (UtilValidate.isNotEmpty(queryString)) { @@ -646,7 +807,8 @@ public class RequestHandler { // ========== Handle the responses - chains/views ========== - // if the request has the save-last-view attribute set, save it now before the view can be rendered or other chain done so that the _LAST* session attributes will represent the previous request + // if the request has the save-last-view attribute set, save it now before the view can be rendered or other chain done so that the _LAST* + // session attributes will represent the previous request if (nextRequestResponse.saveLastView) { // Debug.logInfo("======save last view: " + session.getAttribute("_LAST_VIEW_NAME_")); String lastViewName = (String) session.getAttribute("_LAST_VIEW_NAME_"); @@ -657,8 +819,12 @@ public class RequestHandler { } } String saveName = null; - if (nextRequestResponse.saveCurrentView) { saveName = "SAVED"; } - if (nextRequestResponse.saveHomeView) { saveName = "HOME"; } + if (nextRequestResponse.saveCurrentView) { + saveName = "SAVED"; + } + if (nextRequestResponse.saveHomeView) { + saveName = "HOME"; + } if ("request".equals(nextRequestResponse.type)) { // chained request @@ -668,7 +834,7 @@ public class RequestHandler { // ======== handle views ======== // first invoke the post-processor events. - for (ConfigXMLReader.Event event: ccfg.getPostprocessorEventList().values()) { + for (ConfigXMLReader.Event event : ccfg.getPostprocessorEventList().values()) { try { String returnString = this.runEvent(request, response, event, requestMap, "postprocessor"); if (returnString != null && !"success".equalsIgnoreCase(returnString)) { @@ -716,7 +882,8 @@ public class RequestHandler { callRedirect(link, response, request, redirectSC); } else if ("request-redirect-noparam".equals(nextRequestResponse.type)) { if (Debug.verboseOn()) { - Debug.logVerbose("[RequestHandler.doRequest]: Response is a Request redirect with no parameters." + showSessionId(request), MODULE); + Debug.logVerbose("[RequestHandler.doRequest]: Response is a Request redirect with no parameters." + showSessionId(request), + MODULE); } String link = makeLink(request, response, nextRequestResponse.value); @@ -731,7 +898,8 @@ public class RequestHandler { } // check for an override view, only used if "success" = eventReturn - String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value; + String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) + ? overrideViewUri : nextRequestResponse.value; renderView(viewName, requestMap.securityExternalView, request, response, saveName); } else if ("view-last".equals(nextRequestResponse.type)) { if (Debug.verboseOn()) { @@ -739,7 +907,8 @@ public class RequestHandler { } // check for an override view, only used if "success" = eventReturn - String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value; + String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) + ? overrideViewUri : nextRequestResponse.value; // as a further override, look for the _SAVED and then _HOME and then _LAST session attributes Map<String, Object> urlParams = null; @@ -759,7 +928,7 @@ public class RequestHandler { viewName = nextRequestResponse.value; } if (urlParams != null) { - for (Map.Entry<String, Object> urlParamEntry: urlParams.entrySet()) { + for (Map.Entry<String, Object> urlParamEntry : urlParams.entrySet()) { String key = urlParamEntry.getKey(); // Don't overwrite messages coming from the current event if (!("_EVENT_MESSAGE_".equals(key) || "_ERROR_MESSAGE_".equals(key) @@ -775,8 +944,8 @@ public class RequestHandler { } // check for an override view, only used if "success" = eventReturn - String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? - overrideViewUri : nextRequestResponse.value; + String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) + ? overrideViewUri : nextRequestResponse.value; // as a further override, look for the _SAVED and then _HOME and then _LAST session attributes if (session.getAttribute("_SAVED_VIEW_NAME_") != null) { @@ -795,7 +964,8 @@ public class RequestHandler { } // check for an override view, only used if "success" = eventReturn - String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value; + String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) + ? overrideViewUri : nextRequestResponse.value; // as a further override, look for the _HOME session attributes Map<String, Object> urlParams = null; @@ -804,7 +974,7 @@ public class RequestHandler { urlParams = UtilGenerics.cast(session.getAttribute("_HOME_VIEW_PARAMS_")); } if (urlParams != null) { - for (Map.Entry<String, Object> urlParamEntry: urlParams.entrySet()) { + for (Map.Entry<String, Object> urlParamEntry : urlParams.entrySet()) { request.setAttribute(urlParamEntry.getKey(), urlParamEntry.getValue()); } } @@ -821,17 +991,24 @@ public class RequestHandler { } } - /** Find the event handler and invoke an event. */ + /** + * Find the event handler and invoke an event. + */ public String runEvent(HttpServletRequest request, HttpServletResponse response, - ConfigXMLReader.Event event, ConfigXMLReader.RequestMap requestMap, String trigger) throws EventHandlerException { + ConfigXMLReader.Event event, ConfigXMLReader.RequestMap requestMap, String trigger) throws EventHandlerException { EventHandler eventHandler = eventFactory.getEventHandler(event.type); String eventReturn = eventHandler.invoke(event, requestMap, request, response); - if (Debug.verboseOn() || (Debug.infoOn() && "request".equals(trigger))) Debug.logInfo("Ran Event [" + event.type + ":" + event.path + "#" + event.invoke + "] from [" + trigger + "], result is [" + eventReturn + "]", MODULE); + if (Debug.verboseOn() || (Debug.infoOn() && "request".equals(trigger))) { + Debug.logInfo("Ran Event [" + event.type + ":" + event.path + "#" + event.invoke + "] from [" + trigger + "], result is [" + eventReturn + "]", MODULE); + } return eventReturn; } - /** Returns the default error page for this request. - * @throws MalformedURLException */ + /** + * Returns the default error page for this request. + * + * @throws MalformedURLException + */ public String getDefaultErrorPage(HttpServletRequest request) throws MalformedURLException { URL errorPage = null; try { @@ -846,94 +1023,28 @@ public class RequestHandler { return errorPage.toString(); } - /** Returns the default status-code for this request. */ + /** + * Returns the default status-code for this request. + */ public String getStatusCode(HttpServletRequest request) { String statusCode = getControllerConfig().getStatusCode(); return UtilValidate.isNotEmpty(statusCode) ? statusCode : null; } - /** Returns the ViewFactory Object. */ + /** + * Returns the ViewFactory Object. + */ public ViewFactory getViewFactory() { return viewFactory; } - /** Returns the EventFactory Object. */ + /** + * Returns the EventFactory Object. + */ public EventFactory getEventFactory() { return eventFactory; } - public static String getRequestUri(String path) { - List<String> pathInfo = StringUtil.split(path, "/"); - if (UtilValidate.isEmpty(pathInfo)) { - Debug.logWarning("Got nothing when splitting URI: " + path, MODULE); - return null; - } - if (pathInfo.get(0).indexOf('?') > -1) { - return pathInfo.get(0).substring(0, pathInfo.get(0).indexOf('?')); - } else { - return pathInfo.get(0); - } - } - - public static String getOverrideViewUri(String path) { - List<String> pathItemList = StringUtil.split(path, "/"); - if (pathItemList == null) { - return null; - } - pathItemList = pathItemList.subList(1, pathItemList.size()); - - String nextPage = null; - for (String pathItem: pathItemList) { - if (pathItem.indexOf('~') != 0) { - if (pathItem.indexOf('?') > -1) { - pathItem = pathItem.substring(0, pathItem.indexOf('?')); - } - nextPage = (nextPage == null ? pathItem : nextPage + "/" + pathItem); - } - } - return nextPage; - } - - private static void callRedirect(String url, HttpServletResponse resp, HttpServletRequest req, String statusCodeString) throws RequestHandlerException { - if (Debug.infoOn()) { - Debug.logInfo("Sending redirect to: [" + url + "]. " + showSessionId(req), MODULE); - } - // set the attributes in the session so we can access it. - Enumeration<String> attributeNameEnum = UtilGenerics.cast(req.getAttributeNames()); - Map<String, Object> reqAttrMap = new HashMap<>(); - Integer statusCode; - try { - statusCode = Integer.valueOf(statusCodeString); - } catch (NumberFormatException e) { - statusCode = 303; - } - while (attributeNameEnum.hasMoreElements()) { - String name = attributeNameEnum.nextElement(); - Object obj = req.getAttribute(name); - if (obj instanceof Serializable) { - if (obj instanceof Map) { - // See OFBIZ-750 and OFBIZ-11123 for cases where a value in an inner Map is not serializable - UtilMisc.makeMapSerializable(UtilGenerics.cast(obj)); - } - reqAttrMap.put(name, obj); - } - } - if (reqAttrMap.size() > 0) { - byte[] reqAttrMapBytes = UtilObject.getBytes(reqAttrMap); - if (reqAttrMapBytes != null) { - req.getSession().setAttribute("_REQ_ATTR_MAP_", StringUtil.toHexString(reqAttrMapBytes)); - } - } - - // send the redirect - try { - resp.setStatus(statusCode); - resp.setHeader("Location", url); - resp.setHeader("Connection", "close"); - } catch (IllegalStateException ise) { - throw new RequestHandlerException(ise.getMessage(), ise); - } - } private void renderView(String view, boolean allowExtView, HttpServletRequest req, HttpServletResponse resp, String saveName) throws RequestHandlerException { GenericValue userLogin = (GenericValue) req.getSession().getAttribute("userLogin"); // workaround if we are in the root webapp @@ -972,7 +1083,9 @@ public class RequestHandler { // before mapping the view, set a request attribute so we know where we are req.setAttribute("_CURRENT_VIEW_", view); - // save the view in the session for the last view, plus the parameters Map (can use all parameters as they will never go into a URL, will only stay in the session and extra data will be ignored as we won't go to the original request just the view); note that this is saved after the request/view processing has finished so when those run they will get the value from the previous request + // save the view in the session for the last view, plus the parameters Map (can use all parameters as they will never go into a URL, will + // only stay in the session and extra data will be ignored as we won't go to the original request just the view); note that this is saved + // after the request/view processing has finished so when those run they will get the value from the previous request Map<String, Object> paramMap = UtilHttp.getParameterMap(req); // add in the attributes as well so everything needed for the rendering context will be in place if/when we get back to this view paramMap.putAll(UtilHttp.getAttributeMap(req)); @@ -1072,7 +1185,8 @@ public class RequestHandler { try { resp.flushBuffer(); } catch (java.io.IOException e) { - /* If any request gets aborted before completing, i.e if a user requests a page and cancels that request before the page is rendered and returned + /* If any request gets aborted before completing, i.e if a user requests a page and cancels that request before the page is rendered + and returned or if request is an ajax request and user calls abort() method for on ajax request then its showing broken pipe exception on console, skip throwing of RequestHandlerException. JIRA Ticket - OFBIZ-254 */ @@ -1085,14 +1199,15 @@ public class RequestHandler { if (this.trackStats(req) && vname != null) { ServerHitBin.countView(cname + "." + vname, req, viewStartTime, - System.currentTimeMillis() - viewStartTime, userLogin); + System.currentTimeMillis() - viewStartTime, userLogin); } } /** - * Creates a query string based on the redirect parameters for a request response, if specified, or for all request parameters if no redirect parameters are specified. + * Creates a query string based on the redirect parameters for a request response, if specified, or for all request parameters if no redirect + * parameters are specified. * - * @param request the Http request + * @param request the Http request * @param requestResponse the RequestResponse Object * @return return the query string */ @@ -1108,7 +1223,7 @@ public class RequestHandler { } else { StringBuilder queryString = new StringBuilder(); queryString.append("?"); - for (Map.Entry<String, String> entry: requestResponse.redirectParameterMap.entrySet()) { + for (Map.Entry<String, String> entry : requestResponse.redirectParameterMap.entrySet()) { String name = entry.getKey(); String from = entry.getValue(); @@ -1120,7 +1235,7 @@ public class RequestHandler { addNameValuePairToQueryString(queryString, name, (String) value); } - for (Map.Entry<String, String> entry: requestResponse.redirectParameterValueMap.entrySet()) { + for (Map.Entry<String, String> entry : requestResponse.redirectParameterValueMap.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); @@ -1131,21 +1246,8 @@ public class RequestHandler { } } - private static void addNameValuePairToQueryString(StringBuilder queryString, String name, String value) { - if (UtilValidate.isNotEmpty(value)) { - if (queryString.length() > 1) { - queryString.append("&"); - } - String encodedName = UtilCodec.getEncoder("url").encode(name); - if (encodedName != null) { - queryString.append(encodedName); - queryString.append("="); - queryString.append(UtilCodec.getEncoder("url").encode(value)); - } - } - } - - public String makeLinkWithQueryString(HttpServletRequest request, HttpServletResponse response, String url, ConfigXMLReader.RequestResponse requestResponse) { + public String makeLinkWithQueryString(HttpServletRequest request, HttpServletResponse response, String url, + ConfigXMLReader.RequestResponse requestResponse) { String initialLink = this.makeLink(request, response, url); String queryString = this.makeQueryString(request, requestResponse); return initialLink + queryString; @@ -1159,7 +1261,8 @@ public class RequestHandler { return makeLink(request, response, url, fullPath, secure, encode, ""); } - public String makeLink(HttpServletRequest request, HttpServletResponse response, String url, boolean fullPath, boolean secure, boolean encode, String targetControlPath) { + public String makeLink(HttpServletRequest request, HttpServletResponse response, String url, boolean fullPath, boolean secure, boolean encode, + String targetControlPath) { WebSiteProperties webSiteProps = null; try { webSiteProps = WebSiteProperties.from(request); @@ -1251,9 +1354,9 @@ public class RequestHandler { if (addExternalKeyParam) { if (url.contains("?")) { - url += "&externalLoginKey=" + ExternalLoginKeysManager.getExternalLoginKey(request);; + url += "&externalLoginKey=" + ExternalLoginKeysManager.getExternalLoginKey(request); } else { - url += "?externalLoginKey=" + ExternalLoginKeysManager.getExternalLoginKey(request);; + url += "?externalLoginKey=" + ExternalLoginKeysManager.getExternalLoginKey(request); } } @@ -1272,25 +1375,10 @@ public class RequestHandler { return encodedUrl; } - public static String makeUrl(HttpServletRequest request, HttpServletResponse response, String url) { - return makeUrl(request, response, url, false, false, false); - } - - public static String makeUrl(HttpServletRequest request, HttpServletResponse response, String url, boolean fullPath, - boolean secure, boolean encode) { - RequestHandler rh = from(request); - return rh.makeLink(request, response, url, fullPath, secure, encode); - } - - @FunctionalInterface - private interface EventCollectionProducer { - Collection<ConfigXMLReader.Event> get() throws WebAppConfigurationException; - } - private void runEvents(HttpServletRequest req, HttpServletResponse res, - EventCollectionProducer prod, String trigger) { + EventCollectionProducer prod, String trigger) { try { - for (ConfigXMLReader.Event event: prod.get()) { + for (ConfigXMLReader.Event event : prod.get()) { String ret = runEvent(req, res, event, null, trigger); if (ret != null && !"success".equalsIgnoreCase(ret)) { throw new EventHandlerException("Pre-Processor event did not return 'success'."); @@ -1306,7 +1394,7 @@ public class RequestHandler { /** * Run all the "after-login" Web events defined in the controller configuration. * - * @param req the request to run the events with + * @param req the request to run the events with * @param resp the response to run the events with */ public void runAfterLoginEvents(HttpServletRequest req, HttpServletResponse resp) { @@ -1317,7 +1405,7 @@ public class RequestHandler { /** * Run all the "before-logout" Web events defined in the controller configuration. * - * @param req the request to run the events with + * @param req the request to run the events with * @param resp the response to run the events with */ public void runBeforeLogoutEvents(HttpServletRequest req, HttpServletResponse resp) { @@ -1328,9 +1416,9 @@ public class RequestHandler { /** * Checks if a request must be tracked according a global toggle and a request map predicate. * - * @param request the request that can potentially be tracked - * @param globalToggle the global configuration toggle - * @param pred the predicate checking if each individual request map must be tracked or not. + * @param request the request that can potentially be tracked + * @param globalToggle the global configuration toggle + * @param pred the predicate checking if each individual request map must be tracked or not. * @return {@code true} when the request must be tracked. * @throws NullPointerException when either {@code request} or {@code pred} is {@code null}. */ @@ -1343,7 +1431,7 @@ public class RequestHandler { // is used outside `doRequest`. String uriString = RequestHandler.getRequestUri(request.getPathInfo()); if (uriString == null) { - uriString= ""; + uriString = ""; } Map<String, RequestMap> rmaps = getControllerConfig().getRequestMapMap(); RequestMap requestMap = rmaps.get(uriString); @@ -1358,8 +1446,7 @@ public class RequestHandler { /** * Checks if server hits must be tracked for a given request. - * - * @param request the HTTP request that can potentially be tracked + * @param request the HTTP request that can potentially be tracked * @return {@code true} when the request must be tracked. */ public boolean trackStats(HttpServletRequest request) { @@ -1368,58 +1455,15 @@ public class RequestHandler { /** * Checks if visits must be tracked for a given request. - * - * @param request the HTTP request that can potentially be tracked + * @param request the HTTP request that can potentially be tracked * @return {@code true} when the request must be tracked. */ public boolean trackVisit(HttpServletRequest request) { return track(request, trackVisit, rmap -> rmap.trackVisit); } - private static String showSessionId(HttpServletRequest request) { - Delegator delegator = (Delegator) request.getAttribute("delegator"); - boolean showSessionIdInLog = EntityUtilProperties.propertyValueEqualsIgnoreCase("requestHandler", "show-sessionId-in-log", "Y", delegator); - if (showSessionIdInLog) { - return " sessionId=" + UtilHttp.getSessionId(request); - } - return " Hidden sessionId by default."; - } - - /** - * Checks that the request contains some valid certificates. - * - * @param request the request to verify - * @param validator the predicate applied the certificates found - * @return true if the request contains some valid certificates, otherwise false. - */ - static boolean checkCertificates(HttpServletRequest request, Predicate<X509Certificate[]> validator) { - return Stream.of("javax.servlet.request.X509Certificate", // 2.2 spec - "javax.net.ssl.peer_certificates") // 2.1 spec - .map(request::getAttribute) - .filter(Objects::nonNull) - .map(X509Certificate[].class::cast) - .peek(certs -> { - if (Debug.infoOn()) { - for (X509Certificate cert : certs) { - Debug.logInfo(cert.getSubjectX500Principal().getName(), MODULE); - } - } - }) - .map(validator::test) - .findFirst().orElseGet(() -> { - Debug.logWarning("Received no client certificates from browser", MODULE); - return false; - }); - } - - /** - * Retrieves the request handler which is stored inside an HTTP request. - * - * @param request the HTTP request containing the request handler - * @return a request handler or {@code null} when absent - * @throws NullPointerException when {@code request} or the servlet context is {@code null}. - */ - public static RequestHandler from(HttpServletRequest request) { - return UtilGenerics.cast(request.getServletContext().getAttribute("_REQUEST_HANDLER_")); + @FunctionalInterface + private interface EventCollectionProducer { + Collection<ConfigXMLReader.Event> get() throws WebAppConfigurationException; } } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/CoreEvents.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/CoreEvents.java index 2b286da..8795689 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/CoreEvents.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/CoreEvents.java @@ -22,7 +22,6 @@ import static org.apache.ofbiz.base.util.UtilGenerics.checkMap; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Timestamp; import java.util.Collection; @@ -61,7 +60,7 @@ import org.apache.ofbiz.webapp.control.RequestHandler; public class CoreEvents { private static final String MODULE = CoreEvents.class.getName(); - public static final String err_resource = "WebappUiLabels"; + private static final String ERR_RESOURCE = "WebappUiLabels"; /** * Return success event. Used as a place holder for events. @@ -150,7 +149,7 @@ public class CoreEvents { // make sure we passed a service if (serviceName == null) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.must_specify_service", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -161,12 +160,12 @@ public class CoreEvents { modelService = dispatcher.getDispatchContext().getModelService(serviceName); } catch (GenericServiceException e) { Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", MODULE); - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.error_modelservice_for_srv_name", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]: " + e.toString()); return "error"; } if (modelService == null) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_name_not_find", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]"); return "error"; } @@ -226,7 +225,7 @@ public class CoreEvents { } if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.not_authorized_to_call", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -240,12 +239,12 @@ public class CoreEvents { try { startTime = Long.parseLong(serviceTime); } catch (NumberFormatException nfe) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.invalid_format_time", locale); errorBuf.append(errMsg); } } if (startTime < (new Date()).getTime()) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_time_already_passed", locale); errorBuf.append(errMsg); } } @@ -257,12 +256,12 @@ public class CoreEvents { try { endTime = Long.parseLong(serviceEndTime); } catch (NumberFormatException nfe) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.invalid_format_time", locale); errorBuf.append(errMsg); } } if (endTime < (new Date()).getTime()) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_time_already_passed", locale); errorBuf.append(errMsg); } } @@ -270,7 +269,7 @@ public class CoreEvents { try { interval = Integer.parseInt(serviceIntr); } catch (NumberFormatException nfe) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_interval", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.invalid_format_interval", locale); errorBuf.append(errMsg); } } @@ -278,7 +277,7 @@ public class CoreEvents { try { count = Integer.parseInt(serviceCnt); } catch (NumberFormatException nfe) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_count", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.invalid_format_count", locale); errorBuf.append(errMsg); } } @@ -287,14 +286,15 @@ public class CoreEvents { try { parsedValue = Integer.parseInt(serviceFreq); - if (parsedValue > 0 && parsedValue < 8) + if (parsedValue > 0 && parsedValue < 8) { frequency = parsedValue; + } } catch (NumberFormatException nfe) { parsedValue = 0; } if (parsedValue == 0) { if (!freqMap.containsKey(serviceFreq.toUpperCase())) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_frequency", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.invalid_format_frequency", locale); errorBuf.append(errMsg); } else { frequency = freqMap.get(serviceFreq.toUpperCase()); @@ -327,20 +327,20 @@ public class CoreEvents { Map<String, Object> syncServiceResult = null; // schedule service try { - if (null!=request.getParameter("_RUN_SYNC_") && "Y".equals(request.getParameter("_RUN_SYNC_"))) { + if (null != request.getParameter("_RUN_SYNC_") && "Y".equals(request.getParameter("_RUN_SYNC_"))) { syncServiceResult = dispatcher.runSync(serviceName, serviceContext); } else { dispatcher.schedule(jobName, poolName, serviceName, serviceContext, startTime, frequency, interval, count, endTime, maxRetry); } } catch (GenericServiceException e) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_dispatcher_exception", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_dispatcher_exception", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + e.getMessage()); return "error"; } - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_scheduled", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_scheduled", locale); request.setAttribute("_EVENT_MESSAGE_", errMsg); - if (null!=syncServiceResult) { + if (null != syncServiceResult) { request.getSession().setAttribute("_RUN_SYNC_RESULT_", syncServiceResult); return "sync_success"; } @@ -352,13 +352,14 @@ public class CoreEvents { Locale locale = UtilHttp.getLocale(request); Map<String, Object> syncServiceResult = checkMap(session.getAttribute("_RUN_SYNC_RESULT_"), String.class, Object.class); if (null == syncServiceResult) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.no_fields_in_session", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.no_fields_in_session", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } - if (null!=request.getParameter("_CLEAR_PREVIOUS_PARAMS_") && "on".equalsIgnoreCase(request.getParameter("_CLEAR_PREVIOUS_PARAMS_"))) + if (null != request.getParameter("_CLEAR_PREVIOUS_PARAMS_") && "on".equalsIgnoreCase(request.getParameter("_CLEAR_PREVIOUS_PARAMS_"))) { session.removeAttribute("_SAVED_SYNC_RESULT_"); + } Map<String, String[]> serviceFieldsToSave = checkMap(request.getParameterMap(), String.class, String[].class); Map<String, Object> savedFields = new HashMap<>(); @@ -367,11 +368,11 @@ public class CoreEvents { String key = entry.getKey(); if (entry.getValue() != null && "on".equalsIgnoreCase(request.getParameter(key)) && !"_CLEAR_PREVIOUS_PARAMS_".equals(key)) { String[] servicePath = key.split("\\|\\|"); - String partialKey = servicePath[servicePath.length-1]; + String partialKey = servicePath[servicePath.length - 1]; savedFields.put(partialKey, getObjectFromServicePath(key, syncServiceResult)); } } - if (null!=session.getAttribute("_SAVED_SYNC_RESULT_")) { + if (null != session.getAttribute("_SAVED_SYNC_RESULT_")) { Map<String, Object> savedSyncResult = checkMap(session.getAttribute("_SAVED_SYNC_RESULT_"), String.class, Object.class); savedSyncResult.putAll(savedFields); savedFields = savedSyncResult; @@ -437,7 +438,7 @@ public class CoreEvents { Locale locale = UtilHttp.getLocale(request); if (UtilValidate.isEmpty(serviceName)) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service_name", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.must_specify_service_name", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -456,18 +457,18 @@ public class CoreEvents { modelService = dispatcher.getDispatchContext().getModelService(serviceName); } catch (GenericServiceException e) { Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", MODULE); - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.error_modelservice_for_srv_name", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]: " + e.toString()); return "error"; } if (modelService == null) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_name_not_find", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]"); return "error"; } if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.not_authorized_to_call", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + "."); return "error"; } @@ -480,7 +481,7 @@ public class CoreEvents { try { return seh.invoke(event, null, request, response); } catch (EventHandlerException e) { - String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_eventhandler_exception", locale); + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "coreEvents.service_eventhandler_exception", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.getMessage()); return "error"; } 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 0d6e215..2877963 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,7 +26,7 @@ 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 final static Map<String, RequestBodyMapHandler> requestBodyMapHandlers = new HashMap<>(); + private static final Map<String, RequestBodyMapHandler> requestBodyMapHandlers = new HashMap<>(); static { requestBodyMapHandlers.put("application/json", new JSONRequestBodyMapHandler()); } diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ServiceMultiEventHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ServiceMultiEventHandler.java index ece3cd0..8fff58f 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ServiceMultiEventHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/ServiceMultiEventHandler.java @@ -135,12 +135,12 @@ public class ServiceMultiEventHandler implements EventHandler { } // check if we are using per row submit - boolean useRowSubmit = request.getParameter("_useRowSubmit") == null ? false : - "Y".equalsIgnoreCase(request.getParameter("_useRowSubmit")); + boolean useRowSubmit = request.getParameter("_useRowSubmit") == null ? false + : "Y".equalsIgnoreCase(request.getParameter("_useRowSubmit")); // check if we are to also look in a global scope (no delimiter) - boolean checkGlobalScope = request.getParameter("_checkGlobalScope") == null ? true : - !"N".equalsIgnoreCase(request.getParameter("_checkGlobalScope")); + boolean checkGlobalScope = request.getParameter("_checkGlobalScope") == null ? true + : !"N".equalsIgnoreCase(request.getParameter("_checkGlobalScope")); // The number of multi form rows is retrieved int rowCount = UtilHttp.getMultiFormRowCount(request); @@ -187,11 +187,11 @@ public class ServiceMultiEventHandler implements EventHandler { String curSuffix = UtilHttp.getMultiRowDelimiter() + i; boolean rowSelected = false; if (UtilValidate.isNotEmpty(request.getAttribute(UtilHttp.getRowSubmitPrefix() + i))) { - rowSelected = request.getAttribute(UtilHttp.getRowSubmitPrefix() + i) == null ? false : - "Y".equalsIgnoreCase((String) request.getAttribute(UtilHttp.getRowSubmitPrefix() + i)); + rowSelected = request.getAttribute(UtilHttp.getRowSubmitPrefix() + i) == null ? false + : "Y".equalsIgnoreCase((String) request.getAttribute(UtilHttp.getRowSubmitPrefix() + i)); } else { - rowSelected = request.getParameter(UtilHttp.getRowSubmitPrefix() + i) == null ? false : - "Y".equalsIgnoreCase(request.getParameter(UtilHttp.getRowSubmitPrefix() + i)); + rowSelected = request.getParameter(UtilHttp.getRowSubmitPrefix() + i) == null ? false + : "Y".equalsIgnoreCase(request.getParameter(UtilHttp.getRowSubmitPrefix() + i)); } // make sure we are to process this row @@ -310,7 +310,7 @@ public class ServiceMultiEventHandler implements EventHandler { result = dispatcher.runSync(serviceName, serviceContext); } catch (ServiceAuthException e) { // not logging since the service engine already did - errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i +"): " + e.getNonNestedMessage()); + errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage()); } catch (ServiceValidationException e) { // not logging since the service engine already did request.setAttribute("serviceValidationException", e); @@ -320,11 +320,11 @@ public class ServiceMultiEventHandler implements EventHandler { errorMessages.add("Service invocation error on row (" + i + "): " + message); } } else { - errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i +"): " + e.getNonNestedMessage()); + errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage()); } } catch (GenericServiceException e) { Debug.logError(e, "Service invocation error", MODULE); - errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i +"): " + e.getNested() + messageSuffixStr); + errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNested() + messageSuffixStr); } if (result == null) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/SimpleEventHandler.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/SimpleEventHandler.java index b927c3e..4d0d706 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/SimpleEventHandler.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/event/SimpleEventHandler.java @@ -41,7 +41,7 @@ public class SimpleEventHandler implements EventHandler { private static final String MODULE = SimpleEventHandler.class.getName(); /** Contains the property file name for translation of error messages. */ - public static final String err_resource = "WebappUiLabels"; + private static final String ERR_RESOURCE = "WebappUiLabels"; @Override public void init(ServletContext context) throws EventHandlerException { @@ -79,7 +79,7 @@ public class SimpleEventHandler implements EventHandler { return eventReturn; } catch (MiniLangException e) { Debug.logError(e, MODULE); - String errMsg = UtilProperties.getMessage(SimpleEventHandler.err_resource, "simpleEventHandler.event_not_completed", (locale != null ? locale : Locale.getDefault())) + ": "; + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "simpleEventHandler.event_not_completed", (locale != null ? locale : Locale.getDefault())) + ": "; request.setAttribute("_ERROR_MESSAGE_", errMsg + e.getMessage()); return "error"; } catch (GenericTransactionException e) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizContentTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizContentTransform.java index 1bcd3fc..7ce4062 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizContentTransform.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizContentTransform.java @@ -41,7 +41,7 @@ import freemarker.template.TemplateTransformModel; */ public class OfbizContentTransform implements TemplateTransformModel { - public final static String MODULE = OfbizContentTransform.class.getName(); + private static final String MODULE = OfbizContentTransform.class.getName(); private static String getArg(Map<String, Object> args, String key) { String result = ""; diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizUrlTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizUrlTransform.java index f94b3cb..92340ff 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizUrlTransform.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/OfbizUrlTransform.java @@ -58,7 +58,7 @@ import freemarker.template.TemplateTransformModel; */ public class OfbizUrlTransform implements TemplateTransformModel { - public final static String MODULE = OfbizUrlTransform.class.getName(); + private static final String MODULE = OfbizUrlTransform.class.getName(); @SuppressWarnings("rawtypes") private static boolean checkBooleanArg(Map args, String key, boolean defaultValue) { diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetContextFieldTransform.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetContextFieldTransform.java index 916a1e0..1293a08 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetContextFieldTransform.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetContextFieldTransform.java @@ -40,12 +40,15 @@ public class SetContextFieldTransform implements TemplateMethodModelEx { @Override public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException { - if (args == null || args.size() != 2) + if (args == null || args.size() != 2) { throw new TemplateModelException("Invalid number of arguements"); - if (!(args.get(0) instanceof TemplateScalarModel)) + } + if (!(args.get(0) instanceof TemplateScalarModel)) { throw new TemplateModelException("First argument not an instance of TemplateScalarModel"); - if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel)) + } + if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel)) { throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel"); + } Environment env = Environment.getCurrentEnvironment(); BeanModel req = (BeanModel) env.getVariable("context"); @@ -53,12 +56,15 @@ public class SetContextFieldTransform implements TemplateMethodModelEx { String name = ((TemplateScalarModel) args.get(0)).getAsString(); Object value = null; - if (args.get(1) instanceof TemplateScalarModel) + if (args.get(1) instanceof TemplateScalarModel) { value = ((TemplateScalarModel) args.get(1)).getAsString(); - if (args.get(1) instanceof TemplateNumberModel) + } + if (args.get(1) instanceof TemplateNumberModel) { value = ((TemplateNumberModel) args.get(1)).getAsNumber(); - if (args.get(1) instanceof BeanModel) + } + if (args.get(1) instanceof BeanModel) { value = ((BeanModel) args.get(1)).getWrappedObject(); + } context.put(name, value); return new SimpleScalar(""); diff --git a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetRequestAttributeMethod.java b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetRequestAttributeMethod.java index 64830aa..9d10444 100644 --- a/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetRequestAttributeMethod.java +++ b/framework/webapp/src/main/java/org/apache/ofbiz/webapp/ftl/SetRequestAttributeMethod.java @@ -39,12 +39,15 @@ public class SetRequestAttributeMethod implements TemplateMethodModelEx { @Override public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException { - if (args == null || args.size() != 2) + if (args == null || args.size() != 2) { throw new TemplateModelException("Invalid number of arguements"); - if (!(args.get(0) instanceof TemplateScalarModel)) + } + if (!(args.get(0) instanceof TemplateScalarModel)) { throw new TemplateModelException("First argument not an instance of TemplateScalarModel"); - if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel)) + } + if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel)) { throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel"); + } Environment env = Environment.getCurrentEnvironment(); BeanModel req = (BeanModel) env.getVariable("request"); @@ -52,12 +55,15 @@ public class SetRequestAttributeMethod implements TemplateMethodModelEx { String name = ((TemplateScalarModel) args.get(0)).getAsString(); Object value = null; - if (args.get(1) instanceof TemplateScalarModel) + if (args.get(1) instanceof TemplateScalarModel) { value = ((TemplateScalarModel) args.get(1)).getAsString(); - if (args.get(1) instanceof TemplateNumberModel) + } + if (args.get(1) instanceof TemplateNumberModel) { value = ((TemplateNumberModel) args.get(1)).getAsNumber(); - if (args.get(1) instanceof BeanModel) + } + if (args.get(1) instanceof BeanModel) { value = ((BeanModel) args.get(1)).getWrappedObject(); + } request.setAttribute(name, value); return new SimpleScalar(""); diff --git a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/GenericWebEvent.java b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/GenericWebEvent.java index fb9c1d8..4f6f039 100644 --- a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/GenericWebEvent.java +++ b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/GenericWebEvent.java @@ -49,7 +49,7 @@ import org.apache.ofbiz.security.Security; public class GenericWebEvent { private static final String MODULE = GenericWebEvent.class.getName(); - public static final String err_resource = "WebtoolsErrorUiLabels"; + private static final String ERR_RESOURCE = "WebtoolsErrorUiLabels"; /** An HTTP WebEvent handler that updates a Generic entity * @@ -66,7 +66,7 @@ public class GenericWebEvent { entityName = (String) request.getAttribute("entityName"); } if (UtilValidate.isEmpty(entityName)) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.entity_name_not_specified", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); Debug.logWarning("[GenericWebEvent.updateGeneric] The entityName was not specified," @@ -78,7 +78,7 @@ public class GenericWebEvent { Delegator delegator = (Delegator) request.getAttribute("delegator"); if (security == null) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.security_object_not_found", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); Debug.logWarning("[updateGeneric] The security object was not found in the request," @@ -86,7 +86,7 @@ public class GenericWebEvent { return "error"; } if (delegator == null) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.delegator_object_not_found", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); Debug.logWarning("[updateGeneric] The delegator object was not found in the request," @@ -117,14 +117,14 @@ public class GenericWebEvent { (String) request.getAttribute("pkValues")); } catch (Exception e) { - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(err_resource, + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.entity_path_not_valid", locale)); return "error"; } } if (UtilValidate.isEmpty(updateMode)) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.update_mode_not_specified", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); Debug.logWarning("[updateGeneric] Update Mode was not specified, but is required;" @@ -140,9 +140,9 @@ public class GenericWebEvent { "updateMode", updateMode, "entityName", entity.getEntityName(), "entityPlainTableName", plainTableName); - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.not_sufficient_permissions_01", messageMap, locale); - errMsg += UtilProperties.getMessage(err_resource, + errMsg += UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.not_sufficient_permissions_02", messageMap, locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); @@ -165,7 +165,7 @@ public class GenericWebEvent { } catch (GenericEntityException e) { Debug.logWarning(e, MODULE); Map<String, String> messageMap = UtilMisc.toMap("fieldType", field.getType()); - errMsg += UtilProperties.getMessage(err_resource, + errMsg += UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.fatal_error_param", messageMap, locale) + "."; } @@ -175,7 +175,7 @@ public class GenericWebEvent { findByEntity.setString(field.getName(), fval); } catch (Exception e) { Map<String, String> messageMap = UtilMisc.toMap("fval", fval); - errMsg = errMsg + "<li>" + field.getColName() + UtilProperties.getMessage(err_resource, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + "."; + errMsg = errMsg + "<li>" + field.getColName() + UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + "."; Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " + type.getJavaType() + "; entityName: " + entityName, MODULE); } } @@ -192,11 +192,11 @@ public class GenericWebEvent { // Delete actual main entity last, just in case database is set up to do a cascading delete, caches won't get cleared try { delegator.removeByPrimaryKey(findByEntity.getPrimaryKey()); - String confirmMsg = UtilProperties.getMessage(err_resource, + String confirmMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.delete_succeeded", locale); request.setAttribute("_EVENT_MESSAGE_", confirmMsg); } catch (GenericEntityException e) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.delete_failed", locale) + ": " + e.toString(); Debug.logWarning(e, errMsg, MODULE); request.setAttribute("_ERROR_MESSAGE_", errMsg); @@ -218,7 +218,7 @@ public class GenericWebEvent { } catch (GenericEntityException e) { Debug.logWarning(e, MODULE); Map<String, String> messageMap = UtilMisc.toMap("fieldType", field.getType()); - errMsgNonPk += UtilProperties.getMessage(err_resource, + errMsgNonPk += UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.fatal_error_param", messageMap, locale) + "."; } @@ -228,7 +228,7 @@ public class GenericWebEvent { findByEntity.setString(field.getName(), fval); } catch (Exception e) { Map<String, String> messageMap = UtilMisc.toMap("fval", fval); - errMsgNonPk += field.getColName() + UtilProperties.getMessage(err_resource, + errMsgNonPk += field.getColName() + UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + "."; Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " @@ -255,7 +255,7 @@ public class GenericWebEvent { .where(findByEntity.getPrimaryKey()) .queryOne(); } catch (GenericEntityException e) { - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.create_failed_by_check", locale) + ": " + e.toString(); Debug.logWarning(e, errMsg, MODULE); @@ -264,7 +264,7 @@ public class GenericWebEvent { } if (tempEntity != null) { Map<String, String> messageMap = UtilMisc.toMap("primaryKey", findByEntity.getPrimaryKey().toString()); - String errMsg = "[updateGeneric] " + entity.getEntityName() + UtilProperties.getMessage(err_resource, + String errMsg = "[updateGeneric] " + entity.getEntityName() + UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.already_exists_pk", messageMap, locale) + "."; Debug.logWarning(errMsg, MODULE); } @@ -327,9 +327,9 @@ public class GenericWebEvent { } catch (Exception e) { Debug.logError("[updateGeneric] Could not find validation message field: " + curValidate + "Msg of class " + className + "; returning generic validation failure message.", MODULE); - message = UtilProperties.getMessage(err_resource, "genericWebEvent.validation_failed", locale) + "."; + message = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.validation_failed", locale) + "."; } - errMsgParam += field.getColName() + " " + curValidate + " " + UtilProperties.getMessage(err_resource, + errMsgParam += field.getColName() + " " + curValidate + " " + UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.failed", locale) + ": " + message; Debug.logWarning("[updateGeneric] " + field.getColName() + " " + curValidate + " failed: " + message, MODULE); @@ -338,7 +338,7 @@ public class GenericWebEvent { } if (errMsgParam.length() > 0) { - errMsgParam = UtilProperties.getMessage(err_resource, + errMsgParam = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.following_error_occurred", locale) + errMsgParam; request.setAttribute("_ERROR_MESSAGE_", errMsgParam); return "error"; @@ -349,7 +349,7 @@ public class GenericWebEvent { delegator.create(findByEntity.getEntityName(), findByEntity.getAllFields()); } catch (GenericEntityException e) { Map<String, String> messageMap = UtilMisc.toMap("entityName", entity.getEntityName()); - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.creation_param_failed", messageMap, locale) + ": " + findByEntity.toString() + ": " + e.toString(); Debug.logWarning(e, errMsg, MODULE); @@ -363,7 +363,7 @@ public class GenericWebEvent { value.store(); } catch (GenericEntityException e) { Map<String, String> messageMap = UtilMisc.toMap("entityName", entity.getEntityName()); - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.update_of_param_failed", messageMap, locale) + ": " + value.toString() + ": " + e.toString(); Debug.logWarning(e, errMsg, MODULE); @@ -372,7 +372,7 @@ public class GenericWebEvent { } } else { Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode); - String errMsg = UtilProperties.getMessage(err_resource, + String errMsg = UtilProperties.getMessage(ERR_RESOURCE, "genericWebEvent.update_of_param_failed", messageMap, locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); diff --git a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/UtilCacheEvents.java b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/UtilCacheEvents.java index 8edd45b..17b964b 100644 --- a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/UtilCacheEvents.java +++ b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/UtilCacheEvents.java @@ -39,7 +39,7 @@ import org.apache.ofbiz.security.Security; */ public final class UtilCacheEvents { - private static final String err_resource = "WebtoolsErrorUiLabels"; + private static final String ERR_RESOURCE = "WebtoolsErrorUiLabels"; private static final String MODULE = UtilCacheEvents.class.getName(); @@ -56,21 +56,21 @@ public final class UtilCacheEvents { Security security = (Security) request.getAttribute("security"); if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.permissionEdit", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String name = request.getParameter("UTIL_CACHE_NAME"); if (name == null) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.noCacheNameSpecified", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.noCacheNameSpecified", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String numString = request.getParameter("UTIL_CACHE_ELEMENT_NUMBER"); if (numString == null) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.noElementNumberSpecified", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.noElementNumberSpecified", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", ""); return "error"; } @@ -102,15 +102,15 @@ public final class UtilCacheEvents { if (key != null) { utilCache.remove(key); - errMsg = UtilProperties.getMessage(err_resource, "utilCache.removeElementWithKey", UtilMisc.toMap("key", key.toString()), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.removeElementWithKey", UtilMisc.toMap("key", key.toString()), locale) + "."; request.setAttribute("_EVENT_MESSAGE_", errMsg); } else { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotRemoveElementNumber", UtilMisc.toMap("name", name, "numString", numString), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotRemoveElementNumber", UtilMisc.toMap("name", name, "numString", numString), locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } else { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotRemoveElement", UtilMisc.toMap("name", name), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotRemoveElement", UtilMisc.toMap("name", name), locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -128,7 +128,7 @@ public final class UtilCacheEvents { Security security = (Security) request.getAttribute("security"); if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.permissionEdit", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -136,7 +136,7 @@ public final class UtilCacheEvents { String name = request.getParameter("UTIL_CACHE_NAME"); if (name == null) { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotClearCache", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotClearCache", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -144,10 +144,10 @@ public final class UtilCacheEvents { if (utilCache != null) { utilCache.clear(); - errMsg = UtilProperties.getMessage(err_resource, "utilCache.clearCache", UtilMisc.toMap("name", name), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.clearCache", UtilMisc.toMap("name", name), locale) + "."; request.setAttribute("_EVENT_MESSAGE_", errMsg); } else { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotClearCacheNotFoundName", UtilMisc.toMap("name", name), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotClearCacheNotFoundName", UtilMisc.toMap("name", name), locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -165,13 +165,13 @@ public final class UtilCacheEvents { Security security = (Security) request.getAttribute("security"); if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.permissionEdit", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } UtilCache.clearAllCaches(); - errMsg = UtilProperties.getMessage(err_resource, "utilCache.clearAllCaches", locale); + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.clearAllCaches", locale); request.setAttribute("_EVENT_MESSAGE_", errMsg + " (" + UtilDateTime.nowDateString("yyyy-MM-dd HH:mm:ss") + ")."); return "success"; } @@ -187,7 +187,7 @@ public final class UtilCacheEvents { Security security = (Security) request.getAttribute("security"); if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.permissionEdit", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -206,7 +206,7 @@ public final class UtilCacheEvents { String name = request.getParameter("cacheName"+suffix); if (name == null) { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotClearCache", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotClearCache", locale) + "."; eventList.add(errMsg); } @@ -214,10 +214,10 @@ public final class UtilCacheEvents { if (utilCache != null) { utilCache.clear(); - errMsg = UtilProperties.getMessage(err_resource, "utilCache.clearCache", UtilMisc.toMap("name", name), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.clearCache", UtilMisc.toMap("name", name), locale) + "."; eventList.add(errMsg); } else { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotClearCacheNotFoundName", UtilMisc.toMap("name", name), locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotClearCacheNotFoundName", UtilMisc.toMap("name", name), locale) + "."; eventList.add(errMsg); } } @@ -236,7 +236,7 @@ public final class UtilCacheEvents { Security security = (Security) request.getAttribute("security"); if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) { - errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCacheEvents.permissionEdit", locale) + "."; request.setAttribute("_EVENT_MESSAGE_", errMsg); return "error"; } @@ -244,7 +244,7 @@ public final class UtilCacheEvents { String name = request.getParameter("UTIL_CACHE_NAME"); if (name == null) { - errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotUpdateCacheSetting", locale) + "."; + errMsg = UtilProperties.getMessage(ERR_RESOURCE, "utilCache.couldNotUpdateCacheSetting", locale) + "."; request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } diff --git a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/WebToolsServices.java b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/WebToolsServices.java index 387bd00..452f3af 100644 --- a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/WebToolsServices.java +++ b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/WebToolsServices.java @@ -249,8 +249,8 @@ public class WebToolsServices { int initialListSize = files.size(); int lastUnprocessedFilesCount = 0; List<File> unprocessedFiles = new LinkedList<>(); - while (files.size() > 0 && - files.size() != lastUnprocessedFilesCount) { + while (files.size() > 0 + && files.size() != lastUnprocessedFilesCount) { lastUnprocessedFilesCount = files.size(); unprocessedFiles = new LinkedList<>(); for (File f: files) { diff --git a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/artifactinfo/ControllerViewArtifactInfo.java b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/artifactinfo/ControllerViewArtifactInfo.java index ef88c32..f2e46bd 100644 --- a/framework/webtools/src/main/java/org/apache/ofbiz/webtools/artifactinfo/ControllerViewArtifactInfo.java +++ b/framework/webtools/src/main/java/org/apache/ofbiz/webtools/artifactinfo/ControllerViewArtifactInfo.java @@ -112,8 +112,8 @@ public class ControllerViewArtifactInfo extends ArtifactInfoBase { public boolean equals(Object obj) { if (obj instanceof ControllerViewArtifactInfo) { ControllerViewArtifactInfo that = (ControllerViewArtifactInfo) obj; - return Objects.equals(this.controllerXmlUrl, that.controllerXmlUrl) && - Objects.equals(this.viewUri, that.viewUri); + return Objects.equals(this.controllerXmlUrl, that.controllerXmlUrl) + && Objects.equals(this.viewUri, that.viewUri); } else { return false; } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java index a23e22c..394c16e 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java @@ -1037,7 +1037,7 @@ public class ModelFormField { * @see <code>widget-form.xsd</code> */ public static class CheckField extends FieldInfoWithOptions { - public final static String ROW_SUBMIT_FIELD_NAME = "_rowSubmit"; + public static final String ROW_SUBMIT_FIELD_NAME = "_rowSubmit"; private final FlexibleStringExpander allChecked; private CheckField(CheckField original, ModelFormField modelFormField) { @@ -1685,9 +1685,9 @@ public class ModelFormField { if (!this.format.isEmpty()) { formatVal = this.format.expandString(context); } else { - formatVal = this.type.endsWith("-number")? - this.type.replaceFirst("-number", "") - :"default"; + formatVal = this.type.endsWith("-number") + ? this.type.replaceFirst("-number", "") + : "default"; } Delegator delegator = (Delegator) context.get("delegator"); try { @@ -3881,13 +3881,15 @@ public class ModelFormField { Object retVal = GroovyUtil.eval(StringUtil.convertOperatorSubstitutions(ignoreWhen), context); if (retVal instanceof Boolean) { - shouldIgnore =(Boolean) retVal; + shouldIgnore = (Boolean) retVal; } else { - throw new IllegalArgumentException("Return value from ignore-when condition eval was not a Boolean: " + (retVal != null ? retVal.getClass().getName() : "null") + " [" + retVal + "] on the field " + this.name + " of form " + this.modelForm.getName()); + throw new IllegalArgumentException("Return value from ignore-when condition eval was not a Boolean: " + (retVal != null + ? retVal.getClass().getName() : "null") + " [" + retVal + "] on the field " + this.name + " of form " + this.modelForm.getName()); } } catch (CompilationFailedException e) { - String errMsg = "Error evaluating BeanShell ignore-when condition [" + ignoreWhen + "] on the field " + this.name + " of form " + this.modelForm.getName() + ": " + e.toString(); + String errMsg = + "Error evaluating BeanShell ignore-when condition [" + ignoreWhen + "] on the field " + this.name + " of form " + this.modelForm.getName() + ": " + e.toString(); Debug.logError(e, errMsg, MODULE); throw new IllegalArgumentException(errMsg); } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelTheme.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelTheme.java index 032ca58..1fdc54e 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelTheme.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelTheme.java @@ -330,8 +330,8 @@ public class ModelTheme implements Serializable { try { name.put(initThemePropertiesMap, ObjectType.simpleTypeOrObjectConvert(value, type, null, null)); } catch (GeneralException e) { - Debug.logError("Impossible to parse the value " + value + " to type " + type + - " for the property " + name + " on theme " + this.name, MODULE); + Debug.logError("Impossible to parse the value " + value + " to type " + type + + " for the property " + name + " on theme " + this.name, MODULE); } } } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/portal/PortalPageWorker.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/portal/PortalPageWorker.java index 3feb7ec..bcbbb69 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/portal/PortalPageWorker.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/portal/PortalPageWorker.java @@ -145,7 +145,7 @@ public class PortalPageWorker { /** * Checks if the user is allowed to configure the PortalPage. * PortalPage configuration is allowed if he is the PortalPage owner or he has got the PORTALPAGE_ADMIN permission - */ + */ public static Boolean userIsAllowedToConfigure(String portalPageId, Map<String, Object> context) { Boolean userIsAllowed = false; diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenStringRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenStringRenderer.java index 13263ad..4cbce09 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenStringRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/ScreenStringRenderer.java @@ -29,38 +29,38 @@ import org.apache.ofbiz.widget.model.ModelScreenWidget; * Widget Library - Screen String Renderer interface. */ public interface ScreenStringRenderer { - public String getRendererName(); - public void renderScreenBegin(Appendable writer, Map<String, Object> context) throws IOException; - public void renderScreenEnd(Appendable writer, Map<String, Object> context) throws IOException; - public void renderSectionBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException; - public void renderSectionEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException; - public void renderColumnContainer(Appendable writer, Map<String, Object> context, ModelScreenWidget.ColumnContainer columnContainer) throws IOException; - public void renderContainerBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException; - public void renderContainerEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException; - public void renderContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; - public void renderContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; - public void renderContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; - public void renderSubContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; - public void renderSubContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; - public void renderSubContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; + String getRendererName(); + void renderScreenBegin(Appendable writer, Map<String, Object> context) throws IOException; + void renderScreenEnd(Appendable writer, Map<String, Object> context) throws IOException; + void renderSectionBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException; + void renderSectionEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException; + void renderColumnContainer(Appendable writer, Map<String, Object> context, ModelScreenWidget.ColumnContainer columnContainer) throws IOException; + void renderContainerBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException; + void renderContainerEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException; + void renderContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; + void renderContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; + void renderContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; + void renderSubContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; + void renderSubContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; + void renderSubContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException; - public void renderHorizontalSeparator(Appendable writer, Map<String, Object> context, ModelScreenWidget.HorizontalSeparator separator) throws IOException; - public void renderLabel(Appendable writer, Map<String, Object> context, ModelScreenWidget.Label label) throws IOException; - public void renderLink(Appendable writer, Map<String, Object> context, ModelScreenWidget.ScreenLink link) throws IOException; - public void renderImage(Appendable writer, Map<String, Object> context, ModelScreenWidget.ScreenImage image) throws IOException; + void renderHorizontalSeparator(Appendable writer, Map<String, Object> context, ModelScreenWidget.HorizontalSeparator separator) throws IOException; + void renderLabel(Appendable writer, Map<String, Object> context, ModelScreenWidget.Label label) throws IOException; + void renderLink(Appendable writer, Map<String, Object> context, ModelScreenWidget.ScreenLink link) throws IOException; + void renderImage(Appendable writer, Map<String, Object> context, ModelScreenWidget.ScreenImage image) throws IOException; - public void renderContentFrame(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; - public void renderScreenletBegin(Appendable writer, Map<String, Object> context, boolean collapsed, ModelScreenWidget.Screenlet screenlet) throws IOException; - public void renderScreenletSubWidget(Appendable writer, Map<String, Object> context, ModelScreenWidget subWidget, ModelScreenWidget.Screenlet screenlet) throws GeneralException, IOException; - public void renderScreenletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Screenlet screenlet) throws IOException; + void renderContentFrame(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException; + void renderScreenletBegin(Appendable writer, Map<String, Object> context, boolean collapsed, ModelScreenWidget.Screenlet screenlet) throws IOException; + void renderScreenletSubWidget(Appendable writer, Map<String, Object> context, ModelScreenWidget subWidget, ModelScreenWidget.Screenlet screenlet) throws GeneralException, IOException; + void renderScreenletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Screenlet screenlet) throws IOException; - public void renderPortalPageBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException; - public void renderPortalPageEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException; - public void renderPortalPageColumnBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException; - public void renderPortalPageColumnEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException; - public void renderPortalPagePortletBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; - public void renderPortalPagePortletBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; - public void renderPortalPagePortletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; + void renderPortalPageBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException; + void renderPortalPageEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException; + void renderPortalPageColumnBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException; + void renderPortalPageColumnEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException; + void renderPortalPagePortletBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; + void renderPortalPagePortletBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; + void renderPortalPagePortletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException; } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/ScreenFopViewHandler.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/ScreenFopViewHandler.java index 64dd709..3350f30 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/ScreenFopViewHandler.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/fo/ScreenFopViewHandler.java @@ -152,9 +152,9 @@ public class ScreenFopViewHandler extends AbstractViewHandler { Reader reader = new StringReader(screenOutString); StreamSource src = new StreamSource(reader); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); /* Debug area, uncomment this to view the xml file generate before analyse by fop - try { + try { java.io.FileWriter fw = new java.io.FileWriter(new java.io.File(System.getProperty("ofbiz.home")+"/runtime/tempfiles/temp.xsl.fo")); fw.write(screenOutString); fw.close(); 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 95cf728..2fbdfbb 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 @@ -54,7 +54,7 @@ public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRe protected String userLoginIdAtPermGrant; protected String permissionErrorMessage = ""; - public static final String MODULE = HtmlMenuRenderer.class.getName(); + protected static final String MODULE = HtmlMenuRenderer.class.getName(); protected HtmlMenuRenderer() { } diff --git a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java index be7b885..e09234f 100644 --- a/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java +++ b/framework/widget/src/main/java/org/apache/ofbiz/widget/renderer/macro/MacroFormRenderer.java @@ -102,7 +102,6 @@ import freemarker.template.TemplateException; /** * Widget Library - Form Renderer implementation based on Freemarker macros - * */ public final class MacroFormRenderer implements FormStringRenderer { @@ -141,6 +140,25 @@ public final class MacroFormRenderer implements FormStringRenderer { this(macroLibraryPath, request, response); } + private static String encodeDoubleQuotes(String htmlString) { + return htmlString.replaceAll("\"", "\\\\\""); + } + + /** + * Extracts parameters from a target URL string, prepares them for an Ajax + * JavaScript call. This method is currently set to return a parameter string + * suitable for the Prototype.js library. + * + * @param target Target URL string + * @return Parameter string + */ + public static String getAjaxParamsFromTarget(String target) { + String targetParams = UtilHttp.getQueryStringFromTarget(target); + targetParams = targetParams.replace("?", ""); + targetParams = targetParams.replace("&", "&"); + return targetParams; + } + public boolean getRenderPagination() { return this.renderPagination; } @@ -176,10 +194,6 @@ public final class MacroFormRenderer implements FormStringRenderer { return value; } - private static String encodeDoubleQuotes(String htmlString) { - return htmlString.replaceAll("\"", "\\\\\""); - } - public void renderLabel(Appendable writer, Map<String, Object> context, ModelScreenWidget.Label label) { String labelText = label.getText(context); if (UtilValidate.isEmpty(labelText)) { @@ -208,7 +222,8 @@ public final class MacroFormRenderer implements FormStringRenderer { try { size = Integer.parseInt(displayField.getSize()); } catch (NumberFormatException nfe) { - Debug.logError(nfe, "Error reading size of a field fieldName=" + displayField.getModelFormField().getFieldName() + " FormName= " + displayField.getModelFormField().getModelForm().getName(), MODULE); + Debug.logError(nfe, "Error reading size of a field fieldName=" + displayField.getModelFormField().getFieldName() + " FormName= " + + displayField.getModelFormField().getModelForm().getName(), MODULE); } } ModelFormField.InPlaceEditor inPlaceEditor = displayField.getInPlaceEditor(); @@ -558,7 +573,7 @@ public final class MacroFormRenderer implements FormStringRenderer { Debug.logWarning("Invalid value for step property for field[" + paramName + "] with input-method=\"time-dropdown\" " + " Found Value [" + stepString + "] " + e.getMessage(), MODULE); } timeValues.append("["); - for (int i = 0; i <= 59;) { + for (int i = 0; i <= 59; ) { if (i != 0) { timeValues.append(", "); } @@ -1584,6 +1599,7 @@ public final class MacroFormRenderer implements FormStringRenderer { executeMacro(writer, sr.toString()); } + @Override public void renderEmptyFormDataMessage(Appendable writer, Map<String, Object> context, ModelForm modelForm) throws IOException { StringWriter sr = new StringWriter(); @@ -2900,8 +2916,9 @@ public final class MacroFormRenderer implements FormStringRenderer { /** * Renders the beginning boundary comment string. - * @param writer The writer to write to - * @param widgetType The widget type: "Screen Widget", "Form Widget", etc. + * + * @param writer The writer to write to + * @param widgetType The widget type: "Screen Widget", "Form Widget", etc. * @param modelWidget The widget */ public void renderBeginningBoundaryComment(Appendable writer, String widgetType, ModelWidget modelWidget) { @@ -2921,8 +2938,9 @@ public final class MacroFormRenderer implements FormStringRenderer { /** * Renders the ending boundary comment string. - * @param writer The writer to write to - * @param widgetType The widget type: "Screen Widget", "Form Widget", etc. + * + * @param writer The writer to write to + * @param widgetType The widget type: "Screen Widget", "Form Widget", etc. * @param modelWidget The widget */ public void renderEndingBoundaryComment(Appendable writer, String widgetType, ModelWidget modelWidget) { @@ -3020,8 +3038,10 @@ public final class MacroFormRenderer implements FormStringRenderer { executeMacro(writer, sr.toString()); } - /** Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See + /** + * Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See * <code>OfbizUtil.js</code>. + * * @param updateAreas * @param extraParams Renderer-supplied additional target parameters * @param context @@ -3062,8 +3082,10 @@ public final class MacroFormRenderer implements FormStringRenderer { return FlexibleStringExpander.expandString(sb.toString(), context, locale); } - /** Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See + /** + * Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See * <code>OfbizUtil.js</code>. + * * @param updateAreas * @param extraParams Renderer-supplied additional target parameters * @param context @@ -3121,19 +3143,6 @@ public final class MacroFormRenderer implements FormStringRenderer { return FlexibleStringExpander.expandString(ajaxUrl, context, locale); } - /** Extracts parameters from a target URL string, prepares them for an Ajax - * JavaScript call. This method is currently set to return a parameter string - * suitable for the Prototype.js library. - * @param target Target URL string - * @return Parameter string - */ - public static String getAjaxParamsFromTarget(String target) { - String targetParams = UtilHttp.getQueryStringFromTarget(target); - targetParams = targetParams.replace("?", ""); - targetParams = targetParams.replace("&", "&"); - return targetParams; - } - public void appendTooltip(Appendable writer, Map<String, Object> context, ModelFormField modelFormField) { // render the tooltip, in other methods too String tooltip = modelFormField.getTooltip(context); @@ -3191,7 +3200,7 @@ public final class MacroFormRenderer implements FormStringRenderer { } public void makeHyperlinkByType(Appendable writer, String linkType, String linkStyle, String targetType, String target, Map<String, String> parameterMap, String description, String targetWindow, String confirmation, ModelFormField modelFormField, HttpServletRequest request, - HttpServletResponse response, Map<String, Object> context) throws IOException { + HttpServletResponse response, Map<String, Object> context) throws IOException { String realLinkType = WidgetWorker.determineAutoLinkType(linkType, target, targetType, request); String encodedDescription = encode(description, modelFormField, context); // get the parameterized pagination index and size fields @@ -3259,7 +3268,7 @@ public final class MacroFormRenderer implements FormStringRenderer { } public void makeHyperlinkString(Appendable writer, String linkStyle, String targetType, String target, Map<String, String> parameterMap, String description, String confirmation, ModelFormField modelFormField, HttpServletRequest request, HttpServletResponse response, Map<String, Object> context, - String targetWindow) throws IOException { + String targetWindow) throws IOException { if (description != null || UtilValidate.isNotEmpty(request.getAttribute("image"))) { StringBuilder linkUrl = new StringBuilder(); final URI linkUri = WidgetWorker.buildHyperlinkUri(target, targetType, @@ -3309,7 +3318,7 @@ public final class MacroFormRenderer implements FormStringRenderer { height = request.getAttribute("height").toString(); } StringBuilder targetParameters = new StringBuilder(); - if (UtilValidate.isNotEmpty(parameterMap) ) { + if (UtilValidate.isNotEmpty(parameterMap)) { targetParameters.append("{"); for (Map.Entry<String, String> parameter : parameterMap.entrySet()) { if (targetParameters.length() > 1) { |
Free forum by Nabble | Edit this page |