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 9689201 Improved: Make data members of class as private and added accessor methods for the same, also corrected occurences of the same in framework component. (OFBIZ-11963) Also made some related checkstyle code enhancements. Thanks jacques for finalizing Javadoc pattern during this effort. 9689201 is described below commit 9689201b84ca4e3db52138670644923de172ff85 Author: Suraj Khurana <[hidden email]> AuthorDate: Sat Aug 22 13:20:39 2020 +0530 Improved: Make data members of class as private and added accessor methods for the same, also corrected occurences of the same in framework component. (OFBIZ-11963) Also made some related checkstyle code enhancements. Thanks jacques for finalizing Javadoc pattern during this effort. --- .../ofbiz/base/component/ComponentConfig.java | 21 - .../base/component/ComponentLoaderConfig.java | 12 +- .../base/component/ComponentResourceHandler.java | 11 +- .../ofbiz/base/concurrent/ExecutionPool.java | 2 - .../ofbiz/base/container/AdminServerContainer.java | 12 +- .../ofbiz/base/container/ComponentContainer.java | 6 +- .../ofbiz/base/container/ContainerConfig.java | 4 - .../ofbiz/base/container/ContainerLoader.java | 2 +- .../base/container/NamingServiceContainer.java | 16 +- .../ofbiz/base/conversion/DateTimeConverters.java | 24 +- .../apache/ofbiz/base/lang/ComparableRange.java | 22 +- .../java/org/apache/ofbiz/base/util/DateRange.java | 12 +- .../java/org/apache/ofbiz/base/util/FileUtil.java | 6 +- .../apache/ofbiz/base/util/IndentingWriter.java | 8 +- .../org/apache/ofbiz/base/util/MessageString.java | 16 +- .../org/apache/ofbiz/base/util/UtilFormatOut.java | 31 +- .../java/org/apache/ofbiz/base/util/UtilHttp.java | 5 +- .../org/apache/ofbiz/base/util/UtilProperties.java | 51 +- .../java/org/apache/ofbiz/base/util/UtilTimer.java | 44 +- .../apache/ofbiz/base/util/cache/UtilCache.java | 69 +- .../util/collections/FlexibleServletAccessor.java | 76 +- .../base/util/collections/GenericMapEntry.java | 6 +- .../ofbiz/base/util/collections/PagedList.java | 12 +- .../util/collections/ResourceBundleMapWrapper.java | 38 +- .../catalina/container/CatalinaContainer.java | 2 +- .../example/TestFailAuthenticator.java | 6 +- .../ofbiz/common/scripting/ScriptHelperImpl.java | 28 +- .../org/apache/ofbiz/entity/GenericDelegator.java | 344 ++++++--- .../java/org/apache/ofbiz/entity/cache/Cache.java | 93 ++- .../entity/condition/EntityConditionSubSelect.java | 8 +- .../ofbiz/entity/condition/EntityFieldValue.java | 25 +- .../apache/ofbiz/entity/condition/OrderByItem.java | 42 +- .../org/apache/ofbiz/entity/finder/ListFinder.java | 37 +- .../ofbiz/entity/finder/PrimaryKeyFinder.java | 13 +- .../apache/ofbiz/entity/jdbc/CursorStatement.java | 10 +- .../org/apache/ofbiz/entity/jdbc/DatabaseUtil.java | 8 - .../ofbiz/entity/model/DynamicViewEntity.java | 122 ++- .../org/apache/ofbiz/entity/model/ModelEntity.java | 375 +++++++++- .../apache/ofbiz/entity/model/ModelViewEntity.java | 256 +++++-- .../org/apache/ofbiz/entity/util/SequenceUtil.java | 2 - .../permission/EntityPermissionChecker.java | 84 ++- .../apache/ofbiz/minilang/SimpleServiceEngine.java | 19 +- .../ofbiz/minilang/method/callops/CallService.java | 41 +- .../apache/ofbiz/minilang/operation/Compare.java | 4 +- .../ofbiz/minilang/operation/CompareField.java | 4 +- .../apache/ofbiz/minilang/operation/Convert.java | 26 +- .../org/apache/ofbiz/minilang/operation/Copy.java | 16 +- .../apache/ofbiz/minilang/operation/NotEmpty.java | 5 +- .../apache/ofbiz/minilang/operation/Regexp.java | 4 +- .../minilang/operation/SimpleMapOperation.java | 24 +- .../ofbiz/minilang/operation/SimpleMapProcess.java | 23 +- .../ofbiz/minilang/operation/ValidateMethod.java | 8 +- .../java/org/apache/ofbiz/security/CsrfUtil.java | 2 +- .../org/apache/ofbiz/security/CsrfUtilTests.java | 20 +- .../ofbiz/service/GeneralServiceException.java | 15 +- .../ofbiz/service/GenericAbstractDispatcher.java | 80 +- .../ofbiz/service/GenericDispatcherFactory.java | 114 +-- .../java/org/apache/ofbiz/service/ModelParam.java | 371 ++++++++- .../org/apache/ofbiz/service/ModelPermission.java | 151 +++- .../org/apache/ofbiz/service/ModelService.java | 825 ++++++++++++++++++--- .../apache/ofbiz/service/ModelServiceReader.java | 335 ++++----- .../apache/ofbiz/service/ServiceDispatcher.java | 209 +++--- .../ofbiz/service/ServiceSynchronization.java | 40 +- .../java/org/apache/ofbiz/service/ServiceUtil.java | 2 +- .../ofbiz/service/ServiceValidationException.java | 32 +- .../org/apache/ofbiz/service/ServiceXaWrapper.java | 2 +- .../service/calendar/TemporalExpressions.java | 4 - .../ofbiz/service/config/model/ServiceEngine.java | 4 +- .../ofbiz/service/engine/AbstractEngine.java | 20 +- .../ofbiz/service/engine/EntityAutoEngine.java | 97 ++- .../ofbiz/service/engine/GenericAsyncEngine.java | 30 +- .../apache/ofbiz/service/engine/GroovyEngine.java | 18 +- .../apache/ofbiz/service/engine/HttpEngine.java | 8 +- .../ofbiz/service/engine/SOAPClientEngine.java | 19 +- .../apache/ofbiz/service/engine/ScriptEngine.java | 14 +- .../ofbiz/service/engine/StandardJavaEngine.java | 31 +- .../ofbiz/service/engine/XMLRPCClientEngine.java | 18 +- .../ofbiz/service/group/ServiceGroupEngine.java | 4 +- .../ofbiz/service/jms/AbstractJmsListener.java | 2 +- .../apache/ofbiz/service/jms/JmsServiceEngine.java | 83 ++- .../ofbiz/service/rmi/RemoteDispatcherImpl.java | 34 +- .../ofbiz/service/rmi/RmiServiceContainer.java | 4 +- .../apache/ofbiz/service/rmi/RmiServiceEngine.java | 11 +- .../ofbiz/service/semaphore/ServiceSemaphore.java | 18 +- .../org/apache/ofbiz/service/test/XmlRpcTests.java | 6 +- .../org/apache/ofbiz/base/start/AdminClient.java | 6 +- .../java/org/apache/ofbiz/base/start/Config.java | 65 +- .../apache/ofbiz/base/start/StartupCommand.java | 17 + .../ofbiz/base/start/StartupControlPanel.java | 10 +- .../org/apache/ofbiz/testtools/ModelTestSuite.java | 27 +- .../apache/ofbiz/testtools/SimpleMethodTest.java | 8 +- .../org/apache/ofbiz/webapp/OfbizUrlBuilder.java | 5 +- .../ofbiz/webapp/control/ConfigXMLReader.java | 545 ++++++++++++-- .../apache/ofbiz/webapp/control/LoginWorker.java | 4 +- .../ofbiz/webapp/control/RequestHandler.java | 213 +++--- .../org/apache/ofbiz/webapp/event/CoreEvents.java | 10 +- .../webapp/event/FileUploadProgressListener.java | 24 +- .../ofbiz/webapp/event/GroovyEventHandler.java | 16 +- .../ofbiz/webapp/event/JavaEventHandler.java | 12 +- .../ofbiz/webapp/event/SOAPEventHandler.java | 10 +- .../ofbiz/webapp/event/ScriptEventHandler.java | 6 +- .../ofbiz/webapp/event/ServiceEventHandler.java | 28 +- .../webapp/event/ServiceMultiEventHandler.java | 38 +- .../ofbiz/webapp/event/SimpleEventHandler.java | 9 +- .../ofbiz/webapp/event/XmlRpcEventHandler.java | 4 +- .../apache/ofbiz/webapp/webdav/WebDavServlet.java | 8 +- .../ofbiz/webapp/website/WebSiteProperties.java | 12 +- .../ofbiz/webapp/control/RequestHandlerTests.java | 6 +- .../groovyScripts/service/AvailableServices.groovy | 62 +- .../webtools/artifactinfo/ArtifactInfoFactory.java | 324 +++++++- .../ControllerRequestArtifactInfo.java | 93 ++- .../artifactinfo/ControllerViewArtifactInfo.java | 25 +- .../webtools/artifactinfo/EntityArtifactInfo.java | 45 +- .../artifactinfo/FormWidgetArtifactInfo.java | 100 ++- .../artifactinfo/ScreenWidgetArtifactInfo.java | 68 +- .../webtools/artifactinfo/ServiceArtifactInfo.java | 212 ++++-- .../artifactinfo/ServiceEcaArtifactInfo.java | 64 +- .../ofbiz/webtools/labelmanager/LabelInfo.java | 37 +- .../webtools/labelmanager/LabelManagerFactory.java | 29 +- .../webtools/labelmanager/LabelReferences.java | 118 ++- .../webtools/labelmanager/SaveLabelsToXmlFile.java | 9 +- .../java/org/apache/ofbiz/widget/WidgetWorker.java | 2 +- .../widget/artifact/ArtifactInfoGatherer.java | 6 +- .../ofbiz/widget/model/AbstractModelCondition.java | 4 +- .../ofbiz/widget/model/CommonWidgetModels.java | 36 +- .../org/apache/ofbiz/widget/model/ModelForm.java | 667 ++++++++++++++++- .../apache/ofbiz/widget/model/ModelFormField.java | 473 +++++++++++- .../ofbiz/widget/model/ModelFormFieldBuilder.java | 416 ++++++++++- .../ofbiz/widget/model/ModelWidgetCondition.java | 2 +- .../ofbiz/widget/model/XmlWidgetVisitor.java | 25 +- .../ofbiz/widget/renderer/ScreenRenderer.java | 27 +- .../widget/renderer/html/HtmlMenuRenderer.java | 56 +- .../renderer/html/HtmlMenuRendererImage.java | 10 +- .../widget/renderer/html/HtmlMenuWrapper.java | 76 +- .../widget/renderer/html/HtmlMenuWrapperImage.java | 4 +- .../ofbiz/widget/test/WidgetMacroLibraryTests.java | 34 +- 136 files changed, 6940 insertions(+), 1925 deletions(-) diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentConfig.java b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentConfig.java index dd2c1f9..77f492f 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentConfig.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentConfig.java @@ -825,7 +825,6 @@ public final class ComponentConfig { /** * Create resource handler component resource handler. - * * @return the component resource handler */ public ComponentResourceHandler createResourceHandler() { @@ -834,7 +833,6 @@ public final class ComponentConfig { /** * Gets component config. - * * @return the component config */ public ComponentConfig getComponentConfig() { @@ -843,7 +841,6 @@ public final class ComponentConfig { /** * Gets location. - * * @return the location */ public String getLocation() { @@ -990,7 +987,6 @@ public final class ComponentConfig { /** * Component config builder. - * * @param componentConfig the component config * @return the builder */ @@ -1001,7 +997,6 @@ public final class ComponentConfig { /** * Virtual hosts builder. - * * @param virtualHosts the virtual hosts * @return the builder */ @@ -1012,7 +1007,6 @@ public final class ComponentConfig { /** * Init parameters builder. - * * @param initParameters the init parameters * @return the builder */ @@ -1023,7 +1017,6 @@ public final class ComponentConfig { /** * Name builder. - * * @param name the name * @return the builder */ @@ -1034,7 +1027,6 @@ public final class ComponentConfig { /** * Title builder. - * * @param title the title * @return the builder */ @@ -1045,7 +1037,6 @@ public final class ComponentConfig { /** * Description builder. - * * @param description the description * @return the builder */ @@ -1056,7 +1047,6 @@ public final class ComponentConfig { /** * Menu name builder. - * * @param menuName the menu name * @return the builder */ @@ -1067,7 +1057,6 @@ public final class ComponentConfig { /** * Server builder. - * * @param server the server * @return the builder */ @@ -1078,7 +1067,6 @@ public final class ComponentConfig { /** * Mount point builder. - * * @param mountPoint the mount point * @return the builder */ @@ -1089,7 +1077,6 @@ public final class ComponentConfig { /** * Context root builder. - * * @param contextRoot the context root * @return the builder */ @@ -1100,7 +1087,6 @@ public final class ComponentConfig { /** * Location builder. - * * @param location the location * @return the builder */ @@ -1111,7 +1097,6 @@ public final class ComponentConfig { /** * Base permissions builder. - * * @param basePermissions the base permissions * @return the builder */ @@ -1122,7 +1107,6 @@ public final class ComponentConfig { /** * Position builder. - * * @param position the position * @return the builder */ @@ -1133,7 +1117,6 @@ public final class ComponentConfig { /** * Privileged builder. - * * @param privileged the privileged * @return the builder */ @@ -1144,7 +1127,6 @@ public final class ComponentConfig { /** * App bar display builder. - * * @param appBarDisplay the app bar display * @return the builder */ @@ -1155,7 +1137,6 @@ public final class ComponentConfig { /** * Access permission builder. - * * @param accessPermission the access permission * @return the builder */ @@ -1166,7 +1147,6 @@ public final class ComponentConfig { /** * Use autologin cookie builder. - * * @param useAutologinCookie the use autologin cookie * @return the builder */ @@ -1177,7 +1157,6 @@ public final class ComponentConfig { /** * Create webapp info. - * * @return the webapp info */ public WebappInfo create() { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentLoaderConfig.java b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentLoaderConfig.java index 1caf8db..917d78b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentLoaderConfig.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/component/ComponentLoaderConfig.java @@ -92,9 +92,17 @@ public final class ComponentLoaderConfig { */ public static class ComponentDef { /** The location of the component. */ - public final Path location; + private final Path location; /** The type of component. */ - public final ComponentType type; + private final ComponentType type; + + public Path getLocation() { + return location; + } + + public ComponentType getType() { + return type; + } /** * Constructs a component definition. 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 2be1a32..713a9f2 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 @@ -40,9 +40,9 @@ import org.xml.sax.SAXException; public class ComponentResourceHandler implements ResourceHandler { private static final String MODULE = ComponentResourceHandler.class.getName(); - protected String componentName; - protected String loaderName; - protected String location; + private String componentName; + private String loaderName; + private String location; public ComponentResourceHandler(String componentName, Element element) { this.componentName = componentName; @@ -73,7 +73,7 @@ public class ComponentResourceHandler implements ResourceHandler { public Document getDocument() throws GenericConfigException { try { return UtilXml.readXmlDocument(this.getStream(), this.getFullLocation(), true); - } catch (SAXException | ParserConfigurationException | IOException e) { + } catch (SAXException | ParserConfigurationException | IOException e) { throw new GenericConfigException("Error reading " + this.toString(), e); } } @@ -120,6 +120,7 @@ public class ComponentResourceHandler implements ResourceHandler { @Override public String toString() { - return "ComponentResourceHandler from XML file [" + this.componentName + "] with loaderName [" + loaderName + "] and location [" + location + "]"; + return "ComponentResourceHandler from XML file [" + this.componentName + "] with loaderName [" + loaderName + "] and location [" + + location + "]"; } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/concurrent/ExecutionPool.java b/framework/base/src/main/java/org/apache/ofbiz/base/concurrent/ExecutionPool.java index 375b4df..388c82b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/concurrent/ExecutionPool.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/concurrent/ExecutionPool.java @@ -137,7 +137,6 @@ public final class ExecutionPool { /** * Gets load time nanos. - * * @return the load time nanos */ public long getLoadTimeNanos() { @@ -146,7 +145,6 @@ public final class ExecutionPool { /** * Gets expire time nanos. - * * @return the expire time nanos */ public long getExpireTimeNanos() { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java index e13821c..3e1bf0c 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java @@ -56,13 +56,13 @@ public final class AdminServerContainer implements Container { public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException { this.name = name; try { - serverSocket = new ServerSocket(cfg.adminPort, 1, cfg.adminAddress); + serverSocket = new ServerSocket(cfg.getAdminPort(), 1, cfg.getAdminAddress()); } catch (IOException e) { - String msg = "Couldn't create server socket(" + cfg.adminAddress + ":" + cfg.adminPort + ")"; + String msg = "Couldn't create server socket(" + cfg.getAdminAddress() + ":" + cfg.getAdminPort() + ")"; throw new ContainerException(msg, e); } - if (cfg.adminPort > 0) { + if (cfg.getAdminPort() > 0) { serverThread = new Thread(this::run, "OFBiz-AdminServer"); } else { serverThread = new Thread("OFBiz-AdminServer"); // Dummy thread @@ -73,7 +73,7 @@ public final class AdminServerContainer implements Container { // Listens for administration commands. private void run() { - System.out.println("Admin socket configured on - " + cfg.adminAddress + ":" + cfg.adminPort); + System.out.println("Admin socket configured on - " + cfg.getAdminAddress() + ":" + cfg.getAdminPort()); while (!Thread.interrupted()) { try (Socket client = serverSocket.accept()) { System.out.println("Received connection from - " + client.getInetAddress() + " : " + client.getPort()); @@ -104,7 +104,7 @@ public final class AdminServerContainer implements Container { private void processClientRequest(Socket client) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8), true)) { + PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8), true)) { // read client request and prepare response String clientRequest = reader.readLine(); @@ -136,7 +136,7 @@ public final class AdminServerContainer implements Container { private boolean isValidRequest(String request) { return UtilValidate.isNotEmpty(request) && request.contains(":") - && request.substring(0, request.indexOf(':')).equals(cfg.adminKey) + && request.substring(0, request.indexOf(':')).equals(cfg.getAdminKey()) && !request.substring(request.indexOf(':') + 1).isEmpty(); } private static String prepareResponseToClient(OfbizSocketCommand control) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/ComponentContainer.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/ComponentContainer.java index 60392ff..3cb3445 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/ComponentContainer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/ComponentContainer.java @@ -54,7 +54,7 @@ public class ComponentContainer implements Container { @Override public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException { - init(name, Start.getInstance().getConfig().ofbizHome); + init(name, Start.getInstance().getConfig().getOfbizHome()); } /** @@ -93,8 +93,8 @@ public class ComponentContainer implements Container { * @throws IOException when component directory loading fails. */ private void loadComponent(Path dir, ComponentDef component) throws IOException { - Path location = component.location.isAbsolute() ? component.location : dir.resolve(component.location); - switch (component.type) { + Path location = component.getLocation().isAbsolute() ? component.getLocation() : dir.resolve(component.getLocation()); + switch (component.getType()) { case COMPONENT_DIRECTORY: loadComponentDirectory(location); break; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerConfig.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerConfig.java index 565288c..f20fe97 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerConfig.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerConfig.java @@ -222,7 +222,6 @@ public final class ContainerConfig { //FORBID PUBLIC FIELDS /** * Constructs a container configuration element. - * * @param element the {@code <property>} XML element containing the configuration. */ public Property(Element element) { @@ -236,7 +235,6 @@ public final class ContainerConfig { } /** * Aggregates the {@code <property>} XML elements in a Map. - * * @param root the root XML Element containing {@code <property>} children * @return a map of property elements */ @@ -250,7 +248,6 @@ public final class ContainerConfig { } /** * Provides all the child properties whose values are equal a specified value. - * * @param value the value to match * @return a list of matching properties */ @@ -287,7 +284,6 @@ public final class ContainerConfig { } /** * Provides all the child properties whose values are equal a specified value. - * * @param value the value to match * @return a list of matching properties */ diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerLoader.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerLoader.java index 85e54d7..d0db7c4 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerLoader.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/ContainerLoader.java @@ -71,7 +71,7 @@ public class ContainerLoader { // Load containers defined in components. Debug.logInfo("[Startup] Loading containers...", MODULE); - loadedContainers.addAll(loadContainersFromConfigurations(config.loaders, ofbizCommands)); + loadedContainers.addAll(loadContainersFromConfigurations(config.getLoaders(), ofbizCommands)); // Start all containers loaded from above steps startLoadedContainers(); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/container/NamingServiceContainer.java b/framework/base/src/main/java/org/apache/ofbiz/base/container/NamingServiceContainer.java index a7c66bc..53255e2 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/container/NamingServiceContainer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/container/NamingServiceContainer.java @@ -40,19 +40,19 @@ public class NamingServiceContainer implements Container { private static final String MODULE = NamingServiceContainer.class.getName(); - protected String configFileLocation = null; - protected boolean isRunning = false; - protected Registry registry = null; - protected int namingPort = 1099; - protected String namingHost = null; + private String configFileLocation = null; + private boolean isRunning = false; + private Registry registry = null; + private int namingPort = 1099; + private String namingHost = null; - protected RMIExtendedSocketFactory rmiSocketFactory; + private RMIExtendedSocketFactory rmiSocketFactory; private String name; @Override public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException { - this.name =name; + this.name = name; this.configFileLocation = configFile; Configuration cfg = ContainerConfig.getConfiguration(name); @@ -62,7 +62,7 @@ public class NamingServiceContainer implements Container { Configuration.Property port = cfg.getProperty("port"); if (port.value() != null) { try { - this.namingPort = Integer.parseInt(port.value()) + Start.getInstance().getConfig().portOffset; + this.namingPort = Integer.parseInt(port.value()) + Start.getInstance().getConfig().getPortOffset(); } catch (Exception e) { throw new ContainerException("Invalid port defined in container [naming-container] configuration or as portOffset; not a valid int"); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/DateTimeConverters.java b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/DateTimeConverters.java index d4fc222..90e566c 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/conversion/DateTimeConverters.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/conversion/DateTimeConverters.java @@ -109,7 +109,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public Long convert(java.util.Date obj) throws ConversionException { - return obj.getTime(); + return obj.getTime(); } } @@ -194,7 +194,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.math.BigDecimal convert(TimeDuration obj) throws ConversionException { - return new java.math.BigDecimal(TimeDuration.toLong(obj)); + return new java.math.BigDecimal(TimeDuration.toLong(obj)); } } @@ -205,7 +205,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public Double convert(TimeDuration obj) throws ConversionException { - return (double) TimeDuration.toLong(obj); + return (double) TimeDuration.toLong(obj); } } @@ -216,7 +216,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public Float convert(TimeDuration obj) throws ConversionException { - return (float) TimeDuration.toLong(obj); + return (float) TimeDuration.toLong(obj); } } @@ -233,7 +233,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public Long convert(TimeDuration obj) throws ConversionException { - return TimeDuration.toLong(obj); + return TimeDuration.toLong(obj); } } @@ -250,7 +250,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public String convert(TimeDuration obj) throws ConversionException { - return obj.toString(); + return obj.toString(); } } @@ -303,7 +303,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.util.Date convert(Number obj) throws ConversionException { - return new java.util.Date(obj.longValue()); + return new java.util.Date(obj.longValue()); } } @@ -314,7 +314,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public TimeDuration convert(Number obj) throws ConversionException { - return TimeDuration.fromNumber(obj); + return TimeDuration.fromNumber(obj); } } @@ -350,7 +350,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.sql.Time convert(Number obj) throws ConversionException { - return new java.sql.Time(obj.longValue()); + return new java.sql.Time(obj.longValue()); } } @@ -366,7 +366,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.sql.Timestamp convert(Number obj) throws ConversionException { - return new java.sql.Timestamp(obj.longValue()); + return new java.sql.Timestamp(obj.longValue()); } } @@ -433,7 +433,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.sql.Time convert(java.sql.Date obj) throws ConversionException { throw new ConversionException("Conversion from Date to Time not supported"); - } + } } public static class SqlDateToTimestamp extends AbstractConverter<java.sql.Date, java.sql.Timestamp> { @@ -449,7 +449,7 @@ public class DateTimeConverters implements ConverterLoader { @Override public java.sql.Timestamp convert(java.sql.Date obj) throws ConversionException { return new java.sql.Timestamp(obj.getTime()); - } + } } public static class SqlTimeToList extends GenericSingletonToList<java.sql.Time> { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/lang/ComparableRange.java b/framework/base/src/main/java/org/apache/ofbiz/base/lang/ComparableRange.java index 19e2be0..4de918a 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/lang/ComparableRange.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/lang/ComparableRange.java @@ -22,9 +22,25 @@ package org.apache.ofbiz.base.lang; @SourceMonitored public class ComparableRange<T extends Comparable<T>> implements Range<T>, Comparable<ComparableRange<T>> { - protected final T start; - protected final T end; - protected final boolean isPoint; + private final T start; + private final T end; + private final boolean isPoint; + + /** + * Gets start. + * @return the start + */ + public T getStart() { + return start; + } + + /** + * Gets end. + * @return the end + */ + public T getEnd() { + return end; + } public ComparableRange(T start, T end) { if (start.getClass() != end.getClass()) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/DateRange.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/DateRange.java index 56b78f6..60c31aa 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/DateRange.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/DateRange.java @@ -68,19 +68,19 @@ public class DateRange extends ComparableRange<Date> implements Serializable { * @return Range duration in milliseconds */ public long durationInMillis() { - return this.end.getTime() - this.start.getTime(); + return this.getEnd().getTime() - this.getStart().getTime(); } @Override public Date end() { - return (Date) this.end.clone(); + return (Date) this.getEnd().clone(); } /** Returns the ending date of this range as a <code>Timestamp</code> instance. * @return Range ending date <code>Timestamp</code> */ public Timestamp endStamp() { - return new Timestamp(this.end.getTime()); + return new Timestamp(this.getEnd().getTime()); } /** Returns <code>true</code> if <code>date</code> occurs within this range. @@ -107,18 +107,18 @@ public class DateRange extends ComparableRange<Date> implements Serializable { * @return <code>true</code> if <code>range</code> intersects this range */ public boolean intersectsRange(DateRange range) { - return (isPoint() && range.isPoint() && this.start.equals(range.start)) || (!before(range) && !after(range)); + return (isPoint() && range.isPoint() && this.getStart().equals(range.getStart())) || (!before(range) && !after(range)); } @Override public Date start() { - return (Date) this.start.clone(); + return (Date) this.getStart().clone(); } /** Returns the starting date of this range as a <code>Timestamp</code> instance. * @return Range starting date <code>Timestamp</code> */ public Timestamp startStamp() { - return new Timestamp(this.start.getTime()); + return new Timestamp(this.getStart().getTime()); } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java index c3372fe..11ae20b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java @@ -431,9 +431,9 @@ public final class FileUtil { } private static class SearchTextFilesFilter implements FilenameFilter { - String fileExtension; - Set<String> stringsToFindInFile = new HashSet<>(); - Set<String> stringsToFindInPath = new HashSet<>(); + private String fileExtension; + private Set<String> stringsToFindInFile = new HashSet<>(); + private Set<String> stringsToFindInPath = new HashSet<>(); SearchTextFilesFilter(String fileExtension, Set<String> stringsToFindInPath, Set<String> stringsToFindInFile) { this.fileExtension = fileExtension; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java index d5d714f..7441c3d 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java @@ -26,10 +26,10 @@ import org.apache.ofbiz.base.lang.SourceMonitored; @SourceMonitored public class IndentingWriter extends FilterWriter { - protected final StringBuilder indent = new StringBuilder(); - protected final boolean doSpace; - protected final boolean doNewline; - protected boolean lastWasNewline; + private final StringBuilder indent = new StringBuilder(); + private final boolean doSpace; + private final boolean doNewline; + private boolean lastWasNewline; public static IndentingWriter makeIndentingWriter(Writer writer) { return writer instanceof IndentingWriter ? (IndentingWriter) writer : new IndentingWriter(writer); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java index 3f247d9..6352190 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java @@ -35,14 +35,14 @@ public class MessageString implements Serializable { private static final String MODULE = MessageString.class.getName(); - protected String message; - protected String fieldName; - protected String toFieldName; - protected Throwable sourceError; - protected Locale locale; - protected String propertyResource; - protected String propertyName; - protected boolean isError = true; + private String message; + private String fieldName; + private String toFieldName; + private Throwable sourceError; + private Locale locale; + private String propertyResource; + private String propertyName; + private boolean isError = true; public static List<Object> getMessagesForField(String fieldName, boolean convertToStrings, List<Object> messageStringList) { if (fieldName == null) { 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 973c179..3024f09 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 @@ -209,15 +209,16 @@ public final class UtilFormatOut { } - /** Formats a BigDecimal value 1:1 into a percentage string (e.g. 10 to 10% instead of 0,1 to 10%) + /** + * Formats a BigDecimal value 1:1 into a percentage string (e.g. 10 to 10% instead of 0,1 to 10%) * @param percentage The percentage Decimal to be formatted * @return A String with the formatted percentage */ - public static String formatPercentageRate(BigDecimal percentage, boolean negate) { + public static String formatPercentageRate(BigDecimal percentage, boolean negate) { if (percentage == null) { return ""; } - BigDecimal hundred = BigDecimal.valueOf(negate? -100: 100); + BigDecimal hundred = BigDecimal.valueOf(negate ? -100 : 100); return formatNumber(percentage.divide(hundred), PERCENTAGE_FORMAT, null, null); } @@ -376,11 +377,13 @@ public final class UtilFormatOut { } } - /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String. + /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, + * otherwise an empty but non-null String. * @param string1 The first passed String * @param string2 The second passed String * @param string3 The third passed String - * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String + * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, + * otherwise an empty but non-null String */ public static String checkNull(String string1, String string2, String string3) { if (string1 != null) { @@ -394,12 +397,14 @@ public final class UtilFormatOut { } } - /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String. + /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, + * otherwise the fourth if not null, otherwise an empty but non-null String. * @param string1 The first passed String * @param string2 The second passed String * @param string3 The third passed String * @param string4 The fourth passed String - * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String + * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, + * otherwise the fourth if not null, otherwise an empty but non-null String */ public static String checkNull(String string1, String string2, String string3, String string4) { if (string1 != null) { @@ -443,11 +448,13 @@ public final class UtilFormatOut { } } - /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String. + /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, + * otherwise an empty but non-null String. * @param string1 The first passed String * @param string2 The second passed String * @param string3 The third passed String - * @return The first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String + * @return The first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, + * otherwise an empty but non-null String */ public static String checkEmpty(String string1, String string2, String string3) { if (UtilValidate.isNotEmpty(string1)) { @@ -559,7 +566,7 @@ public final class UtilFormatOut { return newString.toString(); } public static String makeSqlSafe(String unsafeString) { - return unsafeString.replaceAll("'","''"); + return unsafeString.replaceAll("'", "''"); } public static String formatPrintableCreditCard(String original) { @@ -571,10 +578,10 @@ public final class UtilFormatOut { } StringBuilder buffer = new StringBuilder(); - for (int i = 0; i < original.length()-4; i++) { + for (int i = 0; i < original.length() - 4; i++) { buffer.append('*'); } - buffer.append(original.substring(original.length()-4)); + buffer.append(original.substring(original.length() - 4)); return buffer.toString(); } } 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 0478712..642f9fc 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 @@ -1033,7 +1033,6 @@ public final class UtilHttp { /** * Encodes a query parameter - * * @throws UnsupportedEncodingException */ public static String getEncodedParameter(String parameter) throws UnsupportedEncodingException { @@ -1156,8 +1155,8 @@ public final class UtilHttp { // HTTP Strict-Transport-Security (HSTS) enforces secure (HTTP over SSL/TLS) connections to the server. String strictTransportSecurity = null; if (viewMap != null) { - xFrameOption = viewMap.xFrameOption; - strictTransportSecurity = viewMap.strictTransportSecurity; + xFrameOption = viewMap.getxFrameOption(); + strictTransportSecurity = viewMap.getStrictTransportSecurity(); } // Default to sameorigin if (UtilValidate.isNotEmpty(xFrameOption)) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java index 818769c..58bca03 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java @@ -70,9 +70,9 @@ public final class UtilProperties implements Serializable { /** * A cache for storing Properties instances. Each Properties instance is keyed by its URL. */ - private static final UtilCache<String, Properties> urlCache = UtilCache.createUtilCache("properties.UtilPropertiesUrlCache"); + private static final UtilCache<String, Properties> URL_CACHE = UtilCache.createUtilCache("properties.UtilPropertiesUrlCache"); - private static final Set<String> propertiesNotFound = new HashSet<>(); + private static final Set<String> PROP_NOT_FOUND = new HashSet<>(); /** Compares the specified property to the compareString, returns true if they are the same, false otherwise * @param resource The name of the resource - if the properties file is 'webevent.properties', the resource name is 'webevent' @@ -150,7 +150,7 @@ public final class UtilProperties implements Serializable { } catch (GeneralException e) { Debug.logWarning("Error converting String \"" + str + "\" to " + type + "; using defaultNumber " + defaultNumber + ".", MODULE); } - return defaultNumber; + return defaultNumber; } /** @@ -234,7 +234,8 @@ public final class UtilProperties implements Serializable { try { result = new BigInteger(strValue); } catch (NumberFormatException nfe) { - Debug.logWarning("Couldnt convert String \"" + strValue + "\" to BigInteger; using defaultNumber " + defaultNumber.toString() + ".", MODULE); + Debug.logWarning("Couldnt convert String \"" + strValue + "\" to BigInteger; using defaultNumber " + + defaultNumber.toString() + ".", MODULE); } return result; } @@ -253,7 +254,8 @@ public final class UtilProperties implements Serializable { try { result = new BigDecimal(strValue); } catch (NumberFormatException nfe) { - Debug.logWarning("Couldnt convert String \"" + strValue + "\" to BigDecimal; using defaultNumber " + defaultNumber.toString() + ".", MODULE); + Debug.logWarning("Couldnt convert String \"" + strValue + "\" to BigDecimal; using defaultNumber " + + defaultNumber.toString() + ".", MODULE); } return result; } @@ -342,11 +344,11 @@ public final class UtilProperties implements Serializable { return null; } String cacheKey = url.toString(); - Properties properties = urlCache.get(cacheKey); + Properties properties = URL_CACHE.get(cacheKey); if (properties == null) { try { properties = new ExtendedProperties(url, null); - urlCache.put(cacheKey, properties); + URL_CACHE.put(cacheKey, properties); } catch (Exception e) { Debug.logInfo(e, MODULE); } @@ -700,7 +702,7 @@ public final class UtilProperties implements Serializable { // Private lazy-initializer class private static class FallbackLocaleHolder { - private static final Locale fallbackLocale = getFallbackLocale(); + private static final Locale FALLBACK_LOCALE = getFallbackLocale(); private static Locale getFallbackLocale() { Locale fallbackLocale = null; @@ -722,7 +724,7 @@ public final class UtilProperties implements Serializable { * @return The configured fallback locale */ public static Locale getFallbackLocale() { - return FallbackLocaleHolder.fallbackLocale; + return FallbackLocaleHolder.FALLBACK_LOCALE; } /** Converts a Locale instance to a candidate Locale list. The list @@ -810,7 +812,7 @@ public final class UtilProperties implements Serializable { } public static boolean isPropertiesResourceNotFound(String resource, Locale locale, boolean removeExtension) { - return propertiesNotFound.contains(createResourceName(resource, locale, removeExtension)); + return PROP_NOT_FOUND.contains(createResourceName(resource, locale, removeExtension)); } /** @@ -841,7 +843,7 @@ public final class UtilProperties implements Serializable { throw new IllegalArgumentException("resource cannot be null or empty"); } String resourceName = createResourceName(resource, locale, false); - if (propertiesNotFound.contains(resourceName)) { + if (PROP_NOT_FOUND.contains(resourceName)) { return null; } boolean containsProtocol = resource.contains(":"); @@ -897,9 +899,9 @@ public final class UtilProperties implements Serializable { } catch (Exception e) { Debug.logInfo("Properties resolver: invalid URL - " + e.getMessage(), MODULE); } - if (propertiesNotFound.size() <= 300) { + if (PROP_NOT_FOUND.size() <= 300) { // Sanity check - list could get quite large - propertiesNotFound.add(resourceName); + PROP_NOT_FOUND.add(resourceName); } return null; } @@ -927,7 +929,8 @@ public final class UtilProperties implements Serializable { * @param properties Optional Properties object to populate * @return Properties instance or null if not found */ - public static Properties xmlToProperties(InputStream in, Locale locale, Properties properties) throws IOException, InvalidPropertiesFormatException { + public static Properties xmlToProperties(InputStream in, Locale locale, Properties properties) + throws IOException, InvalidPropertiesFormatException { if (in == null) { throw new IllegalArgumentException("InputStream cannot be null"); } @@ -948,12 +951,12 @@ public final class UtilProperties implements Serializable { throw new IllegalArgumentException("locale cannot be null"); } String localeString = locale.toString(); - String correctedLocaleString = localeString.replace('_','-'); + String correctedLocaleString = localeString.replace('_', '-'); for (Element property : propertyList) { // Support old way of specifying xml:lang value. // Old way: en_AU, new way: en-AU Element value = UtilXml.firstChildElement(property, "value", "xml:lang", correctedLocaleString); - if ( value == null) { + if (value == null) { value = UtilXml.firstChildElement(property, "value", "xml:lang", localeString); } if (value != null) { @@ -990,10 +993,10 @@ public final class UtilProperties implements Serializable { * properties file format. */ public static class UtilResourceBundle extends ResourceBundle { - private static final UtilCache<String, UtilResourceBundle> bundleCache = UtilCache.createUtilCache("properties.UtilPropertiesBundleCache"); - protected Properties properties = null; - protected Locale locale = null; - protected int hashCode = hashCode(); + private static final UtilCache<String, UtilResourceBundle> BUNDLE_CACHE = UtilCache.createUtilCache("properties.UtilPropertiesBundleCache"); + private Properties properties = null; + private Locale locale = null; + private int hashCode = hashCode(); protected UtilResourceBundle() { } @@ -1010,7 +1013,7 @@ public final class UtilProperties implements Serializable { public static ResourceBundle getBundle(String resource, Locale locale, ClassLoader loader) throws MissingResourceException { String resourceName = createResourceName(resource, locale, true); - UtilResourceBundle bundle = bundleCache.get(resourceName); + UtilResourceBundle bundle = BUNDLE_CACHE.get(resourceName); if (bundle == null) { double startTime = System.currentTimeMillis(); List<Locale> candidateLocales = getCandidateLocales(locale); @@ -1020,14 +1023,14 @@ public final class UtilProperties implements Serializable { Locale candidateLocale = candidateLocales.remove(candidateLocales.size() - 1); // ResourceBundles are connected together as a singly-linked list String lookupName = createResourceName(resource, candidateLocale, true); - UtilResourceBundle lookupBundle = bundleCache.get(lookupName); + UtilResourceBundle lookupBundle = BUNDLE_CACHE.get(lookupName); if (lookupBundle == null) { Properties newProps = getProperties(resource, candidateLocale); if (UtilValidate.isNotEmpty(newProps)) { // The last bundle we found becomes the parent of the new bundle parentBundle = bundle; bundle = new UtilResourceBundle(newProps, candidateLocale, parentBundle); - bundleCache.putIfAbsent(lookupName, bundle); + BUNDLE_CACHE.putIfAbsent(lookupName, bundle); numProperties = newProps.size(); } } else { @@ -1046,7 +1049,7 @@ public final class UtilProperties implements Serializable { Debug.logInfo("ResourceBundle " + resource + " (" + locale + ") created in " + totalTime / 1000.0 + "s with " + numProperties + " properties", MODULE); } - bundleCache.putIfAbsent(resourceName, bundle); + BUNDLE_CACHE.putIfAbsent(resourceName, bundle); } return bundle; } 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 29e6ea2..360bf0d 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 @@ -30,16 +30,16 @@ import java.util.concurrent.ConcurrentHashMap; public class UtilTimer { private static final String MODULE = UtilTimer.class.getName(); - protected static final ConcurrentHashMap<String, UtilTimer> staticTimers = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, UtilTimer> STATIC_TIMERS = new ConcurrentHashMap<>(); - protected String timerName = null; - protected String lastMessage = null; + private String timerName = null; + private String lastMessage = null; - protected long realStartTime; - protected long startTime; - protected long lastMessageTime; - protected boolean running = false; - protected boolean log = false; + private long realStartTime; + private long startTime; + private long lastMessageTime; + private boolean running = false; + private boolean log = false; public static UtilTimer makeTimer() { return new UtilTimer(); @@ -62,21 +62,33 @@ public class UtilTimer { } } + /** + * Start timer. + */ public void startTimer() { this.lastMessageTime = realStartTime = startTime = System.currentTimeMillis(); this.lastMessage = "Begin"; this.running = true; } + /** + * Gets name. + * @return the name + */ public String getName() { return this.timerName; } + /** + * Is running boolean. + * @return the boolean + */ public boolean isRunning() { return this.running; } - /** 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 + /** 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 * @return A String with the timing information, the timer String */ @@ -100,7 +112,8 @@ public class UtilTimer { StringBuilder retBuf = new StringBuilder(); retBuf.append("[[").append(message).append("- total:").append(secondsSinceStart()); if (lastMessage != null) { - retBuf.append(",since last(").append(((lastMessage.length() > 20) ? (lastMessage.substring(0, 17) + "...") : lastMessage)).append("):").append(secondsSinceLast()); + retBuf.append(",since last(").append(((lastMessage.length() > 20) ? (lastMessage.substring(0, 17) + "...") + : lastMessage)).append("):").append(secondsSinceLast()); } retBuf.append("]]"); @@ -177,7 +190,8 @@ public class UtilTimer { * @return A String with the timing information, the timer String */ public String timerString(int level, String message) { - // String retString = "[[" + message + ": seconds since start: " + secondsSinceStart() + ",since last(" + lastMessage + "):" + secondsSinceLast() + "]]"; + // String retString = "[[" + message + ": seconds since start: " + secondsSinceStart() + ",since last(" + lastMessage + "):" + // + secondsSinceLast() + "]]"; StringBuilder retStringBuf = new StringBuilder(); @@ -216,12 +230,12 @@ public class UtilTimer { } public static UtilTimer getTimer(String timerName, boolean log) { - UtilTimer timer = staticTimers.get(timerName); + UtilTimer timer = STATIC_TIMERS.get(timerName); if (timer == null) { timer = new UtilTimer(timerName, false); timer.setLog(log); - staticTimers.putIfAbsent(timerName, timer); - timer = staticTimers.get(timerName); + STATIC_TIMERS.putIfAbsent(timerName, timer); + timer = STATIC_TIMERS.get(timerName); } return timer; } @@ -252,6 +266,6 @@ public class UtilTimer { if (message != null) { UtilTimer.timerLog(timerName, message, className); } - staticTimers.remove(timerName); + STATIC_TIMERS.remove(timerName); } } 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 5fbf02d..3ffbae1 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 @@ -67,47 +67,47 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C private static final String MODULE = UtilCache.class.getName(); /** A static Map to keep track of all of the UtilCache instances. */ - private static final ConcurrentHashMap<String, UtilCache<?, ?>> utilCacheTable = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, UtilCache<?, ?>> UTIL_CACHE_TABLE = new ConcurrentHashMap<>(); /** An index number appended to utilCacheTable names when there are conflicts. */ - private static final ConcurrentHashMap<String, AtomicInteger> defaultIndices = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, AtomicInteger> DEFAULT_INDICES = new ConcurrentHashMap<>(); /** The name of the UtilCache instance, is also the key for the instance in utilCacheTable. */ private final String name; /** A count of the number of cache hits */ - protected AtomicLong hitCount = new AtomicLong(0); + private AtomicLong hitCount = new AtomicLong(0); /** A count of the number of cache misses because it is not found in the cache */ - protected AtomicLong missCountNotFound = new AtomicLong(0); + private AtomicLong missCountNotFound = new AtomicLong(0); /** A count of the number of cache misses because it expired */ - protected AtomicLong missCountExpired = new AtomicLong(0); + private AtomicLong missCountExpired = new AtomicLong(0); /** A count of the number of cache misses because it was cleared from the Soft Reference (ie garbage collection, etc) */ - protected AtomicLong missCountSoftRef = new AtomicLong(0); + private AtomicLong missCountSoftRef = new AtomicLong(0); /** A count of the number of cache hits on removes */ - protected AtomicLong removeHitCount = new AtomicLong(0); + private AtomicLong removeHitCount = new AtomicLong(0); /** A count of the number of cache misses on removes */ - protected AtomicLong removeMissCount = new AtomicLong(0); + private AtomicLong removeMissCount = new AtomicLong(0); /** The maximum number of elements in the cache. * If set to 0, there will be no limit on the number of elements in the cache. */ - protected int sizeLimit = 0; - protected int maxInMemory = 0; + private int sizeLimit = 0; + private int maxInMemory = 0; /** Specifies the amount of time since initial loading before an element will be reported as expired. * If set to 0, elements will never expire. */ - protected long expireTimeNanos = 0; + private long expireTimeNanos = 0; /** Specifies whether or not to use soft references for this cache, defaults to false */ - protected boolean useSoftReference = false; + private boolean useSoftReference = false; /** The set of listeners to receive notifications when items are modified (either deliberately or because they were expired). */ - protected Set<CacheListener<K, V>> listeners = new CopyOnWriteArraySet<>(); + private Set<CacheListener<K, V>> listeners = new CopyOnWriteArraySet<>(); - protected ConcurrentMap<Object, CacheLine<V>> memoryTable = null; + private ConcurrentMap<Object, CacheLine<V>> memoryTable = null; /** Constructor which specifies the cacheName as well as the sizeLimit, expireTime and useSoftReference. * The passed sizeLimit, expireTime and useSoftReference will be overridden by values from cache.properties if found. @@ -116,7 +116,8 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C * @param cacheName The name of the cache. * @param useSoftReference Specifies whether or not to use soft references for this cache. */ - private UtilCache(String cacheName, int sizeLimit, int maxInMemory, long expireTimeMillis, boolean useSoftReference, String propName, String... propNames) { + private UtilCache(String cacheName, int sizeLimit, int maxInMemory, long expireTimeMillis, boolean useSoftReference, + String propName, String... propNames) { this.name = cacheName; this.sizeLimit = sizeLimit; this.maxInMemory = maxInMemory; @@ -139,10 +140,10 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C } private static String getNextDefaultIndex(String cacheName) { - AtomicInteger curInd = defaultIndices.get(cacheName); + AtomicInteger curInd = DEFAULT_INDICES.get(cacheName); if (curInd == null) { - defaultIndices.putIfAbsent(cacheName, new AtomicInteger(0)); - curInd = defaultIndices.get(cacheName); + DEFAULT_INDICES.putIfAbsent(cacheName, new AtomicInteger(0)); + curInd = DEFAULT_INDICES.get(cacheName); } int i = curInd.getAndIncrement(); return i == 0 ? "" : Integer.toString(i); @@ -374,14 +375,16 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C return UtilObject.getByteCount(o); } if (Debug.verboseOn()) { - Debug.logVerbose("Unable to compute memory size for non serializable object; returning 0 byte size for object of " + o.getClass(), MODULE); + Debug.logVerbose("Unable to compute memory size for non serializable object; returning 0 byte size for object of " + + o.getClass(), MODULE); } return 0; } catch (NotSerializableException e) { // this happens when we try to get the byte count for an object which itself is // serializable, but fails to be serialized, such as a map holding unserializable objects if (Debug.warningOn()) { - Debug.logWarning("NotSerializableException while computing memory size; returning 0 byte size for object of " + e.getMessage(), MODULE); + Debug.logWarning("NotSerializableException while computing memory size; returning 0 byte size for object of " + e.getMessage(), + MODULE); } return 0; } catch (Exception e) { @@ -463,14 +466,14 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C /** Removes all elements from this cache */ public static void clearAllCaches() { // We make a copy since clear may take time - for (UtilCache<?, ?> cache : utilCacheTable.values()) { + for (UtilCache<?, ?> cache : UTIL_CACHE_TABLE.values()) { cache.clear(); } } public static Set<String> getUtilCacheTableKeySet() { - Set<String> set = new HashSet<>(utilCacheTable.size()); - set.addAll(utilCacheTable.keySet()); + Set<String> set = new HashSet<>(UTIL_CACHE_TABLE.size()); + set.addAll(UTIL_CACHE_TABLE.keySet()); return set; } @@ -544,7 +547,7 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C ((ConcurrentLinkedHashMap<?, ?>) this.memoryTable).setCapacity(newInMemory); return; } - this.memoryTable =new Builder<Object, CacheLine<V>>() + this.memoryTable = new Builder<Object, CacheLine<V>>() .maximumWeightedCapacity(newInMemory) .build(); } else { @@ -715,7 +718,7 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C } public static void clearCachesThatStartWith(String startsWith) { - for (Map.Entry<String, UtilCache<?, ?>> entry: utilCacheTable.entrySet()) { + for (Map.Entry<String, UtilCache<?, ?>> entry: UTIL_CACHE_TABLE.entrySet()) { String name = entry.getKey(); if (name.startsWith(startsWith)) { UtilCache<?, ?> cache = entry.getValue(); @@ -733,18 +736,20 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C } @SuppressWarnings("unchecked") - public static <K, V> UtilCache<K, V> getOrCreateUtilCache(String name, int sizeLimit, int maxInMemory, long expireTime, boolean useSoftReference, String... names) { - UtilCache<K, V> existingCache = (UtilCache<K, V>) utilCacheTable.get(name); + public static <K, V> UtilCache<K, V> getOrCreateUtilCache(String name, int sizeLimit, int maxInMemory, long expireTime, + boolean useSoftReference, String... names) { + UtilCache<K, V> existingCache = (UtilCache<K, V>) UTIL_CACHE_TABLE.get(name); if (existingCache != null) { return existingCache; } String cacheName = name + getNextDefaultIndex(name); UtilCache<K, V> newCache = new UtilCache<>(cacheName, sizeLimit, maxInMemory, expireTime, useSoftReference, name, names); - utilCacheTable.putIfAbsent(name, newCache); - return (UtilCache<K, V>) utilCacheTable.get(name); + UTIL_CACHE_TABLE.putIfAbsent(name, newCache); + return (UtilCache<K, V>) UTIL_CACHE_TABLE.get(name); } - public static <K, V> UtilCache<K, V> createUtilCache(String name, int sizeLimit, int maxInMemory, long expireTime, boolean useSoftReference, String... names) { + public static <K, V> UtilCache<K, V> createUtilCache(String name, int sizeLimit, int maxInMemory, long expireTime, + boolean useSoftReference, String... names) { String cacheName = name + getNextDefaultIndex(name); return storeCache(new UtilCache<>(cacheName, sizeLimit, maxInMemory, expireTime, useSoftReference, name, names)); } @@ -785,13 +790,13 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C } private static <K, V> UtilCache<K, V> storeCache(UtilCache<K, V> cache) { - utilCacheTable.put(cache.getName(), cache); + UTIL_CACHE_TABLE.put(cache.getName(), cache); return cache; } @SuppressWarnings("unchecked") public static <K, V> UtilCache<K, V> findCache(String cacheName) { - return (UtilCache<K, V>) UtilCache.utilCacheTable.get(cacheName); + return (UtilCache<K, V>) UtilCache.UTIL_CACHE_TABLE.get(cacheName); } @Override diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/FlexibleServletAccessor.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/FlexibleServletAccessor.java index 38dc2b8..42ea403 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/FlexibleServletAccessor.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/FlexibleServletAccessor.java @@ -38,11 +38,11 @@ import org.apache.ofbiz.base.util.string.FlexibleStringExpander; @SuppressWarnings("serial") public class FlexibleServletAccessor<T> implements Serializable { - protected String name; - protected String attributeName; - protected FlexibleMapAccessor<T> fma; - protected boolean needsExpand; - protected boolean empty; + private String name; + private String attributeName; + private FlexibleMapAccessor<T> fma; + private boolean needsExpand; + private boolean empty; public FlexibleServletAccessor(String name) { init(name); @@ -56,6 +56,10 @@ public class FlexibleServletAccessor<T> implements Serializable { } } + /** + * Init. + * @param name the name + */ protected void init(String name) { this.name = name; if (UtilValidate.isEmpty(name)) { @@ -85,6 +89,10 @@ public class FlexibleServletAccessor<T> implements Serializable { } } + /** + * Is empty boolean. + * @return the boolean + */ public boolean isEmpty() { return this.empty; } @@ -196,17 +204,18 @@ public class FlexibleServletAccessor<T> implements Serializable { } protected static class AttributeAccessor<T> implements Serializable { - protected Map<String, Object> expandContext; - protected String attributeName; - protected FlexibleMapAccessor<T> fma; - protected boolean isListReference; - protected boolean isAddAtIndex; - protected boolean isAddAtEnd; - protected int listIndex; - protected int openBrace; - protected int closeBrace; - - public AttributeAccessor(String origName, Map<String, Object> expandContext, String defAttributeName, FlexibleMapAccessor<T> defFma, boolean needsExpand) { + private Map<String, Object> expandContext; + private String attributeName; + private FlexibleMapAccessor<T> fma; + private boolean isListReference; + private boolean isAddAtIndex; + private boolean isAddAtEnd; + private int listIndex; + private int openBrace; + private int closeBrace; + + public AttributeAccessor(String origName, Map<String, Object> expandContext, String defAttributeName, + FlexibleMapAccessor<T> defFma, boolean needsExpand) { attributeName = defAttributeName; fma = defFma; @@ -248,6 +257,11 @@ public class FlexibleServletAccessor<T> implements Serializable { } + /** + * Get t. + ** @param request the request + * @return the t + */ public T get(ServletRequest request) { Object theValue = null; if (isListReference) { @@ -263,6 +277,11 @@ public class FlexibleServletAccessor<T> implements Serializable { return UtilGenerics.<T>cast(theValue); } + /** + * Get t. + * @param session the session + * @return the t + */ public T get(HttpSession session) { Object theValue = null; if (isListReference) { @@ -278,6 +297,11 @@ public class FlexibleServletAccessor<T> implements Serializable { return UtilGenerics.<T>cast(theValue); } + /** + * Put in list. + * @param lst the lst + * @param value the value + */ protected void putInList(List<T> lst, T value) { //if brackets are empty, append to list if (isAddAtEnd) { @@ -291,6 +315,11 @@ public class FlexibleServletAccessor<T> implements Serializable { } } + /** + * Put. + * @param request the request + * @param value the value + */ public void put(ServletRequest request, T value) { if (fma == null) { if (isListReference) { @@ -310,6 +339,11 @@ public class FlexibleServletAccessor<T> implements Serializable { } } + /** + * Put. + * @param session the session + * @param value the value + */ public void put(HttpSession session, T value) { if (fma == null) { if (isListReference) { @@ -329,6 +363,11 @@ public class FlexibleServletAccessor<T> implements Serializable { } } + /** + * Remove t. + * @param request the request + * @return the t + */ public T remove(ServletRequest request) { if (fma != null) { Object theObj = request.getAttribute(attributeName); @@ -347,6 +386,11 @@ public class FlexibleServletAccessor<T> implements Serializable { return UtilGenerics.<T>cast(theValue); } + /** + * Remove t. + * @param session the session + * @return the t + */ public T remove(HttpSession session) { if (fma != null) { Object theObj = session.getAttribute(attributeName); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMapEntry.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMapEntry.java index 9caaed4..b1790a1 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMapEntry.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/GenericMapEntry.java @@ -24,9 +24,9 @@ import java.util.Objects; import org.apache.ofbiz.base.util.UtilObject; public class GenericMapEntry<K, V> implements Map.Entry<K, V> { - protected final GenericMap<K, V> map; - protected final K key; - protected final boolean noteAccess; + private final GenericMap<K, V> map; + private final K key; + private final boolean noteAccess; public GenericMapEntry(GenericMap<K, V> map, K key, boolean noteAccess) { this.map = map; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/PagedList.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/PagedList.java index 6141ba6..34f80fd 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/PagedList.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/PagedList.java @@ -28,12 +28,12 @@ import java.util.List; */ public class PagedList<E> implements Iterable<E> { - protected int startIndex; - protected int endIndex; - protected int size; - protected int viewIndex; - protected int viewSize; - protected List<E> data; + private int startIndex; + private int endIndex; + private int size; + private int viewIndex; + private int viewSize; + private List<E> data; /** * Default constructor - populates all fields in this class diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/ResourceBundleMapWrapper.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/ResourceBundleMapWrapper.java index a209e17..3389185 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/ResourceBundleMapWrapper.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/ResourceBundleMapWrapper.java @@ -39,23 +39,25 @@ import org.apache.ofbiz.service.calendar.TemporalExpressions.Frequency; public class ResourceBundleMapWrapper implements Map<String, Object>, Serializable { private static final String MODULE = Frequency.class.getName(); - protected MapStack<String> rbmwStack; - protected ResourceBundle initialResourceBundle; - protected Map<String, Object> context; + private MapStack<String> rbmwStack; + private ResourceBundle initialResourceBundle; + private Map<String, Object> context; protected ResourceBundleMapWrapper() { rbmwStack = MapStack.create(); } /** - * When creating new from a InternalRbmWrapper the one passed to the constructor should be the most specific or local InternalRbmWrapper, with more common ones pushed onto the stack progressively. + * When creating new from a InternalRbmWrapper the one passed to the constructor should be the most specific or local InternalRbmWrapper, + * with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(InternalRbmWrapper initialInternalRbmWrapper) { this.initialResourceBundle = initialInternalRbmWrapper.getResourceBundle(); this.rbmwStack = MapStack.create(initialInternalRbmWrapper); } - /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, with more common ones pushed onto the stack progressively. + /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, + * with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(ResourceBundle initialResourceBundle) { if (initialResourceBundle == null) { @@ -65,7 +67,8 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab this.rbmwStack = MapStack.create(new InternalRbmWrapper(initialResourceBundle)); } - /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, with more common ones pushed onto the stack progressively. + /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, + * with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(ResourceBundle initialResourceBundle, Map<String, Object> context) { if (initialResourceBundle == null) { @@ -76,12 +79,14 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab this.context = context; } - /** Puts ResourceBundle on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, ie everything else already there) */ + /** Puts ResourceBundle on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, + * ie everything else already there) */ public void addBottomResourceBundle(ResourceBundle topResourceBundle) { this.rbmwStack.addToBottom(new InternalRbmWrapper(topResourceBundle)); } - /** Puts InternalRbmWrapper on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, ie everything else already there) */ + /** Puts InternalRbmWrapper on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, + * ie everything else already there) */ public void addBottomResourceBundle(InternalRbmWrapper topInternalRbmWrapper) { this.rbmwStack.addToBottom(topInternalRbmWrapper); } @@ -89,7 +94,8 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab /** Don't pass the locale to make sure it has the same locale as the base */ public void addBottomResourceBundle(String resource) { if (this.initialResourceBundle == null) { - throw new IllegalArgumentException("Cannot add bottom resource bundle, this wrapper was not properly initialized (there is no base/initial ResourceBundle)."); + throw new IllegalArgumentException("Cannot add bottom resource bundle, this wrapper was not properly initialized" + + "(there is no base/initial ResourceBundle)."); } this.addBottomResourceBundle(new InternalRbmWrapper(UtilProperties.getResourceBundle(resource, this.initialResourceBundle.getLocale()))); } @@ -101,6 +107,10 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab this.rbmwStack.push(new InternalRbmWrapper(topResourceBundle)); } + /** + * Gets initial resource bundle. + * @return the initial resource bundle + */ public ResourceBundle getInitialResourceBundle() { return this.initialResourceBundle; } @@ -166,8 +176,8 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab } public static class InternalRbmWrapper implements Map<String, Object>, Serializable { - protected ResourceBundle resourceBundle; - protected Map<String, Object> topLevelMap; + private ResourceBundle resourceBundle; + private Map<String, Object> topLevelMap; private boolean isMapInitialized = false; public InternalRbmWrapper(ResourceBundle resourceBundle) { @@ -205,7 +215,7 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab public int size() { if (isMapInitialized) { // this is an approximate size, won't include elements from parent bundles - return topLevelMap.size() -1; + return topLevelMap.size() - 1; } return resourceBundle.keySet().size(); } @@ -303,6 +313,10 @@ public class ResourceBundleMapWrapper implements Map<String, Object>, Serializab return this.topLevelMap.entrySet(); } + /** + * Gets resource bundle. + * @return the resource bundle + */ public ResourceBundle getResourceBundle() { return this.resourceBundle; } 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 fbacbb7..9f5828e 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 @@ -419,7 +419,7 @@ public class CatalinaContainer implements Container { private static Connector prepareConnector(Configuration.Property connectorProp) { Connector connector = new Connector(ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1")); - connector.setPort(ContainerConfig.getPropertyValue(connectorProp, "port", 0) + Start.getInstance().getConfig().portOffset); + connector.setPort(ContainerConfig.getPropertyValue(connectorProp, "port", 0) + Start.getInstance().getConfig().getPortOffset()); if ("true".equals(ContainerConfig.getPropertyValue(connectorProp, "upgradeProtocol", "false"))) { connector.addUpgradeProtocol(new Http2Protocol()); Debug.logInfo("Tomcat " + connector + ": enabled HTTP/2", MODULE); diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/authentication/example/TestFailAuthenticator.java b/framework/common/src/main/java/org/apache/ofbiz/common/authentication/example/TestFailAuthenticator.java index 82fadcc..f1e2868 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/authentication/example/TestFailAuthenticator.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/authentication/example/TestFailAuthenticator.java @@ -31,9 +31,9 @@ import org.apache.ofbiz.service.LocalDispatcher; public class TestFailAuthenticator implements Authenticator { private static final String MODULE = TestFailAuthenticator.class.getName(); - protected Delegator delegator; - protected LocalDispatcher dispatcher; - protected float weight = 1; + private Delegator delegator; + private LocalDispatcher dispatcher; + private float weight = 1; /** * Method called when authenticator is first initialized (the delegator diff --git a/framework/common/src/main/java/org/apache/ofbiz/common/scripting/ScriptHelperImpl.java b/framework/common/src/main/java/org/apache/ofbiz/common/scripting/ScriptHelperImpl.java index e5729dc..b081b3f 100644 --- a/framework/common/src/main/java/org/apache/ofbiz/common/scripting/ScriptHelperImpl.java +++ b/framework/common/src/main/java/org/apache/ofbiz/common/scripting/ScriptHelperImpl.java @@ -78,7 +78,8 @@ public final class ScriptHelperImpl implements ScriptHelper { fieldsToSelect = new HashSet<>(selectFieldList); } if (fieldsToSelect != null && useCache) { - String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method: Cannot specify selectFieldList argument when useCache is set to true "; + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method:" + + "Cannot specify selectFieldList argument when useCache is set to true "; Debug.logWarning(errMsg, MODULE); throw new ScriptException(errMsg); } @@ -102,7 +103,8 @@ public final class ScriptHelperImpl implements ScriptHelper { } } else { if (Debug.warningOn()) { - Debug.logWarning("Error running script " + ctxHelper.getScriptName() + ": Returning null because found incomplete primary key in find: " + entityPK, MODULE); + Debug.logWarning("Error running script " + ctxHelper.getScriptName() + ": Returning null because found incomplete" + + "primary key in find: " + entityPK, MODULE); } } return valueOut; @@ -122,11 +124,13 @@ public final class ScriptHelperImpl implements ScriptHelper { try { modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName); } catch (GenericServiceException e) { - String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the createServiceMap method: get service definition for service name [" + serviceName + "]: " + e.getMessage(); + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the createServiceMap method: get service" + + "definition for service name [" + serviceName + "]: " + e.getMessage(); Debug.logWarning(e, errMsg, MODULE); throw new ScriptException(errMsg); } - toMap.putAll(modelService.makeValid(inputMap, ModelService.IN_PARAM, true, UtilGenerics.cast(ctxHelper.getErrorMessages()), ctxHelper.getTimeZone(), ctxHelper.getLocale())); + toMap.putAll(modelService.makeValid(inputMap, ModelService.IN_PARAM, true, UtilGenerics.cast(ctxHelper.getErrorMessages()), + ctxHelper.getTimeZone(), ctxHelper.getLocale())); return toMap; } @@ -172,7 +176,8 @@ public final class ScriptHelperImpl implements ScriptHelper { } @Override - public Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) throws ScriptException { + public Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) + throws ScriptException { Assert.notNull("entityName", entityName); if (args == null) { args = EMPTY_ARGS; @@ -182,7 +187,8 @@ public final class ScriptHelperImpl implements ScriptHelper { List<String> selectFieldList = UtilGenerics.cast(args.get("selectFieldList")); ModelEntity modelEntity = ctxHelper.getDelegator().getModelEntity(entityName); if (modelEntity == null) { - throw new ScriptException("Error running script " + ctxHelper.getScriptName() + " - no entity definition found for entity name [" + entityName + "]"); + throw new ScriptException("Error running script " + ctxHelper.getScriptName() + " - no entity definition found for entity name [" + + entityName + "]"); } return runFindByPrimaryKey(modelEntity, ctxHelper, useCache, autoFieldMap, fields, selectFieldList); } @@ -221,7 +227,8 @@ public final class ScriptHelperImpl implements ScriptHelper { } @Override - public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException { + public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) + throws ScriptException { Assert.notNull("serviceName", serviceName, "args", args); boolean includeUserLogin = !"false".equals(args.get("includeUserLoginStr")); String requireNewTransactionStr = (String) args.get("requireNewTransaction"); @@ -256,8 +263,8 @@ public final class ScriptHelperImpl implements ScriptHelper { result = ctxHelper.getDispatcher().runSync(serviceName, inMap); } else { ModelService modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName); - boolean requireNewTransaction = modelService.requireNewTransaction; - int timeout = modelService.transactionTimeout; + boolean requireNewTransaction = modelService.isRequireNewTransaction(); + int timeout = modelService.getTransactionTimeout(); if (UtilValidate.isNotEmpty(requireNewTransactionStr)) { requireNewTransaction = "true".equals(requireNewTransactionStr); } @@ -267,7 +274,8 @@ public final class ScriptHelperImpl implements ScriptHelper { result = ctxHelper.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction); } } catch (GenericServiceException e) { - String errMsg = "Error running script " + ctxHelper.getScriptName() + " [problem invoking the [" + serviceName + "] service: " + e.getMessage(); + String errMsg = "Error running script " + ctxHelper.getScriptName() + " [problem invoking the [" + serviceName + "] service: " + + e.getMessage(); Debug.logWarning(e, errMsg, MODULE); throw new ScriptException(errMsg); } 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 2a9fa38..3e34097 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 @@ -96,43 +96,48 @@ public class GenericDelegator implements Delegator { private static final String MODULE = GenericDelegator.class.getName(); - protected ModelReader modelReader = null; - protected ModelGroupReader modelGroupReader = null; - /** This flag is only here for lower level technical testing, it shouldn't be user configurable (or at least I don't think so yet); when true all operations without a transaction will be wrapped in one; seems to be necessary for some (all?) XA aware connection pools, and should improve overall stability and consistency */ - public static final boolean alwaysUseTransaction = true; + private ModelReader modelReader = null; + private ModelGroupReader modelGroupReader = null; + /** This flag is only here for lower level technical testing, it shouldn't be user configurable (or at least I don't think so yet); + * when true all operations without a transaction will be wrapped in one; seems to be necessary for some (all?) XA aware connection pools, + * and should improve overall stability and consistency */ + private static final boolean ALWAYS_USE_TRANS = true; // TODO should this is be handled by tenant? - public static final boolean saveEntitySyncRemoveInfo = UtilProperties.getPropertyAsBoolean("general", "saveEntitySyncRemove", false); + private static final boolean SAVE_ENTITY_SYNC_REMOVE_INFO = UtilProperties.getPropertyAsBoolean("general", "saveEntitySyncRemove", false); - protected String delegatorBaseName = null; - protected String delegatorFullName = null; - protected String delegatorTenantId = null; + private String delegatorBaseName = null; + private String delegatorFullName = null; + private String delegatorTenantId = null; private String originalDelegatorName = null; - protected DelegatorElement delegatorInfo = null; + private DelegatorElement delegatorInfo = null; - protected Cache cache = null; + private Cache cache = null; - protected final AtomicReference<Future<DistributedCacheClear>> distributedCacheClear = new AtomicReference<>(); - protected boolean warnNoEcaHandler = false; - protected final AtomicReference<Future<EntityEcaHandler<?>>> entityEcaHandler = new AtomicReference<>(); - protected final AtomicReference<SequenceUtil> AtomicRefSequencer = new AtomicReference<>(null); - protected EntityCrypto crypto = null; + private final AtomicReference<Future<DistributedCacheClear>> distributedCacheClear = new AtomicReference<>(); + private boolean warnNoEcaHandler = false; + private final AtomicReference<Future<EntityEcaHandler<?>>> entityEcaHandler = new AtomicReference<>(); + private final AtomicReference<SequenceUtil> atomicRefSequence = new AtomicReference<>(null); + private EntityCrypto crypto = null; - /** A ThreadLocal variable to allow other methods to specify a user identifier (usually the userLoginId, though technically the Entity Engine doesn't know anything about the UserLogin entity) */ - private static final ThreadLocal<List<String>> userIdentifierStack = new ThreadLocal<>(); - /** A ThreadLocal variable to allow other methods to specify a session identifier (usually the visitId, though technically the Entity Engine doesn't know anything about the Visit entity) */ - private static final ThreadLocal<List<String>> sessionIdentifierStack = new ThreadLocal<>(); + /** A ThreadLocal variable to allow other methods to specify a user identifier (usually the userLoginId, though technically the Entity Engine + * doesn't know anything about the UserLogin entity) */ + private static final ThreadLocal<List<String>> USE_DENTIFIER_STACK = new ThreadLocal<>(); + /** A ThreadLocal variable to allow other methods to specify a session identifier (usually the visitId, though technically the Entity Engine + * doesn't know anything about the Visit entity) */ + private static final ThreadLocal<List<String>> SESSION_IDENTIFIER_STACK = new ThreadLocal<>(); private boolean testMode = false; private boolean testRollbackInProgress = false; - private static final AtomicReferenceFieldUpdater<GenericDelegator, LinkedBlockingDeque<?>> testOperationsUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericDelegator.class, LinkedBlockingDeque.class, "testOperations")); + private static final AtomicReferenceFieldUpdater<GenericDelegator, LinkedBlockingDeque<?>> TEST_OPERATIONS_UPDATER = + UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericDelegator.class, LinkedBlockingDeque.class, "testOperations")); private volatile LinkedBlockingDeque<TestOperation> testOperations = null; protected static List<String> getUserIdentifierStack() { - List<String> curValList = userIdentifierStack.get(); + List<String> curValList = USE_DENTIFIER_STACK.get(); if (curValList == null) { curValList = new LinkedList<>(); - userIdentifierStack.set(curValList); + USE_DENTIFIER_STACK.set(curValList); } return curValList; } @@ -159,10 +164,10 @@ public class GenericDelegator implements Delegator { } protected static List<String> getSessionIdentifierStack() { - List<String> curValList = sessionIdentifierStack.get(); + List<String> curValList = SESSION_IDENTIFIER_STACK.get(); if (curValList == null) { curValList = new LinkedList<>(); - sessionIdentifierStack.set(curValList); + SESSION_IDENTIFIER_STACK.set(curValList); } return curValList; } @@ -206,11 +211,14 @@ public class GenericDelegator implements Delegator { Delegator baseDelegator = DelegatorFactory.getDelegator(this.delegatorBaseName); GenericValue tenant = EntityQuery.use(baseDelegator).from("Tenant").where("tenantId", this.delegatorTenantId).cache(true).queryOne(); if (tenant == null) { - throw new GenericEntityException("No Tenant record found for delegator [" + this.delegatorFullName + "] with tenantId [" + this.delegatorTenantId + "]"); + throw new GenericEntityException("No Tenant record found for delegator [" + this.delegatorFullName + "] with tenantId [" + + this.delegatorTenantId + "]"); } else if ("Y".equals(tenant.getString("disabled"))) { - throw new GenericEntityException("No Tenant record found for delegator [" + this.delegatorFullName + "] with tenantId [" + this.delegatorTenantId + "]"); + throw new GenericEntityException("No Tenant record found for delegator [" + this.delegatorFullName + "] with tenantId [" + + this.delegatorTenantId + "]"); } - GenericValue kekValue = EntityQuery.use(baseDelegator).from("TenantKeyEncryptingKey").where("tenantId", getDelegatorTenantId()).cache(true).queryOne(); + GenericValue kekValue = EntityQuery.use(baseDelegator).from("TenantKeyEncryptingKey").where("tenantId", getDelegatorTenantId()) + .cache(true).queryOne(); if (kekValue != null) { kekText = kekValue.getString("kekText"); } else { @@ -244,8 +252,8 @@ public class GenericDelegator implements Delegator { } ExecutionPool.getAllFutures(futures); - // NOTE: doing some things before the ECAs and such to make sure it is in place just in case it is used in a service engine startup thing or something - + // NOTE: doing some things before the ECAs and such to make sure it is in place just in case it is used in a service engine startup thing or + // something // setup the crypto class; this also after the delegator is in the cache otherwise we get infinite recursion this.crypto = new EntityCrypto(this, kekText); } @@ -254,14 +262,16 @@ public class GenericDelegator implements Delegator { GenericHelperInfo helperInfo = this.getGroupHelperInfo(groupName); if (helperInfo == null) { if (Debug.infoOn()) { - Debug.logInfo("Delegator \"" + delegatorFullName + "\" NOT initializing helper for entity group \"" + groupName + "\" because the group is not associated to this delegator.", MODULE); + Debug.logInfo("Delegator \"" + delegatorFullName + "\" NOT initializing helper for entity group \"" + groupName + + "\" because the group is not associated to this delegator.", MODULE); } return; } String helperBaseName = helperInfo.getHelperBaseName(); if (Debug.infoOn()) { - Debug.logInfo("Delegator \"" + delegatorFullName + "\" initializing helper \"" + helperBaseName + "\" for entity group \"" + groupName + "\".", MODULE); + Debug.logInfo("Delegator \"" + delegatorFullName + "\" initializing helper \"" + helperBaseName + "\" for entity group \"" + + groupName + "\".", MODULE); } if (UtilValidate.isNotEmpty(helperInfo.getHelperFullName())) { // pre-load field type defs, the return value is ignored @@ -273,7 +283,8 @@ public class GenericDelegator implements Delegator { Datasource datasource = EntityConfig.getDatasource(helperBaseName); if (datasource.getCheckOnStart()) { if (Debug.infoOn()) { - Debug.logInfo("Doing database check as requested in entityengine.xml with addMissing=" + datasource.getAddMissingOnStart(), MODULE); + Debug.logInfo("Doing database check as requested in entityengine.xml with addMissing=" + + datasource.getAddMissingOnStart(), MODULE); } helper.checkDataSource(this.getModelEntityMapByGroup(groupName), null, datasource.getAddMissingOnStart()); } @@ -283,6 +294,11 @@ public class GenericDelegator implements Delegator { } } + /** + * Create helper callable callable. + * @param groupName the group name + * @return the callable + */ protected Callable<Void> createHelperCallable(final String groupName) { return () -> { initializeOneGenericHelper(groupName); @@ -290,6 +306,10 @@ public class GenericDelegator implements Delegator { }; } + /** + * Sets delegator names. + * @param delegatorFullName the delegator full name + */ protected void setDelegatorNames(String delegatorFullName) { this.delegatorFullName = delegatorFullName; @@ -320,6 +340,10 @@ public class GenericDelegator implements Delegator { } } + /** + * Create entity eca handler entity eca handler. + * @return the entity eca handler + */ protected EntityEcaHandler<?> createEntityEcaHandler() { // If useEntityEca is false do nothing: the entityEcaHandler member field with a null value would cause its code to do nothing if (this.delegatorInfo.getEntityEcaEnabled()) { @@ -334,9 +358,11 @@ public class GenericDelegator implements Delegator { entityEcaHandler.setDelegator(this); return entityEcaHandler; } catch (ReflectiveOperationException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " was not found, Entity ECA Rules will be disabled", MODULE); + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + + " was not found, Entity ECA Rules will be disabled", MODULE); } catch (ClassCastException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " does not implement the EntityEcaHandler interface, Entity ECA Rules will be disabled", MODULE); + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + + " does not implement the EntityEcaHandler interface, Entity ECA Rules will be disabled", MODULE); } } else if (!this.warnNoEcaHandler) { Debug.logInfo("Entity ECA Handler disabled for delegator [" + delegatorFullName + "]", MODULE); @@ -447,7 +473,8 @@ public class GenericDelegator implements Delegator { } } catch (GenericEntityException ex) { errorCount++; - Debug.logError("Entity [" + entityName + "] named in Entity Group with name " + groupName + " are not defined in any Entity Definition file", MODULE); + Debug.logError("Entity [" + entityName + "] named in Entity Group with name " + groupName + + " are not defined in any Entity Definition file", MODULE); } } @@ -476,7 +503,8 @@ public class GenericDelegator implements Delegator { return null; } if (UtilValidate.isNotEmpty(this.delegatorTenantId) && "org.apache.ofbiz.tenant".equals(entityGroupName)) { - Debug.logInfo("Can't access entity of entityGroup = " + entityGroupName + " using tenant delegator "+ this.getDelegatorName()+", use base delegator instead", MODULE); + Debug.logInfo("Can't access entity of entityGroup = " + entityGroupName + " using tenant delegator " + this.getDelegatorName() + + ", use base delegator instead", MODULE); return null; } @@ -484,10 +512,12 @@ public class GenericDelegator implements Delegator { if (UtilValidate.isNotEmpty(this.delegatorTenantId)) { // get the JDBC parameters from the DB for the entityGroupName and tenantId try { - // NOTE: instead of caching the GenericHelpInfo object do a cached query here and create a new object each time, will avoid issues when the database data changes during run time + // NOTE: instead of caching the GenericHelpInfo object do a cached query here and create a new object each time, + // will avoid issues when the database data changes during run time // NOTE: always use the base delegator for this to avoid problems when this is being initialized Delegator baseDelegator = DelegatorFactory.getDelegator(this.delegatorBaseName); - GenericValue tenantDataSource = EntityQuery.use(baseDelegator).from("TenantDataSource").where("tenantId", this.delegatorTenantId, "entityGroupName", entityGroupName).cache(true).queryOne(); + GenericValue tenantDataSource = EntityQuery.use(baseDelegator).from("TenantDataSource").where("tenantId", this.delegatorTenantId, + "entityGroupName", entityGroupName).cache(true).queryOne(); if (tenantDataSource != null) { helperInfo.setTenantId(this.delegatorTenantId); helperInfo.setOverrideJdbcUri(tenantDataSource.getString("jdbcUri")); @@ -498,12 +528,18 @@ public class GenericDelegator implements Delegator { } } catch (GenericEntityException e) { // don't complain about this too much, just log the error if there is one - Debug.logInfo(e, "Error getting TenantDataSource info for tenantId=" + this.delegatorTenantId + ", entityGroupName=" + entityGroupName, MODULE); + Debug.logInfo(e, "Error getting TenantDataSource info for tenantId=" + this.delegatorTenantId + ", entityGroupName=" + + entityGroupName, MODULE); } } return helperInfo; } + /** + * Gets entity helper info. + * @param entityName the entity name + * @return the entity helper info + */ protected GenericHelperInfo getEntityHelperInfo(String entityName) { return this.getGroupHelperInfo(this.getEntityGroupName(entityName)); } @@ -537,7 +573,8 @@ public class GenericDelegator implements Delegator { if (helperInfo != null) { return GenericHelperFactory.getHelper(helperInfo); } - throw new GenericEntityException("There is no datasource (Helper) configured for the entity-group [" + this.getEntityGroupName(entityName) + "]; was trying to find datasource (helper) for entity [" + entityName + "]"); + throw new GenericEntityException("There is no datasource (Helper) configured for the entity-group [" + this.getEntityGroupName(entityName) + + "]; was trying to find datasource (helper) for entity [" + entityName + "]"); } /* (non-Javadoc) @@ -567,7 +604,8 @@ public class GenericDelegator implements Delegator { } ModelFieldTypeReader modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName); if (modelFieldTypeReader == null) { - throw new IllegalArgumentException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + helperName); + throw new IllegalArgumentException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + + helperName); } return modelFieldTypeReader; } @@ -741,12 +779,13 @@ public class GenericDelegator implements Delegator { GenericHelper helper = getEntityHelper(value.getEntityName()); // just make sure it is this delegator... value.setDelegator(this); - // this will throw an IllegalArgumentException if the entity for the value does not have one pk field, or if it already has a value set for the one pk field + // this will throw an IllegalArgumentException if the entity for the value does not have one pk field, or if it already has a value + // set for the one pk field value.setNextSeqId(); boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -783,16 +822,18 @@ public class GenericDelegator implements Delegator { throw e; } if (Debug.infoOn()) { - Debug.logInfo("Error creating entity record with a sequenced value [" + value.getPrimaryKey() + "], trying again about to refresh bank for entity [" + value.getEntityName() + "]", MODULE); + Debug.logInfo("Error creating entity record with a sequenced value [" + value.getPrimaryKey() + + "], trying again about to refresh bank for entity [" + value.getEntityName() + "]", MODULE); } // found an existing value... was probably a duplicate key, so clean things up and try again - this.AtomicRefSequencer.get().forceBankRefresh(value.getEntityName(), 1); + this.atomicRefSequence.get().forceBankRefresh(value.getEntityName(), 1); value.setNextSeqId(); value = helper.create(value); if (Debug.infoOn()) { - Debug.logInfo("Successfully created new entity record on retry with a sequenced value [" + value.getPrimaryKey() + "], after getting refreshed bank for entity [" + value.getEntityName() + "]", MODULE); + Debug.logInfo("Successfully created new entity record on retry with a sequenced value [" + value.getPrimaryKey() + + "], after getting refreshed bank for entity [" + value.getEntityName() + "]", MODULE); } if (testMode) { @@ -816,7 +857,8 @@ public class GenericDelegator implements Delegator { return value; } catch (GenericEntityException e) { String entityName = value != null ? value.getEntityName() : "invalid Generic Value"; - String errMsg = "Failure in createSetNextSeqId operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in createSetNextSeqId operation for entity [" + entityName + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -830,7 +872,7 @@ public class GenericDelegator implements Delegator { public GenericValue create(GenericValue value) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -872,7 +914,8 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return value; } catch (IllegalStateException | GenericEntityException e) { - String errMsg = "Failure in create operation for entity [" + (value != null ? value.getEntityName() : "value is null") + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in create operation for entity [" + (value != null ? value.getEntityName() : "value is null") + + "]: " + e.toString() + ". Rolling back transaction."; Debug.logError(errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -886,7 +929,7 @@ public class GenericDelegator implements Delegator { public GenericValue createOrStore(GenericValue value) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -902,13 +945,19 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return value; } catch (Exception e) { - String errMsg = "Failure in createOrStore operation for entity [" + (value != null ? value.getEntityName() : "value is null") + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in createOrStore operation for entity [" + (value != null ? value.getEntityName() : "value is null") + "]: " + + e.toString() + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); } } + /** + * Save entity sync remove info. + * @param dummyPK the dummy pk + * @throws GenericEntityException the generic entity exception + */ protected void saveEntitySyncRemoveInfo(GenericEntity dummyPK) throws GenericEntityException { // don't store remove info on entities where it is disabled if (dummyPK.getModelEntity().getNoAutoStamp() || this.testRollbackInProgress) { @@ -941,7 +990,7 @@ public class GenericDelegator implements Delegator { public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -967,7 +1016,7 @@ public class GenericDelegator implements Delegator { ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_REMOVE, primaryKey, false); this.clearCacheLine(primaryKey); - if (saveEntitySyncRemoveInfo) { + if (SAVE_ENTITY_SYNC_REMOVE_INFO) { this.saveEntitySyncRemoveInfo(primaryKey); } @@ -981,7 +1030,8 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return num; } catch (IllegalStateException | GenericEntityException e) { - String errMsg = "Failure in removeByPrimaryKey operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in removeByPrimaryKey operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -996,7 +1046,7 @@ public class GenericDelegator implements Delegator { // NOTE: this does not call the GenericDelegator.removeByPrimaryKey method because it has more information to pass to the ECA rule hander boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1032,7 +1082,7 @@ public class GenericDelegator implements Delegator { } } - if (saveEntitySyncRemoveInfo) { + if (SAVE_ENTITY_SYNC_REMOVE_INFO) { this.saveEntitySyncRemoveInfo(value.getPrimaryKey()); } @@ -1040,7 +1090,8 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return num; } catch (IllegalStateException | GenericEntityException e) { - String errMsg = "Failure in removeValue operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in removeValue operation for entity [" + value.getEntityName() + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -1071,7 +1122,7 @@ public class GenericDelegator implements Delegator { public int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1087,8 +1138,8 @@ public class GenericDelegator implements Delegator { // for test mode to help the rollback // for eeca to analyse each value to check if a condition match List<GenericValue> removedEntities = (testMode || hasEntityEcaRules) - ? findList(entityName, condition, null, null, null, false) - : Collections.emptyList(); + ? findList(entityName, condition, null, null, null, false) + : Collections.emptyList(); int rowsAffected = 0; if (!removedEntities.isEmpty()) { @@ -1164,10 +1215,11 @@ public class GenericDelegator implements Delegator { * @see org.apache.ofbiz.entity.Delegator#storeByCondition(java.lang.String, java.util.Map, org.apache.ofbiz.entity.condition.EntityCondition) */ @Override - public int storeByCondition(String entityName, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException { + public int storeByCondition(String entityName, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) + throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1206,7 +1258,7 @@ public class GenericDelegator implements Delegator { public int store(GenericValue value) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1288,7 +1340,8 @@ public class GenericDelegator implements Delegator { // exists? // NOTE: don't use findByPrimaryKey because we don't want to the ECA events to fire and such if (!primaryKey.isPrimaryKey()) { - throw new GenericModelException("[GenericDelegator.storeAll] One of the passed primary keys is not a valid primary key: " + primaryKey); + throw new GenericModelException("[GenericDelegator.storeAll] One of the passed primary keys is not a valid primary key: " + + primaryKey); } GenericValue existing; try { @@ -1413,7 +1466,7 @@ public class GenericDelegator implements Delegator { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1458,7 +1511,7 @@ public class GenericDelegator implements Delegator { public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set<String> keys) throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1485,7 +1538,8 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return value; } catch (GenericEntityException e) { - String errMsg = "Failure in findByPrimaryKeyPartial operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in findByPrimaryKeyPartial operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -1505,23 +1559,28 @@ public class GenericDelegator implements Delegator { * @see org.apache.ofbiz.entity.Delegator#findByAnd(java.lang.String, java.util.Map, java.util.List, boolean) */ @Override - public List<GenericValue> findByAnd(String entityName, Map<String, ? extends Object> fields, List<String> orderBy, boolean useCache) throws GenericEntityException { + public List<GenericValue> findByAnd(String entityName, Map<String, ? extends Object> fields, List<String> orderBy, boolean useCache) + throws GenericEntityException { return this.findList(entityName, EntityCondition.makeCondition(fields), null, orderBy, null, useCache); } /* (non-Javadoc) - * @see org.apache.ofbiz.entity.Delegator#find(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions) + * @see org.apache.ofbiz.entity.Delegator#find(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, + * org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions) */ @Override - public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException { + public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, + Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException { // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI if (!TransactionUtil.isTransactionInPlace()) { - //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction."); + //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. + // Wrap this call in a transaction."); //throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed... Exception newE = new Exception("Stack Trace"); - Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", MODULE); + Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place." + + "Wrap this call in a transaction.", MODULE); } ModelEntity modelEntity = getModelReader().getModelEntity(entityName); @@ -1538,7 +1597,8 @@ public class GenericDelegator implements Delegator { ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false); GenericHelper helper = getEntityHelper(modelEntity.getEntityName()); - EntityListIterator eli = helper.findListIteratorByCondition(this, modelEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions); + EntityListIterator eli = helper.findListIteratorByCondition(this, modelEntity, whereEntityCondition, havingEntityCondition, + fieldsToSelect, orderBy, findOptions); eli.setDelegator(this); ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false); @@ -1557,7 +1617,8 @@ public class GenericDelegator implements Delegator { } /* (non-Javadoc) - * @see org.apache.ofbiz.entity.Delegator#findList(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions, boolean) + * @see org.apache.ofbiz.entity.Delegator#findList(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, + * java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions, boolean) */ @Override public List<GenericValue> findList(String entityName, EntityCondition entityCondition, EntityCondition havingCondition, @@ -1579,7 +1640,7 @@ public class GenericDelegator implements Delegator { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1603,18 +1664,24 @@ public class GenericDelegator implements Delegator { } /* (non-Javadoc) - * @see org.apache.ofbiz.entity.Delegator#findListIteratorByCondition(org.apache.ofbiz.entity.model.DynamicViewEntity, org.apache.ofbiz.entity.condition.EntityCondition, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Collection, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions) + * @see org.apache.ofbiz.entity.Delegator#findListIteratorByCondition(org.apache.ofbiz.entity.model.DynamicViewEntity, + * org.apache.ofbiz.entity.condition.EntityCondition, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Collection, java.util.List, + * org.apache.ofbiz.entity.util.EntityFindOptions) */ @Override - public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException { + public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, + EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) + throws GenericEntityException { // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI if (!TransactionUtil.isTransactionInPlace()) { - //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction."); + //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. + // Wrap this call in a transaction."); //throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed... Exception newE = new Exception("Stack Trace"); - Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", MODULE); + Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place." + + "Wrap this call in a transaction.", MODULE); } ModelViewEntity modelViewEntity = dynamicViewEntity.makeModelViewEntity(this); @@ -1653,7 +1720,7 @@ public class GenericDelegator implements Delegator { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1688,7 +1755,8 @@ public class GenericDelegator implements Delegator { TransactionUtil.commit(beganTransaction); return count; } catch (GenericEntityException e) { - String errMsg = "Failure in findListIteratorByCondition operation for entity [DynamicView]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in findListIteratorByCondition operation for entity [DynamicView]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -1696,13 +1764,15 @@ public class GenericDelegator implements Delegator { } /* (non-Javadoc) - * @see org.apache.ofbiz.entity.Delegator#getMultiRelation(org.apache.ofbiz.entity.GenericValue, java.lang.String, java.lang.String, java.util.List) + * @see org.apache.ofbiz.entity.Delegator#getMultiRelation(org.apache.ofbiz.entity.GenericValue, java.lang.String, + * java.lang.String, java.util.List) */ @Override - public List<GenericValue> getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List<String> orderBy) throws GenericEntityException { + public List<GenericValue> getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List<String> orderBy) + throws GenericEntityException { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -1715,11 +1785,13 @@ public class GenericDelegator implements Delegator { ModelEntity modelEntityTwo = getModelEntity(modelRelationTwo.getRelEntityName()); GenericHelper helper = getEntityHelper(modelEntity); - List<GenericValue> result = helper.findByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, modelEntityTwo, orderBy); + List<GenericValue> result = helper.findByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, + modelEntityTwo, orderBy); TransactionUtil.commit(beganTransaction); return result; } catch (GenericEntityException e) { - String errMsg = "Failure in getMultiRelation operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in getMultiRelation operation for entity [" + value.getEntityName() + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); TransactionUtil.rollback(beganTransaction, errMsg, e); throw new GenericEntityException(e); @@ -1727,10 +1799,12 @@ public class GenericDelegator implements Delegator { } /* (non-Javadoc) - * @see org.apache.ofbiz.entity.Delegator#getRelated(java.lang.String, java.util.Map, java.util.List, org.apache.ofbiz.entity.GenericValue, boolean) + * @see org.apache.ofbiz.entity.Delegator#getRelated(java.lang.String, java.util.Map, java.util.List, + * org.apache.ofbiz.entity.GenericValue, boolean) */ @Override - public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, GenericValue value, boolean useCache) throws GenericEntityException { + public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, + GenericValue value, boolean useCache) throws GenericEntityException { ModelEntity modelEntity = value.getModelEntity(); ModelRelation relation = modelEntity.getRelation(relationName); @@ -1755,7 +1829,8 @@ public class GenericDelegator implements Delegator { * @see org.apache.ofbiz.entity.Delegator#getRelatedDummyPK(java.lang.String, java.util.Map, org.apache.ofbiz.entity.GenericValue) */ @Override - public GenericPK getRelatedDummyPK(String relationName, Map<String, ? extends Object> byAndFields, GenericValue value) throws GenericEntityException { + public GenericPK getRelatedDummyPK(String relationName, Map<String, ? extends Object> byAndFields, GenericValue value) + throws GenericEntityException { ModelEntity modelEntity = value.getModelEntity(); ModelRelation relation = modelEntity.getRelation(relationName); @@ -1788,7 +1863,8 @@ public class GenericDelegator implements Delegator { throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); } if (!"one".equals(relation.getType()) && !"one-nofk".equals(relation.getType())) { - throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + value.getEntityName()); + throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + + value.getEntityName()); } Map<String, Object> fields = new HashMap<>(); @@ -2055,7 +2131,8 @@ public class GenericDelegator implements Delegator { if (primaryKey.getModelEntity().getNeverCache()) { if (Debug.warningOn()) { - Debug.logWarning("Tried to put a value of the " + value.getEntityName() + " entity in the BY PRIMARY KEY cache but this entity has never-cache set to true, not caching.", MODULE); + Debug.logWarning("Tried to put a value of the " + value.getEntityName() + " entity in the BY PRIMARY KEY cache but this entity" + + "has never-cache set to true, not caching.", MODULE); } return; } @@ -2130,7 +2207,8 @@ public class GenericDelegator implements Delegator { values.add(value); } } - } while ((curChild = curChild.getNextSibling()) != null); + curChild = curChild.getNextSibling(); + } while (curChild != null); } else { Debug.logWarning("[GenericDelegator.makeValues] No child nodes found in document.", MODULE); } @@ -2200,14 +2278,22 @@ public class GenericDelegator implements Delegator { // ======= Misc Methods ======== protected static class EntityEcaRuleRunner<T> { - protected EntityEcaHandler<T> entityEcaHandler; - protected Map<String, List<T>> eventMap; + private EntityEcaHandler<T> entityEcaHandler; + private Map<String, List<T>> eventMap; protected EntityEcaRuleRunner(EntityEcaHandler<T> entityEcaHandler, Map<String, List<T>> eventMap) { this.entityEcaHandler = entityEcaHandler; this.eventMap = eventMap; } + /** + * Eval rules. + * @param event the event + * @param currentOperation the current operation + * @param value the value + * @param isError the is error + * @throws GenericEntityException the generic entity exception + */ protected void evalRules(String event, String currentOperation, GenericEntity value, boolean isError) throws GenericEntityException { if (entityEcaHandler == null) { return; @@ -2216,6 +2302,11 @@ public class GenericDelegator implements Delegator { } } + /** + * Gets eca rule runner. + * @param entityName the entity name + * @return the eca rule runner + */ protected EntityEcaRuleRunner<?> getEcaRuleRunner(String entityName) { if (this.testRollbackInProgress) { return createEntityEcaRuleRunner(null, null); @@ -2266,7 +2357,8 @@ public class GenericDelegator implements Delegator { Long nextSeqLong = this.getNextSeqIdLong(seqName, staggerMax); if (nextSeqLong == null) { - // NOTE: the getNextSeqIdLong method SHOULD throw a runtime exception when no sequence value is found, which means we should never see it get here + // NOTE: the getNextSeqIdLong method SHOULD throw a runtime exception when no sequence value is found, + // which means we should never see it get here throw new IllegalArgumentException("Could not get next sequenced ID for sequence name: " + seqName); } @@ -2284,12 +2376,12 @@ public class GenericDelegator implements Delegator { @Override public Long getNextSeqIdLong(String seqName, long staggerMax) { try { - SequenceUtil sequencer = this.AtomicRefSequencer.get(); + SequenceUtil sequencer = this.atomicRefSequence.get(); if (sequencer == null) { ModelEntity seqEntity = this.getModelEntity("SequenceValueItem"); sequencer = new SequenceUtil(this.getEntityHelperInfo("SequenceValueItem"), seqEntity, "seqName", "seqId"); - if (!AtomicRefSequencer.compareAndSet(null, sequencer)) { - sequencer = this.AtomicRefSequencer.get(); + if (!atomicRefSequence.compareAndSet(null, sequencer)) { + sequencer = this.atomicRefSequence.get(); } } ModelEntity seqModelEntity = null; @@ -2312,7 +2404,7 @@ public class GenericDelegator implements Delegator { */ @Override public void setSequencer(SequenceUtil sequencer) { - this.AtomicRefSequencer.set(sequencer); + this.atomicRefSequence.set(sequencer); } /* (non-Javadoc) @@ -2320,7 +2412,7 @@ public class GenericDelegator implements Delegator { */ @Override public void refreshSequencer() { - this.AtomicRefSequencer.set(null); + this.atomicRefSequence.set(null); } @@ -2338,7 +2430,7 @@ public class GenericDelegator implements Delegator { boolean beganTransaction = false; try { - if (alwaysUseTransaction) { + if (ALWAYS_USE_TRANS) { beganTransaction = TransactionUtil.begin(); } @@ -2361,7 +2453,8 @@ public class GenericDelegator implements Delegator { highestSeqVal = seqVal; } } catch (NumberFormatException e) { - Debug.logWarning("Error in make-next-seq-id converting SeqId [" + currentSeqId + "] in field: " + seqFieldName + " from entity: " + value.getEntityName() + " to a number: " + e.toString(), MODULE); + Debug.logWarning("Error in make-next-seq-id converting SeqId [" + currentSeqId + "] in field: " + seqFieldName + + " from entity: " + value.getEntityName() + " to a number: " + e.toString(), MODULE); } } } @@ -2373,7 +2466,8 @@ public class GenericDelegator implements Delegator { // only commit the transaction if we started one... TransactionUtil.commit(beganTransaction); } catch (GenericEntityException e) { - String errMsg = "Failure in setNextSubSeqId operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + String errMsg = "Failure in setNextSubSeqId operation for entity [" + value.getEntityName() + "]: " + e.toString() + + ". Rolling back transaction."; Debug.logError(e, errMsg, MODULE); try { // only rollback the transaction if we started one... @@ -2419,6 +2513,10 @@ public class GenericDelegator implements Delegator { this.crypto = crypto; } + /** + * Absorb list. + * @param lst the lst + */ protected void absorbList(List<GenericValue> lst) { if (lst == null) { return; @@ -2436,6 +2534,13 @@ public class GenericDelegator implements Delegator { return cache; } + /** + * Create entity audit log all. + * @param value the value + * @param isUpdate the is update + * @param isRemove the is remove + * @throws GenericEntityException the generic entity exception + */ protected void createEntityAuditLogAll(GenericValue value, boolean isUpdate, boolean isRemove) throws GenericEntityException { Timestamp nowTimestamp = UtilDateTime.nowTimestamp(); for (ModelField mf: value.getModelEntity().getFieldsUnmodifiable()) { @@ -2445,7 +2550,17 @@ public class GenericDelegator implements Delegator { } } - protected void createEntityAuditLogSingle(GenericValue value, ModelField mf, boolean isUpdate, boolean isRemove, Timestamp nowTimestamp) throws GenericEntityException { + /** + * Create entity audit log single. + * @param value the value + * @param mf the mf + * @param isUpdate the is update + * @param isRemove the is remove + * @param nowTimestamp the now timestamp + * @throws GenericEntityException the generic entity exception + */ + protected void createEntityAuditLogSingle(GenericValue value, ModelField mf, boolean isUpdate, boolean isRemove, Timestamp nowTimestamp) + throws GenericEntityException { if (value == null || mf == null || !mf.getEnableAuditLog() || this.testRollbackInProgress) { return; } @@ -2531,7 +2646,7 @@ public class GenericDelegator implements Delegator { // In case this delegator is in testMode give it a reference to // the rollback list newDelegator.testMode = this.testMode; - testOperationsUpdater.set(newDelegator, this.testOperations); + TEST_OPERATIONS_UPDATER.set(newDelegator, this.testOperations); // not setting the sequencer so that we have unique sequences. return newDelegator; @@ -2560,7 +2675,7 @@ public class GenericDelegator implements Delegator { private void setTestMode(boolean testMode) { this.testMode = testMode; if (testMode) { - testOperationsUpdater.set(this, new LinkedBlockingDeque<TestOperation>()); + TEST_OPERATIONS_UPDATER.set(this, new LinkedBlockingDeque<TestOperation>()); } else { this.testOperations.clear(); } @@ -2643,8 +2758,13 @@ public class GenericDelegator implements Delegator { } } + /** + * Create distributed cache clear distributed cache clear. + * @return the distributed cache clear + */ protected DistributedCacheClear createDistributedCacheClear() { - // If useDistributedCacheClear is false do nothing: the distributedCacheClear member field with a null value would cause dcc code to do nothing + // If useDistributedCacheClear is false do nothing: the distributedCacheClear member field with a null value would cause dcc code to do + // nothing if (useDistributedCacheClear()) { //time to do some tricks with manual class loading that resolves circular dependencies, like calling services ClassLoader loader = Thread.currentThread().getContextClassLoader(); @@ -2657,9 +2777,11 @@ public class GenericDelegator implements Delegator { distributedCacheClear.setDelegator(this, this.delegatorInfo.getDistributedCacheClearUserLoginId()); return distributedCacheClear; } catch (ReflectiveOperationException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " was not found, distributed cache clearing will be disabled", MODULE); + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + + " was not found, distributed cache clearing will be disabled", MODULE); } catch (ClassCastException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " does not implement the DistributedCacheClear interface, distributed cache clearing will be disabled", MODULE); + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + + " does not implement the DistributedCacheClear interface, distributed cache clearing will be disabled", MODULE); } } else { if (Debug.verboseOn()) { @@ -2669,6 +2791,10 @@ public class GenericDelegator implements Delegator { return null; } + /** + * Gets distributed cache clear. + * @return the distributed cache clear + */ protected DistributedCacheClear getDistributedCacheClear() { Future<DistributedCacheClear> future = this.distributedCacheClear.get(); try { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/cache/Cache.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/cache/Cache.java index 85dc04c..d250b86 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/cache/Cache.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/cache/Cache.java @@ -31,11 +31,11 @@ public class Cache { private static final String MODULE = Cache.class.getName(); - protected EntityCache entityCache; - protected EntityListCache entityListCache; - protected EntityObjectCache entityObjectCache; + private EntityCache entityCache; + private EntityListCache entityListCache; + private EntityObjectCache entityObjectCache; - protected String delegatorName; + private String delegatorName; public Cache(String delegatorName) { this.delegatorName = delegatorName; @@ -44,37 +44,86 @@ public class Cache { entityListCache = new EntityListCache(delegatorName); } + /** + * Clear. + */ public void clear() { entityCache.clear(); entityListCache.clear(); entityObjectCache.clear(); } + /** + * Remove. + * @param entityName the entity name + */ public void remove(String entityName) { entityCache.remove(entityName); entityListCache.remove(entityName); } + /** + * Get generic value. + * @param pk the pk + * @return the generic value + */ public GenericValue get(GenericPK pk) { return entityCache.get(pk); } + /** + * Get list. + * @param entityName the entity name + * @param condition the condition + * @param orderBy the order by + * @return the list + */ public List<GenericValue> get(String entityName, EntityCondition condition, List<String> orderBy) { return entityListCache.get(entityName, condition, orderBy); } + /** + * Get t. + * @param <T> the type parameter + * @param entityName the entity name + * @param condition the condition + * @param name the name + * @return the t + */ public <T> T get(String entityName, EntityCondition condition, String name) { return UtilGenerics.<T>cast(entityObjectCache.get(entityName, condition, name)); } + /** + * Put list. + * @param entityName the entity name + * @param condition the condition + * @param orderBy the order by + * @param entities the entities + * @return the list + */ public List<GenericValue> put(String entityName, EntityCondition condition, List<String> orderBy, List<GenericValue> entities) { return entityListCache.put(entityName, condition, orderBy, entities); } + /** + * Put t. + * @param <T> the type parameter + * @param entityName the entity name + * @param condition the condition + * @param name the name + * @param value the value + * @return the t + */ public <T> T put(String entityName, EntityCondition condition, String name, T value) { return UtilGenerics.<T>cast(entityObjectCache.put(entityName, condition, name, value)); } + /** + * Put generic value. + * @param entity the entity + * @return the generic value + */ public GenericValue put(GenericValue entity) { GenericValue oldEntity = entityCache.put(entity.getPrimaryKey(), entity); if (entity.getModelEntity().getAutoClearCache()) { @@ -84,6 +133,12 @@ public class Cache { return oldEntity; } + /** + * Put generic value. + * @param pk the pk + * @param entity the entity + * @return the generic value + */ public GenericValue put(GenericPK pk, GenericValue entity) { GenericValue oldEntity = entityCache.put(pk, entity); if (pk.getModelEntity().getAutoClearCache()) { @@ -93,22 +148,47 @@ public class Cache { return oldEntity; } + /** + * Remove list. + * @param entityName the entity name + * @param condition the condition + * @param orderBy the order by + * @return the list + */ public List<GenericValue> remove(String entityName, EntityCondition condition, List<String> orderBy) { entityCache.remove(entityName, condition); entityObjectCache.remove(entityName, condition); return entityListCache.remove(entityName, condition, orderBy); } + /** + * Remove. + * @param entityName the entity name + * @param condition the condition + */ public void remove(String entityName, EntityCondition condition) { entityCache.remove(entityName, condition); entityListCache.remove(entityName, condition); entityObjectCache.remove(entityName, condition); } + /** + * Remove t. + * @param <T> the type parameter + * @param entityName the entity name + * @param condition the condition + * @param name the name + * @return the t + */ public <T> T remove(String entityName, EntityCondition condition, String name) { return UtilGenerics.<T>cast(entityObjectCache.remove(entityName, condition, name)); } + /** + * Remove generic value. + * @param entity the entity + * @return the generic value + */ public GenericValue remove(GenericEntity entity) { if (Debug.verboseOn()) { Debug.logVerbose("Cache remove GenericEntity: " + entity, MODULE); @@ -120,6 +200,11 @@ public class Cache { return oldEntity; } + /** + * Remove generic value. + * @param pk the pk + * @return the generic value + */ public GenericValue remove(GenericPK pk) { if (Debug.verboseOn()) { Debug.logVerbose("Cache remove GenericPK: " + pk, MODULE); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionSubSelect.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionSubSelect.java index 8c357c7..4723843 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionSubSelect.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityConditionSubSelect.java @@ -39,10 +39,10 @@ import org.apache.ofbiz.entity.model.ModelViewEntity; public class EntityConditionSubSelect extends EntityConditionValue { private static final String MODULE = EntityConditionSubSelect.class.getName(); - protected ModelEntity localModelEntity = null; - protected String keyFieldName = null; - protected EntityCondition whereCond = null; - protected Boolean requireAll = null; + private ModelEntity localModelEntity = null; + private String keyFieldName = null; + private EntityCondition whereCond = null; + private Boolean requireAll = null; protected EntityConditionSubSelect() { } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityFieldValue.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityFieldValue.java index 50e6813..7d6ec10 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityFieldValue.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/EntityFieldValue.java @@ -45,10 +45,10 @@ public class EntityFieldValue extends EntityConditionValue { private static final String MODULE = EntityFieldValue.class.getName(); - protected String fieldName = null; - protected String entityAlias = null; - protected List<String> entityAliasStack = null; - protected ModelViewEntity modelViewEntity = null; + private String fieldName = null; + private String entityAlias = null; + private List<String> entityAliasStack = null; + private ModelViewEntity modelViewEntity = null; public static EntityFieldValue makeFieldValue(String fieldName) { EntityFieldValue efv = new EntityFieldValue(); @@ -62,6 +62,13 @@ public class EntityFieldValue extends EntityConditionValue { return efv; } + /** + * Init. + * @param fieldName the field name + * @param entityAlias the entity alias + * @param entityAliasStack the entity alias stack + * @param modelViewEntity the model view entity + */ public void init(String fieldName, String entityAlias, List<String> entityAliasStack, ModelViewEntity modelViewEntity) { this.fieldName = fieldName; this.entityAlias = entityAlias; @@ -81,6 +88,9 @@ public class EntityFieldValue extends EntityConditionValue { } } + /** + * Reset. + */ public void reset() { this.fieldName = null; this.entityAlias = null; @@ -88,6 +98,10 @@ public class EntityFieldValue extends EntityConditionValue { this.modelViewEntity = null; } + /** + * Gets field name. + * @return the field name + */ public String getFieldName() { return fieldName; } @@ -136,7 +150,8 @@ public class EntityFieldValue extends EntityConditionValue { } @Override - public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceInfo) { + public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, + List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceInfo) { if (this.modelViewEntity != null) { // NOTE: this section is a bit of a hack; the other code is terribly complex and really needs to be refactored to incorporate support for this diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/OrderByItem.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/OrderByItem.java index fee159d..ccd7719 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/OrderByItem.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/condition/OrderByItem.java @@ -31,15 +31,15 @@ import org.apache.ofbiz.entity.model.ModelEntity; public class OrderByItem implements Comparator<GenericEntity> { public static final int DEFAULT = 0; public static final int UPPER = 1; - public static final int LOWER = 2; + private static final int LOWER = 2; - public static final String NULLS_FIRST = "NULLS FIRST"; - public static final String NULLS_LAST = "NULLS LAST"; + private static final String NULLS_FIRST = "NULLS FIRST"; + private static final String NULLS_LAST = "NULLS LAST"; private static final String MODULE = OrderByItem.class.getName(); - protected boolean descending; - protected Boolean nullsFirst; - protected EntityConditionValue value; + private boolean descending; + private Boolean nullsFirst; + private EntityConditionValue value; public OrderByItem(EntityConditionValue value) { this.value = value; @@ -55,10 +55,18 @@ public class OrderByItem implements Comparator<GenericEntity> { this.nullsFirst = nullsFirst; } + /** + * Gets value. + * @return the value + */ public EntityConditionValue getValue() { return value; } + /** + * Gets descending. + * @return the descending + */ public boolean getDescending() { return descending; } @@ -90,7 +98,8 @@ public class OrderByItem implements Comparator<GenericEntity> { text = text.substring(0, text.length() - NULLS_LAST.length()).trim(); } - int startIndex = 0, endIndex = text.length(); + int startIndex = 0; + int endIndex = text.length(); boolean descending; int caseSensitivity; if (text.endsWith(" DESC")) { @@ -149,6 +158,11 @@ public class OrderByItem implements Comparator<GenericEntity> { return new OrderByItem(value, descending, nullsFirst); } + /** + * Check order by. + * @param modelEntity the model entity + * @throws GenericModelException the generic model exception + */ public void checkOrderBy(ModelEntity modelEntity) throws GenericModelException { value.validateSql(modelEntity); } @@ -170,12 +184,26 @@ public class OrderByItem implements Comparator<GenericEntity> { return descending ? -result : result; } + /** + * Make order by string string. + * @param modelEntity the model entity + * @param includeTablenamePrefix the include tablename prefix + * @param datasourceInfo the datasource info + * @return the string + */ public String makeOrderByString(ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) { StringBuilder sb = new StringBuilder(); makeOrderByString(sb, modelEntity, includeTablenamePrefix, datasourceInfo); return sb.toString(); } + /** + * Make order by string. + * @param sb the sb + * @param modelEntity the model entity + * @param includeTablenamePrefix the include tablename prefix + * @param datasourceInfo the datasource info + */ public void makeOrderByString(StringBuilder sb, ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) { if ((nullsFirst != null) && (!datasourceInfo.getUseOrderByNulls())) { sb.append("CASE WHEN "); 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 6af953e..fd56b9e 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 @@ -56,17 +56,17 @@ import org.w3c.dom.Element; public abstract class ListFinder extends Finder { private static final String MODULE = ListFinder.class.getName(); - protected String label; + private String label; - protected FlexibleStringExpander filterByDateStrExdr; - protected FlexibleStringExpander distinctStrExdr; - protected FlexibleStringExpander delegatorNameExdr; - protected FlexibleMapAccessor<Object> listAcsr; - protected FlexibleStringExpander resultSetTypeExdr; + private FlexibleStringExpander filterByDateStrExdr; + private FlexibleStringExpander distinctStrExdr; + private FlexibleStringExpander delegatorNameExdr; + private FlexibleMapAccessor<Object> listAcsr; + private FlexibleStringExpander resultSetTypeExdr; - protected List<FlexibleStringExpander> selectFieldExpanderList; - protected List<FlexibleStringExpander> orderByExpanderList; - protected OutputHandler outputHandler; + private List<FlexibleStringExpander> selectFieldExpanderList; + private List<FlexibleStringExpander> orderByExpanderList; + private OutputHandler outputHandler; protected ListFinder(Element element, String label) { super(element); @@ -247,15 +247,34 @@ public abstract class ListFinder extends Finder { } } + /** + * Gets order by field list. + * @param context the context + * @return the order by field list + */ public List<String> getOrderByFieldList(Map<String, Object> context) { List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context); return orderByFields; } + /** + * Gets where entity condition. + * @param context the context + * @param modelEntity the model entity + * @param modelFieldTypeReader the model field type reader + * @return the where entity condition + */ public EntityCondition getWhereEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) { return null; } + /** + * Gets having entity condition. + * @param context the context + * @param modelEntity the model entity + * @param modelFieldTypeReader the model field type reader + * @return the having entity condition + */ public EntityCondition getHavingEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) { return null; } diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/PrimaryKeyFinder.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/PrimaryKeyFinder.java index 17e43dc..bfd3da5 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/PrimaryKeyFinder.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/finder/PrimaryKeyFinder.java @@ -46,10 +46,10 @@ import org.w3c.dom.Element; public class PrimaryKeyFinder extends Finder { private static final String MODULE = PrimaryKeyFinder.class.getName(); - protected FlexibleMapAccessor<Object> valueNameAcsr; - protected FlexibleStringExpander autoFieldMapExdr; - protected Map<FlexibleMapAccessor<Object>, Object> fieldMap; - protected List<FlexibleStringExpander> selectFieldExpanderList; + private FlexibleMapAccessor<Object> valueNameAcsr; + private FlexibleStringExpander autoFieldMapExdr; + private Map<FlexibleMapAccessor<Object>, Object> fieldMap; + private List<FlexibleStringExpander> selectFieldExpanderList; public PrimaryKeyFinder(Element entityOneElement) { super(entityOneElement); @@ -95,8 +95,9 @@ public class PrimaryKeyFinder extends Finder { } } - public static GenericValue runFind(ModelEntity modelEntity, Map<String, Object> context, Delegator delegator, boolean useCache, boolean autoFieldMap, - Map<FlexibleMapAccessor<Object>, Object> fieldMap, List<FlexibleStringExpander> selectFieldExpanderList) throws GeneralException { + public static GenericValue runFind(ModelEntity modelEntity, Map<String, Object> context, Delegator delegator, boolean useCache, + boolean autoFieldMap, Map<FlexibleMapAccessor<Object>, Object> fieldMap, List<FlexibleStringExpander> selectFieldExpanderList) + throws GeneralException { // assemble the field map Map<String, Object> entityContext = new HashMap<>(); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/CursorStatement.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/CursorStatement.java index 5c19587..8bc6a86 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/CursorStatement.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/jdbc/CursorStatement.java @@ -32,10 +32,10 @@ import org.apache.ofbiz.entity.transaction.TransactionUtil; public class CursorStatement extends AbstractCursorHandler { private static final String MODULE = CursorStatement.class.getName(); - protected ResultSet currentResultSet; - protected Statement stmt; - protected boolean beganTransaction; - protected boolean autoCommit; + private ResultSet currentResultSet; + private Statement stmt; + private boolean beganTransaction; + private boolean autoCommit; protected CursorStatement(Statement stmt, String cursorName, int fetchSize) throws GenericTransactionException, SQLException { super(cursorName, fetchSize); @@ -53,7 +53,7 @@ public class CursorStatement extends AbstractCursorHandler { TransactionUtil.commit(beganTransaction); stmt.close(); return null; - } else if ("execute".equals(method.getName())) { + // } else if ("execute".equals(method.getName())) { } else if ("executeQuery".equals(method.getName()) && args == null) { PreparedStatement pstmt = (PreparedStatement) stmt; pstmt.executeUpdate(); 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 7cbc135..4bfb1d1 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 @@ -3069,7 +3069,6 @@ public class DatabaseUtil { /** * Gets decimal digits. - * * @return the decimal digits */ public int getDecimalDigits() { @@ -3078,7 +3077,6 @@ public class DatabaseUtil { /** * Is pk boolean. - * * @return the boolean */ public boolean isPk() { @@ -3087,7 +3085,6 @@ public class DatabaseUtil { /** * Gets column name. - * * @return the column name */ public String getColumnName() { @@ -3096,7 +3093,6 @@ public class DatabaseUtil { /** * Gets type name. - * * @return the type name */ public String getTypeName() { @@ -3105,7 +3101,6 @@ public class DatabaseUtil { /** * Gets column size. - * * @return the column size */ public int getColumnSize() { @@ -3114,7 +3109,6 @@ public class DatabaseUtil { /** * Gets is nullable. - * * @return the is nullable */ public String getIsNullable() { @@ -3208,7 +3202,6 @@ public class DatabaseUtil { /** * Gets entity. - * * @return the entity */ public ModelEntity getEntity() { @@ -3217,7 +3210,6 @@ public class DatabaseUtil { /** * Sets count. - * * @param count the count */ public void setCount(int count) { diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/DynamicViewEntity.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/DynamicViewEntity.java index 7eb5f24..dadadb0 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/DynamicViewEntity.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/DynamicViewEntity.java @@ -46,49 +46,66 @@ public class DynamicViewEntity { private static final String MODULE = DynamicViewEntity.class.getName(); /** The entity-name of the Entity */ - protected String entityName = "DynamicViewEntity"; + private String entityName = "DynamicViewEntity"; /** The package-name of the Entity */ - protected String packageName = "org.apache.ofbiz.dynamicview"; + private String packageName = "org.apache.ofbiz.dynamicview"; /** The default-resource-name of the Entity, used with the getResource call to check for a value in a resource bundle */ - protected String defaultResourceName = ""; + private String defaultResourceName = ""; /** The title for documentation purposes */ - protected String title = ""; + private String title = ""; /** Contains member-entity alias name definitions: key is alias, value is ModelMemberEntity */ - protected Map<String, ModelMemberEntity> memberModelMemberEntities = new HashMap<>(); + private Map<String, ModelMemberEntity> memberModelMemberEntities = new HashMap<>(); /** List of alias-alls which act as a shortcut for easily pulling over member entity fields */ - protected List<ModelAliasAll> aliasAlls = new ArrayList<>(); + private List<ModelAliasAll> aliasAlls = new ArrayList<>(); /** List of aliases with information in addition to what is in the standard field list */ - protected List<ModelAlias> aliases = new ArrayList<>(); + private List<ModelAlias> aliases = new ArrayList<>(); /** List of fields to group by */ - protected List<String> groupBy; + private List<String> groupBy; /** List of view links to define how entities are connected (or "joined") */ - protected List<ModelViewLink> viewLinks = new ArrayList<>(); + private List<ModelViewLink> viewLinks = new ArrayList<>(); /** relations defining relationships between this entity and other entities */ - protected List<ModelRelation> relations = new ArrayList<>(); + private List<ModelRelation> relations = new ArrayList<>(); public DynamicViewEntity() { } + /** + * Make model view entity model view entity. + * @param delegator the delegator + * @return the model view entity + */ public ModelViewEntity makeModelViewEntity(Delegator delegator) { ModelViewEntity modelViewEntity = new ModelViewEntity(this, delegator.getModelReader()); return modelViewEntity; } + /** + * Gets view xml. + * @param entityName the entity name + * @return the view xml + * @throws IOException the io exception + */ public String getViewXml(String entityName) throws IOException { Document doc = UtilXml.makeEmptyXmlDocument(); Element viewElement = getViewElement(doc, entityName); return UtilXml.writeXmlDocument(viewElement); } + /** + * Gets view element. + * @param doc the doc + * @param entityName the entity name + * @return the view element + */ public Element getViewElement(Document doc, String entityName) { Element viewElement = doc.createElement("view-entity"); viewElement.setAttribute("entity-name", entityName); @@ -145,6 +162,10 @@ public class DynamicViewEntity { return viewElement; } + /** + * Gets one real entity name. + * @return the one real entity name + */ public String getOneRealEntityName() { // return first entity name for memberModelMemberEntities Map if (this.memberModelMemberEntities.size() == 0) { @@ -211,11 +232,20 @@ public class DynamicViewEntity { this.title = title; } + /** + * Add member entity. + * @param entityAlias the entity alias + * @param entityName the entity name + */ public void addMemberEntity(String entityAlias, String entityName) { ModelMemberEntity modelMemberEntity = new ModelMemberEntity(entityAlias, entityName); this.memberModelMemberEntities.put(entityAlias, modelMemberEntity); } + /** + * Gets model member entities entry iter. + * @return the model member entities entry iter + */ public Iterator<Map.Entry<String, ModelMemberEntity>> getModelMemberEntitiesEntryIter() { return this.memberModelMemberEntities.entrySet().iterator(); } @@ -228,15 +258,30 @@ public class DynamicViewEntity { addAliasAll(entityAlias, prefix, null); } + /** + * Add alias all. + * @param entityAlias the entity alias + * @param prefix the prefix + * @param excludes the excludes + */ public void addAliasAll(String entityAlias, String prefix, Collection<String> excludes) { ModelAliasAll aliasAll = new ModelAliasAll(entityAlias, prefix, false, null, null, excludes); this.aliasAlls.add(aliasAll); } + /** + * Add all alias alls to list. + * @param addList the add list + */ public void addAllAliasAllsToList(List<ModelAliasAll> addList) { addList.addAll(this.aliasAlls); } + /** + * Add alias. + * @param entityAlias the entity alias + * @param name the name + */ public void addAlias(String entityAlias, String name) { this.addAlias(entityAlias, name, null, null, null, null, null); } @@ -246,10 +291,33 @@ public class DynamicViewEntity { addAlias(entityAlias, name, field, colAlias, primKey, groupBy, function, null, null); } + /** + * Add alias. + * @param entityAlias the entity alias + * @param name the name + * @param field the field + * @param colAlias the col alias + * @param primKey the prim key + * @param groupBy the group by + * @param function the function + * @param complexAliasMember the complex alias member + */ public void addAlias(String entityAlias, String name, String field, String colAlias, Boolean primKey, Boolean groupBy, String function, ComplexAliasMember complexAliasMember) { addAlias(entityAlias, name, field, colAlias, primKey, groupBy, function, null, complexAliasMember); } + /** + * Add alias. + * @param entityAlias the entity alias + * @param name the name + * @param field the field + * @param colAlias the col alias + * @param primKey the prim key + * @param groupBy the group by + * @param function the function + * @param fieldSet the field set + * @param complexAliasMember the complex alias member + */ public void addAlias(String entityAlias, String name, String field, String colAlias, Boolean primKey, Boolean groupBy, String function, String fieldSet, ComplexAliasMember complexAliasMember) { if (entityAlias == null && complexAliasMember == null) { throw new IllegalArgumentException("entityAlias cannot be null if this is not a complex alias in call to DynamicViewEntity.addAlias"); @@ -265,32 +333,66 @@ public class DynamicViewEntity { this.aliases.add(alias); } + /** + * Add all aliases to list. + * @param addList the add list + */ public void addAllAliasesToList(List<ModelAlias> addList) { addList.addAll(this.aliases); } + /** + * Add view link. + * @param entityAlias the entity alias + * @param relEntityAlias the rel entity alias + * @param relOptional the rel optional + * @param modelKeyMaps the model key maps + */ public void addViewLink(String entityAlias, String relEntityAlias, Boolean relOptional, List<ModelKeyMap> modelKeyMaps) { ModelViewLink modelViewLink = new ModelViewLink(entityAlias, relEntityAlias, relOptional, null, modelKeyMaps); this.viewLinks.add(modelViewLink); } + /** + * Add all view links to list. + * @param addList the add list + */ public void addAllViewLinksToList(List<ModelViewLink> addList) { addList.addAll(this.viewLinks); } + /** + * Add relation. + * @param type the type + * @param title the title + * @param relEntityName the rel entity name + * @param modelKeyMaps the model key maps + */ public void addRelation(String type, String title, String relEntityName, List<ModelKeyMap> modelKeyMaps) { ModelRelation relation = ModelRelation.create(null, null, type, title, relEntityName, null, modelKeyMaps, false); this.relations.add(relation); } + /** + * Add all relations to list. + * @param addList the add list + */ public void addAllRelationsToList(List<ModelRelation> addList) { addList.addAll(this.relations); } + /** + * Sets group by. + * @param groupBy the group by + */ public void setGroupBy(List<String> groupBy) { this.groupBy = groupBy; } + /** + * Add all group by fields to list. + * @param addList the add list + */ public void addAllGroupByFieldsToList(List<String> addList) { if (groupBy != null) { addList.addAll(this.groupBy); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntity.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntity.java index 0a3a963..b224810 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntity.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelEntity.java @@ -56,7 +56,6 @@ import org.w3c.dom.Element; /** * An object that models the <code><entity></code> element. - * */ @SuppressWarnings("serial") public class ModelEntity implements Comparable<ModelEntity>, Serializable { @@ -75,19 +74,19 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { private final ModelReader modelReader; /** The entity-name of the Entity */ - protected String entityName = ""; + private String entityName = ""; /** The table-name of the Entity */ - protected String tableName = ""; + private String tableName = ""; /** The package-name of the Entity */ - protected String packageName = ""; + private String packageName = ""; /** The entity-name of the Entity that this Entity is dependent on, if empty then no dependency */ - protected String dependentOn = ""; + private String dependentOn = ""; /** The sequence-bank-size of the Entity */ - protected Integer sequenceBankSize = null; + private Integer sequenceBankSize = null; /** Synchronization object used to control access to the ModelField collection objects. * A single lock is used for all ModelField collections so collection updates are atomic. */ @@ -108,38 +107,38 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { private final ArrayList<ModelField> nopks = new ArrayList<>(); /** relations defining relationships between this entity and other entities */ - protected CopyOnWriteArrayList<ModelRelation> relations = new CopyOnWriteArrayList<>(); + private CopyOnWriteArrayList<ModelRelation> relations = new CopyOnWriteArrayList<>(); /** indexes on fields/columns in this entity */ private CopyOnWriteArrayList<ModelIndex> indexes = new CopyOnWriteArrayList<>(); /** The reference of the dependentOn entity model */ - protected ModelEntity specializationOfModelEntity = null; + private ModelEntity specializationOfModelEntity = null; /** The list of entities that are specialization of on this entity */ - protected Map<String, ModelEntity> specializedEntities = new HashMap<>(); + private Map<String, ModelEntity> specializedEntities = new HashMap<>(); /** map of ModelViewEntities that references this model */ private final Set<String> viewEntities = new HashSet<>(); /** An indicator to specify if this entity requires locking for updates */ - protected boolean doLock = false; + private boolean doLock = false; /** Can be used to disable automatically creating update stamp fields and populating them on inserts and updates */ - protected boolean noAutoStamp = false; + private boolean noAutoStamp = false; /** An indicator to specify if this entity is never cached. * If true causes the delegator to not clear caches on write and to not get * from cache on read showing a warning messages to that effect */ - protected boolean neverCache = false; + private boolean neverCache = false; - protected boolean neverCheck = false; + private boolean neverCheck = false; - protected boolean autoClearCache = true; + private boolean autoClearCache = true; /** The location of this entity's definition */ - protected String location = ""; + private String location = ""; // ===== CONSTRUCTORS ===== /** Default Constructor */ @@ -390,9 +389,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { this.dependentOn = UtilXml.checkEmpty(extendEntityElement.getAttribute("dependent-on")).intern(); } - // ===== GETTERS/SETTERS ===== - - + /** + * Gets model reader. + * @return the model reader + */ public ModelReader getModelReader() { return modelReader; } @@ -402,6 +402,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.entityName; } + /** + * Sets entity name. + * @param entityName the entity name + */ public void setEntityName(String entityName) { this.entityName = entityName; } @@ -425,6 +429,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Sets table name. + * @param tableName the table name + */ public void setTableName(String tableName) { this.tableName = tableName; } @@ -434,6 +442,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.packageName; } + /** + * Sets package name. + * @param packageName the package name + */ public void setPackageName(String packageName) { this.packageName = packageName; } @@ -443,6 +455,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.dependentOn; } + /** + * Sets dependent on. + * @param dependentOn the dependent on + */ public void setDependentOn(String dependentOn) { this.dependentOn = dependentOn; } @@ -455,6 +471,10 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.neverCache; } + /** + * Sets never cache. + * @param neverCache the never cache + */ public void setNeverCache(boolean neverCache) { this.neverCache = neverCache; } @@ -468,18 +488,34 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return neverCheck; } + /** + * Sets never check. + * @param neverCheck the never check + */ public void setNeverCheck(boolean neverCheck) { this.neverCheck = neverCheck; } + /** + * Gets auto clear cache. + * @return the auto clear cache + */ public boolean getAutoClearCache() { return this.autoClearCache; } + /** + * Sets auto clear cache. + * @param autoClearCache the auto clear cache + */ public void setAutoClearCache(boolean autoClearCache) { this.autoClearCache = autoClearCache; } + /** + * Gets has field with audit log. + * @return the has field with audit log + */ public boolean getHasFieldWithAuditLog() { for (ModelField mf : getFieldsUnmodifiable()) { if (mf.getEnableAuditLog()) { @@ -489,12 +525,12 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return false; } - /* Get the location of this entity's definition */ + /** Get the location of this entity's definition */ public String getLocation() { return this.location; } - /* Set the location of this entity's definition */ + /** Set the location of this entity's definition */ public void setLocation(String location) { this.location = location; } @@ -504,10 +540,18 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.doLock; } + /** + * Sets do lock. + * @param doLock the do lock + */ public void setDoLock(boolean doLock) { this.doLock = doLock; } + /** + * Lock boolean. + * @return the boolean + */ public boolean lock() { if (doLock && isField(STAMP_FIELD)) { return true; @@ -517,10 +561,19 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Gets sequence bank size. + * @return the sequence bank size + */ public Integer getSequenceBankSize() { return this.sequenceBankSize; } + /** + * Is field boolean. + * @param fieldName the field name + * @return the boolean + */ public boolean isField(String fieldName) { if (fieldName == null) return false; synchronized (fieldsLock) { @@ -528,6 +581,11 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Are fields boolean. + * @param fieldNames the field names + * @return the boolean + */ public boolean areFields(Collection<String> fieldNames) { if (fieldNames == null) return false; for (String fieldName: fieldNames) { @@ -536,12 +594,20 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return true; } + /** + * Gets pks size. + * @return the pks size + */ public int getPksSize() { synchronized (fieldsLock) { return this.pks.size(); } } + /** + * Gets only pk. + * @return the only pk + */ public ModelField getOnlyPk() { synchronized (fieldsLock) { if (this.pks.size() == 1) { @@ -552,20 +618,36 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Gets pks iterator. + * @return the pks iterator + */ public Iterator<ModelField> getPksIterator() { return getPkFields().iterator(); } + /** + * Gets pk fields. + * @return the pk fields + */ public List<ModelField> getPkFields() { synchronized (fieldsLock) { return new ArrayList<>(this.pks); } } + /** + * Gets pk fields unmodifiable. + * @return the pk fields unmodifiable + */ public List<ModelField> getPkFieldsUnmodifiable() { return Collections.unmodifiableList(getPkFields()); } + /** + * Gets first pk field name. + * @return the first pk field name + */ public String getFirstPkFieldName() { List<String> pkFieldNames = this.getPkFieldNames(); String idFieldName = null; @@ -575,12 +657,20 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return idFieldName; } + /** + * Gets nopks size. + * @return the nopks size + */ public int getNopksSize() { synchronized (fieldsLock) { return this.nopks.size(); } } + /** + * Gets nopks iterator. + * @return the nopks iterator + */ public Iterator<ModelField> getNopksIterator() { return getNopksCopy().iterator(); } @@ -808,26 +898,54 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Convert to view values list. + * @param viewEntityName the view entity name + * @param entity the entity + * @return the list + */ public List<? extends Map<String, Object>> convertToViewValues(String viewEntityName, GenericEntity entity) { if (entity == null || entity == GenericEntity.NULL_ENTITY || entity == GenericValue.NULL_VALUE) return UtilMisc.toList(entity); ModelViewEntity view = (ModelViewEntity) entity.getDelegator().getModelEntity(viewEntityName); return view.convert(getEntityName(), entity); } + /** + * Remove view entity boolean. + * @param viewEntityName the view entity name + * @return the boolean + */ public boolean removeViewEntity(String viewEntityName) { synchronized (viewEntities) { return this.viewEntities.remove(viewEntityName); } } + /** + * Remove view entity boolean. + * @param viewEntity the view entity + * @return the boolean + */ public boolean removeViewEntity(ModelViewEntity viewEntity) { - return removeViewEntity(viewEntity.getEntityName()); + return removeViewEntity(viewEntity.getEntityName()); } + /** + * Name string string. + * @param flds the flds + * @return the string + */ public String nameString(List<ModelField> flds) { return nameString(flds, ", ", ""); } + /** + * Name string string. + * @param flds the flds + * @param separator the separator + * @param afterLast the after last + * @return the string + */ public String nameString(List<ModelField> flds, String separator, String afterLast) { StringBuilder returnString = new StringBuilder(); @@ -873,30 +991,62 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return returnString.toString(); } + /** + * Field name string string. + * @return the string + */ public String fieldNameString() { return fieldNameString(", ", ""); } + /** + * Field name string string. + * @param separator the separator + * @param afterLast the after last + * @return the string + */ public String fieldNameString(String separator, String afterLast) { return nameString(getFieldsUnmodifiable(), separator, afterLast); } + /** + * Field type name string string. + * @return the string + */ public String fieldTypeNameString() { return typeNameString(getFieldsUnmodifiable()); } + /** + * Prim key class name string string. + * @return the string + */ public String primKeyClassNameString() { return typeNameString(getPkFields()); } + /** + * Pk name string string. + * @return the string + */ public String pkNameString() { return pkNameString(", ", ""); } + /** + * Pk name string string. + * @param separator the separator + * @param afterLast the after last + * @return the string + */ public String pkNameString(String separator, String afterLast) { return nameString(getPkFields(), separator, afterLast); } + /** + * Non pk null list string. + * @return the string + */ public String nonPkNullList() { return fieldsStringList(getFieldsUnmodifiable(), "null", ", ", false, true); } @@ -906,37 +1056,103 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return fieldsStringList(Arrays.asList(flds), eachString, separator, false, false); } + /** + * Fields string list string builder. + * @param sb the sb + * @param eachString the each string + * @param separator the separator + * @param flds the flds + * @return the string builder + */ public StringBuilder fieldsStringList(StringBuilder sb, String eachString, String separator, ModelField... flds) { return fieldsStringList(Arrays.asList(flds), sb, eachString, separator, false, false); } + /** + * Fields string list string. + * @param flds the flds + * @param eachString the each string + * @param separator the separator + * @return the string + */ @Deprecated public String fieldsStringList(List<ModelField> flds, String eachString, String separator) { return fieldsStringList(flds, eachString, separator, false, false); } + /** + * Fields string list string builder. + * @param flds the flds + * @param sb the sb + * @param eachString the each string + * @param separator the separator + * @return the string builder + */ public StringBuilder fieldsStringList(List<ModelField> flds, StringBuilder sb, String eachString, String separator) { return fieldsStringList(flds, sb, eachString, separator, false, false); } + /** + * Fields string list string. + * @param eachString the each string + * @param separator the separator + * @param appendIndex the append index + * @param flds the flds + * @return the string + */ @Deprecated public String fieldsStringList(String eachString, String separator, boolean appendIndex, ModelField... flds) { return fieldsStringList(Arrays.asList(flds), eachString, separator, appendIndex, false); } + /** + * Fields string list string builder. + * @param sb the sb + * @param eachString the each string + * @param separator the separator + * @param appendIndex the append index + * @param flds the flds + * @return the string builder + */ public StringBuilder fieldsStringList(StringBuilder sb, String eachString, String separator, boolean appendIndex, ModelField... flds) { return fieldsStringList(Arrays.asList(flds), sb, eachString, separator, appendIndex, false); } + /** + * Fields string list string. + * @param flds the flds + * @param eachString the each string + * @param separator the separator + * @param appendIndex the append index + * @return the string + */ @Deprecated public String fieldsStringList(List<ModelField> flds, String eachString, String separator, boolean appendIndex) { return fieldsStringList(flds, eachString, separator, appendIndex, false); } + /** + * Fields string list string builder. + * @param flds the flds + * @param sb the sb + * @param eachString the each string + * @param separator the separator + * @param appendIndex the append index + * @return the string builder + */ public StringBuilder fieldsStringList(List<ModelField> flds, StringBuilder sb, String eachString, String separator, boolean appendIndex) { return fieldsStringList(flds, sb, eachString, separator, appendIndex, false); } + /** + * Fields string list string. + * @param eachString the each string + * @param separator the separator + * @param appendIndex the append index + * @param onlyNonPK the only non pk + * @param flds the flds + * @return the string + */ @Deprecated public String fieldsStringList(String eachString, String separator, boolean appendIndex, boolean onlyNonPK, ModelField... flds) { return fieldsStringList(Arrays.asList(flds), eachString, separator, appendIndex, onlyNonPK); @@ -967,38 +1183,98 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return sb; } + /** + * Col name string string. + * @param flds the flds + * @return the string + */ @Deprecated public String colNameString(ModelField... flds) { return colNameString(new StringBuilder(), "", flds).toString(); } + /** + * Col name string string builder. + * @param sb the sb + * @param prefix the prefix + * @param flds the flds + * @return the string builder + */ public StringBuilder colNameString(StringBuilder sb, String prefix, ModelField... flds) { return colNameString(Arrays.asList(flds), sb, prefix); } + /** + * Col name string string. + * @param flds the flds + * @return the string + */ @Deprecated public String colNameString(List<ModelField> flds) { return colNameString(flds, new StringBuilder(), "", ", ", "", false).toString(); } + /** + * Col name string string builder. + * @param flds the flds + * @param sb the sb + * @param prefix the prefix + * @return the string builder + */ public StringBuilder colNameString(List<ModelField> flds, StringBuilder sb, String prefix) { return colNameString(flds, sb, prefix, ", ", "", false); } + /** + * Col name string string. + * @param separator the separator + * @param afterLast the after last + * @param alias the alias + * @param flds the flds + * @return the string + */ @Deprecated public String colNameString(String separator, String afterLast, boolean alias, ModelField... flds) { return colNameString(Arrays.asList(flds), new StringBuilder(), "", separator, afterLast, alias).toString(); } + /** + * Col name string string builder. + * @param sb the sb + * @param prefix the prefix + * @param separator the separator + * @param afterLast the after last + * @param alias the alias + * @param flds the flds + * @return the string builder + */ public StringBuilder colNameString(StringBuilder sb, String prefix, String separator, String afterLast, boolean alias, ModelField... flds) { return colNameString(Arrays.asList(flds), sb, prefix, separator, afterLast, alias); } + /** + * Col name string string. + * @param flds the flds + * @param separator the separator + * @param afterLast the after last + * @param alias the alias + * @return the string + */ @Deprecated public String colNameString(List<ModelField> flds, String separator, String afterLast, boolean alias) { return colNameString(flds, new StringBuilder(), "", separator, afterLast, alias).toString(); } + /** + * Col name string string builder. + * @param flds the flds + * @param sb the sb + * @param prefix the prefix + * @param separator the separator + * @param afterLast the after last + * @param alias the alias + * @return the string builder + */ public StringBuilder colNameString(List<ModelField> flds, StringBuilder sb, String prefix, String separator, String afterLast, boolean alias) { if (flds.size() < 1) { return sb; @@ -1340,9 +1616,20 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return this.getEntityName().compareTo(otherModelEntity.getEntityName()); } + /** + * Convert field map in place. + * @param inContext the in context + * @param delegator the delegator + */ public void convertFieldMapInPlace(Map<String, Object> inContext, Delegator delegator) { convertFieldMapInPlace(inContext, delegator.getModelFieldTypeReader(this)); } + + /** + * Convert field map in place. + * @param inContext the in context + * @param modelFieldTypeReader the model field type reader + */ public void convertFieldMapInPlace(Map<String, Object> inContext, ModelFieldTypeReader modelFieldTypeReader) { Iterator<ModelField> modelFields = this.getFieldsIterator(); while (modelFields.hasNext()) { @@ -1355,6 +1642,13 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { } } + /** + * Convert field value object. + * @param fieldName the field name + * @param value the value + * @param delegator the delegator + * @return the object + */ public Object convertFieldValue(String fieldName, Object value, Delegator delegator) { ModelField modelField = this.getField(fieldName); if (modelField == null) { @@ -1364,6 +1658,13 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return convertFieldValue(modelField, value, delegator); } + /** + * Convert field value object. + * @param modelField the model field + * @param value the value + * @param delegator the delegator + * @return the object + */ public Object convertFieldValue(ModelField modelField, Object value, Delegator delegator) { if (value == null || value == GenericEntity.NULL_FIELD) { return null; @@ -1683,26 +1984,58 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable { return topLevelMap; } + /** + * Gets author. + * @return the author + */ public String getAuthor() { return modelInfo.getAuthor(); } + /** + * Gets copyright. + * @return the copyright + */ public String getCopyright() { return modelInfo.getCopyright(); } + /** + * Gets default resource name. + * @return the default resource name + */ public String getDefaultResourceName() { return modelInfo.getDefaultResourceName(); } + /** + * Gets description. + * @return the description + */ public String getDescription() { return modelInfo.getDescription(); } + /** + * Gets relations. + * @return the relations + */ + public CopyOnWriteArrayList<ModelRelation> getRelations() { + return relations; + } + + /** + * Gets title. + * @return the title + */ public String getTitle() { return modelInfo.getTitle(); } + /** + * Gets version. + * @return the version + */ public String getVersion() { return modelInfo.getVersion(); } 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 63a8cec..0101ca8 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 @@ -78,32 +78,32 @@ public class ModelViewEntity extends ModelEntity { } /** Contains member-entity alias name definitions: key is alias, value is ModelMemberEntity */ - protected Map<String, ModelMemberEntity> memberModelMemberEntities = new HashMap<>(); + private Map<String, ModelMemberEntity> memberModelMemberEntities = new HashMap<>(); /** A list of all ModelMemberEntity entries; this is mainly used to preserve the original order of member entities from the XML file */ - protected List<ModelMemberEntity> allModelMemberEntities = new LinkedList<>(); + private List<ModelMemberEntity> allModelMemberEntities = new LinkedList<>(); /** Contains member-entity ModelEntities: key is alias, value is ModelEntity; populated with fields */ - protected Map<String, String> memberModelEntities = new HashMap<>(); + private Map<String, String> memberModelEntities = new HashMap<>(); /** List of alias-alls which act as a shortcut for easily pulling over member entity fields */ - protected List<ModelAliasAll> aliasAlls = new LinkedList<>(); + private List<ModelAliasAll> aliasAlls = new LinkedList<>(); /** List of aliases with information in addition to what is in the standard field list */ - protected List<ModelAlias> aliases = new LinkedList<>(); + private List<ModelAlias> aliases = new LinkedList<>(); /** List of view links to define how entities are connected (or "joined") */ - protected List<ModelViewLink> viewLinks = new LinkedList<>(); + private List<ModelViewLink> viewLinks = new LinkedList<>(); /** A List of the Field objects for the View Entity, one for each GROUP BY field */ - protected List<ModelField> groupBys = new LinkedList<>(); + private List<ModelField> groupBys = new LinkedList<>(); /** List of field names to group by */ - protected List<String> groupByFields = new LinkedList<>(); + private List<String> groupByFields = new LinkedList<>(); - protected Map<String, ModelConversion[]> conversions = new HashMap<>(); + private Map<String, ModelConversion[]> conversions = new HashMap<>(); - protected ViewEntityCondition viewEntityCondition = null; + private ViewEntityCondition viewEntityCondition = null; public ModelViewEntity(ModelReader reader, Element entityElement, UtilTimer utilTimer, ModelInfo def) { super(reader, entityElement, def); @@ -116,7 +116,8 @@ public class ModelViewEntity extends ModelEntity { String alias = UtilXml.checkEmpty(memberEntityElement.getAttribute("entity-alias")).intern(); String name = UtilXml.checkEmpty(memberEntityElement.getAttribute("entity-name")).intern(); if (name.length() <= 0 || alias.length() <= 0) { - Debug.logError("[new ModelViewEntity]: entity-alias or entity-name missing on member-entity element of the view-entity " + this.entityName, MODULE); + Debug.logError("[new ModelViewEntity]: entity-alias or entity-name missing on member-entity element of the view-entity " + + this.getEntityName(), MODULE); } else { ModelMemberEntity modelMemberEntity = new ModelMemberEntity(alias, name); this.addMemberModelMemberEntity(modelMemberEntity); @@ -150,7 +151,7 @@ public class ModelViewEntity extends ModelEntity { } // before finishing, make sure the table name is null, this should help bring up errors early... - this.tableName = null; + this.setTableName(null); } public ModelViewEntity(DynamicViewEntity dynamicViewEntity, ModelReader modelReader) { @@ -161,8 +162,8 @@ public class ModelViewEntity extends ModelEntity { ModelInfo.DEFAULT.getAuthor(), ModelInfo.DEFAULT.getVersion(), dynamicViewEntity.getDefaultResourceName())); - this.entityName = dynamicViewEntity.getEntityName(); - this.packageName = dynamicViewEntity.getPackageName(); + this.setEntityName(dynamicViewEntity.getEntityName()); + this.setPackageName(dynamicViewEntity.getPackageName()); // member-entities Iterator<Map.Entry<String, ModelMemberEntity>> modelMemberEntitiesEntryIter = dynamicViewEntity.getModelMemberEntitiesEntryIter(); @@ -181,37 +182,64 @@ public class ModelViewEntity extends ModelEntity { dynamicViewEntity.addAllViewLinksToList(this.viewLinks); // relations - dynamicViewEntity.addAllRelationsToList(this.relations); + dynamicViewEntity.addAllRelationsToList(this.getRelations()); dynamicViewEntity.addAllGroupByFieldsToList(this.groupByFields); // finalize stuff - // note that this doesn't result in a call to populateReverseLinks because a DynamicViewEntity should never be cached anyway, and will blow up when attempting to make the reverse links to the DynamicViewEntity + // note that this doesn't result in a call to populateReverseLinks because a DynamicViewEntity should never be cached anyway, + // and will blow up when attempting to make the reverse links to the DynamicViewEntity this.populateFieldsBasic(modelReader); } + /** + * Gets member model member entities. + * @return the member model member entities + */ public Map<String, ModelMemberEntity> getMemberModelMemberEntities() { return this.memberModelMemberEntities; } + /** + * Gets all model member entities. + * @return the all model member entities + */ public List<ModelMemberEntity> getAllModelMemberEntities() { return this.allModelMemberEntities; } + /** + * Gets member model member entity. + * @param alias the alias + * @return the member model member entity + */ public ModelMemberEntity getMemberModelMemberEntity(String alias) { return this.memberModelMemberEntities.get(alias); } + /** + * Gets member model entity. + * @param alias the alias + * @return the member model entity + */ public ModelEntity getMemberModelEntity(String alias) { String entityName = this.memberModelEntities.get(alias); return entityName != null ? this.getModelReader().getModelEntityNoCheck(entityName) : null; } + /** + * Add member model member entity. + * @param modelMemberEntity the model member entity + */ public void addMemberModelMemberEntity(ModelMemberEntity modelMemberEntity) { this.memberModelMemberEntities.put(modelMemberEntity.getEntityAlias(), modelMemberEntity); this.allModelMemberEntities.add(modelMemberEntity); } + /** + * Remove member model member entity. + * @param alias the alias + */ public void removeMemberModelMemberEntity(String alias) { ModelMemberEntity modelMemberEntity = this.memberModelMemberEntities.remove(alias); @@ -247,27 +275,52 @@ public class ModelViewEntity extends ModelEntity { return null; } + /** + * Gets aliases size. + * @return the aliases size + */ public int getAliasesSize() { return this.aliases.size(); } + /** + * Gets aliases iterator. + * @return the aliases iterator + */ public Iterator<ModelAlias> getAliasesIterator() { return this.aliases.iterator(); } + /** + * Gets aliases copy. + * @return the aliases copy + */ public List<ModelAlias> getAliasesCopy() { List<ModelAlias> newList = new ArrayList<>(this.aliases); return newList; } + /** + * Gets group bys size. + * @return the group bys size + */ public int getGroupBysSize() { return this.groupBys.size(); } + /** + * Gets group bys copy. + * @return the group bys copy + */ public List<ModelField> getGroupBysCopy() { return getGroupBysCopy(null); } + /** + * Gets group bys copy. + * @param selectFields the select fields + * @return the group bys copy + */ public List<ModelField> getGroupBysCopy(List<ModelField> selectFields) { List<ModelField> newList = new ArrayList<>(this.groupBys.size()); if (UtilValidate.isEmpty(selectFields)) { @@ -287,23 +340,47 @@ public class ModelViewEntity extends ModelEntity { return this.viewLinks.get(index); } + /** + * Gets view links size. + * @return the view links size + */ public int getViewLinksSize() { return this.viewLinks.size(); } + /** + * Gets view links iterator. + * @return the view links iterator + */ public Iterator<ModelViewLink> getViewLinksIterator() { return this.viewLinks.iterator(); } + /** + * Gets view links copy. + * @return the view links copy + */ public List<ModelViewLink> getViewLinksCopy() { List<ModelViewLink> newList = new ArrayList<>(this.viewLinks); return newList; } + /** + * Add view link. + * @param viewLink the view link + */ public void addViewLink(ModelViewLink viewLink) { this.viewLinks.add(viewLink); } + /** + * Populate view entity condition information. + * @param modelFieldTypeReader the model field type reader + * @param whereConditions the where conditions + * @param havingConditions the having conditions + * @param orderByList the order by list + * @param entityAliasStack the entity alias stack + */ public void populateViewEntityConditionInformation(ModelFieldTypeReader modelFieldTypeReader, List<EntityCondition> whereConditions, List<EntityCondition> havingConditions, List<String> orderByList, List<String> entityAliasStack) { if (entityAliasStack == null) { entityAliasStack = new LinkedList<>(); @@ -369,43 +446,71 @@ public class ModelViewEntity extends ModelEntity { return sb; } - protected ModelEntity aliasedModelEntity = new ModelEntity(); + private ModelEntity aliasedModelEntity = new ModelEntity(); + /** + * Gets aliased model entity. + * @return the aliased model entity + */ public ModelEntity getAliasedModelEntity() { return this.aliasedModelEntity; } + /** + * Gets aliased entity. + * @param entityAlias the entity alias + * @param modelReader the model reader + * @return the aliased entity + */ public ModelEntity getAliasedEntity(String entityAlias, ModelReader modelReader) { ModelMemberEntity modelMemberEntity = this.memberModelMemberEntities.get(entityAlias); if (modelMemberEntity == null) { - Debug.logError("[" + this.getEntityName() + "]: No member entity with alias " + entityAlias + " found; this view-entity will NOT be usable...", MODULE); + Debug.logError("[" + this.getEntityName() + "]: No member entity with alias " + entityAlias + + " found; this view-entity will NOT be usable...", MODULE); return null; } String aliasedEntityName = modelMemberEntity.getEntityName(); ModelEntity aliasedEntity = modelReader.getModelEntityNoCheck(aliasedEntityName); if (aliasedEntity == null) { - Debug.logError("[" + this.getEntityName() + "]: [ModelViewEntity.populateFields] ERROR: could not find ModelEntity for entity name: " + aliasedEntityName, MODULE); + Debug.logError("[" + this.getEntityName() + "]: [ModelViewEntity.populateFields] ERROR: could not find ModelEntity for entity name: " + + aliasedEntityName, MODULE); return null; } return aliasedEntity; } + /** + * Gets aliased field. + * @param aliasedEntity the aliased entity + * @param field the field + * @param modelReader the model reader + * @return the aliased field + */ public ModelField getAliasedField(ModelEntity aliasedEntity, String field, ModelReader modelReader) { ModelField aliasedField = aliasedEntity.getField(field); if (aliasedField == null) { - Debug.logError("[" + this.getEntityName() + "]: [ModelViewEntity.populateFields] ERROR: could not find ModelField for entity name: " + aliasedEntity.getEntityName() + " and field: " + field, MODULE); + Debug.logError("[" + this.getEntityName() + "]: [ModelViewEntity.populateFields] ERROR: could not find ModelField for entity name: " + + aliasedEntity.getEntityName() + " and field: " + field, MODULE); return null; } return aliasedField; } + /** + * Populate fields. + * @param modelReader the model reader + */ public void populateFields(ModelReader modelReader) { populateFieldsBasic(modelReader); populateReverseLinks(); } + /** + * Populate fields basic. + * @param modelReader the model reader + */ public void populateFieldsBasic(ModelReader modelReader) { for (Map.Entry<String, ModelMemberEntity> entry: memberModelMemberEntities.entrySet()) { @@ -849,20 +954,20 @@ public class ModelViewEntity extends ModelEntity { } public static final class ModelAlias implements Serializable { - public final String entityAlias; - public final String name; - public final String field; - public final String colAlias; + private final String entityAlias; + private final String name; + private final String field; + private final String colAlias; // this is a Boolean object for a tri-state: null, true or false - public final Boolean isPk; - public final boolean groupBy; + private final Boolean isPk; + private final boolean groupBy; // is specified this alias is a calculated value; can be: min, max, sum, avg, count, count-distinct - public final String function; - public final String fieldSet; - public final boolean isFromAliasAll; - public ComplexAliasMember complexAliasMember; + private final String function; + private final String fieldSet; + private final boolean isFromAliasAll; + private ComplexAliasMember complexAliasMember; // The description for documentation purposes - public String description = ""; + private String description = ""; public ModelAlias(Element aliasElement) { this.entityAlias = UtilXml.checkEmpty(aliasElement.getAttribute("entity-alias")).intern(); @@ -977,8 +1082,8 @@ public class ModelViewEntity extends ModelEntity { } public static final class ComplexAlias implements ComplexAliasMember { - public final List<ComplexAliasMember> complexAliasMembers = new LinkedList<>(); - public final String operator; + private final List<ComplexAliasMember> complexAliasMembers = new LinkedList<>(); + private final String operator; public ComplexAlias(String operator) { this.operator = operator; @@ -1030,11 +1135,11 @@ public class ModelViewEntity extends ModelEntity { } public static final class ComplexAliasField implements ComplexAliasMember { - public final String entityAlias; - public final String field; - public final String defaultValue; - public final String function; - public final String value; + private final String entityAlias; + private final String field; + private final String defaultValue; + private final String function; + private final String value; public ComplexAliasField(Element complexAliasFieldElement) { this.entityAlias = complexAliasFieldElement.getAttribute("entity-alias").intern(); @@ -1068,8 +1173,7 @@ public class ModelViewEntity extends ModelEntity { && UtilValidate.isEmpty(field) && UtilValidate.isNotEmpty(value)) { colNameBuffer.append(value); - } - else { + } else { ModelEntity modelEntity = modelViewEntity.getAliasedEntity(entityAlias, modelReader); ModelField modelField = modelViewEntity.getAliasedField(modelEntity, field, modelReader); String colName = entityAlias + "." + modelField.getColName(); @@ -1097,11 +1201,11 @@ public class ModelViewEntity extends ModelEntity { } public static final class ModelViewLink implements Serializable, Iterable<ModelKeyMap> { - public final String entityAlias; - public final String relEntityAlias; - public final boolean relOptional; - public final List<ModelKeyMap> keyMaps = new LinkedList<>(); - public final ViewEntityCondition viewEntityCondition; + private final String entityAlias; + private final String relEntityAlias; + private final boolean relOptional; + private final List<ModelKeyMap> keyMaps = new LinkedList<>(); + private final ViewEntityCondition viewEntityCondition; public ModelViewLink(ModelViewEntity modelViewEntity, Element viewLinkElement) { this.entityAlias = UtilXml.checkEmpty(viewLinkElement.getAttribute("entity-alias")).intern(); @@ -1192,10 +1296,10 @@ public class ModelViewEntity extends ModelEntity { } public final class ModelConversion implements Serializable { - public final String aliasName; - public final ModelEntity fromModelEntity; - public final Map<String, String> fieldMap = new HashMap<>(); - public final Set<String> wildcards = new HashSet<>(); + private final String aliasName; + private final ModelEntity fromModelEntity; + private final Map<String, String> fieldMap = new HashMap<>(); + private final Set<String> wildcards = new HashSet<>(); public ModelConversion(String aliasName, ModelEntity fromModelEntity) { this.aliasName = aliasName; @@ -1255,13 +1359,13 @@ public class ModelViewEntity extends ModelEntity { } public static final class ViewEntityCondition { - public final ModelViewEntity modelViewEntity; - public final ModelViewLink modelViewLink; - public final boolean filterByDate; - public final boolean distinct; - public final List<String> orderByList; - public final ViewCondition whereCondition; - public final ViewCondition havingCondition; + private final ModelViewEntity modelViewEntity; + private final ModelViewLink modelViewLink; + private final boolean filterByDate; + private final boolean distinct; + private final List<String> orderByList; + private final ViewCondition whereCondition; + private final ViewCondition havingCondition; // TODO: add programatic constructor public ViewEntityCondition(ModelViewEntity modelViewEntity, ModelViewLink modelViewLink, Element element) { @@ -1329,14 +1433,14 @@ public class ModelViewEntity extends ModelEntity { } public static final class ViewConditionExpr implements ViewCondition { - public final ViewEntityCondition viewEntityCondition; - public final String entityAlias; - public final String fieldName; - public final EntityComparisonOperator<?, ?> operator; - public final String relEntityAlias; - public final String relFieldName; - public final Object value; - public final boolean ignoreCase; + private final ViewEntityCondition viewEntityCondition; + private final String entityAlias; + private final String fieldName; + private final EntityComparisonOperator<?, ?> operator; + private final String relEntityAlias; + private final String relFieldName; + private final Object value; + private final boolean ignoreCase; // TODO: add programatic constructor public ViewConditionExpr(ViewEntityCondition viewEntityCondition, Element conditionExprElement) { @@ -1409,14 +1513,16 @@ public class ModelViewEntity extends ModelEntity { } if (Debug.verboseOn()) { - Debug.logVerbose("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + "]: Got value for fieldName [" + fieldName + "]: " + value, MODULE); + Debug.logVerbose("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + "]: Got value for fieldName [" + + fieldName + "]: " + value, MODULE); } Object rhs = null; if (value != null) { rhs = value; } else { - rhs = EntityFieldValue.makeFieldValue(this.relFieldName, this.relEntityAlias, entityAliasStack, this.viewEntityCondition.modelViewEntity); + rhs = EntityFieldValue.makeFieldValue(this.relFieldName, this.relEntityAlias, entityAliasStack, + this.viewEntityCondition.modelViewEntity); } EntityCondition entityCondition; @@ -1435,7 +1541,8 @@ public class ModelViewEntity extends ModelEntity { EntityOperator.OR, EntityCondition.makeCondition(lhs, EntityOperator.EQUALS, null)); } - } else if ( value == null && this.relFieldName == null && (this.operator == EntityOperator.EQUALS || this.operator == EntityOperator.NOT_EQUAL)) { + } else if (value == null && this.relFieldName == null && (this.operator == EntityOperator.EQUALS + || this.operator == EntityOperator.NOT_EQUAL)) { entityCondition = EntityCondition.makeCondition(lhs, this.operator, null); } else { if (ignoreCase) { @@ -1459,9 +1566,9 @@ public class ModelViewEntity extends ModelEntity { } public static final class ViewConditionList implements ViewCondition { - public final ViewEntityCondition viewEntityCondition; - public final List<ViewCondition> conditionList = new LinkedList<>(); - public final EntityJoinOperator operator; + private final ViewEntityCondition viewEntityCondition; + private final List<ViewCondition> conditionList = new LinkedList<>(); + private final EntityJoinOperator operator; public ViewConditionList(ViewEntityCondition viewEntityCondition, Element conditionListElement) { this.viewEntityCondition = viewEntityCondition; @@ -1469,7 +1576,8 @@ public class ModelViewEntity extends ModelEntity { try { this.operator = EntityOperator.lookupJoin(combine); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + "]: Could not find an entity operator for the name: " + combine); + throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + + "]: Could not find an entity operator for the name: " + combine); } List<? extends Element> subElements = UtilXml.childElementList(conditionListElement); @@ -1479,7 +1587,8 @@ public class ModelViewEntity extends ModelEntity { } else if ("condition-list".equals(subElement.getNodeName())) { conditionList.add(new ViewConditionList(this.viewEntityCondition, subElement)); } else { - throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + "]: Invalid element with name [" + subElement.getNodeName() + "] found under a condition-list element."); + throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + + "]: Invalid element with name [" + subElement.getNodeName() + "] found under a condition-list element."); } } } @@ -1489,7 +1598,8 @@ public class ModelViewEntity extends ModelEntity { try { this.operator = EntityOperator.lookupJoin(combine); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + "]: Could not find an entity operator for the name: " + combine); + throw new IllegalArgumentException("[" + this.viewEntityCondition.modelViewEntity.getEntityName() + + "]: Could not find an entity operator for the name: " + combine); } if (UtilValidate.isNotEmpty(conditionList)) { this.conditionList.addAll(conditionList); diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java index 8425e7b..e31de62 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java @@ -73,7 +73,6 @@ public class SequenceUtil { /** * Gets next seq id. - * * @param seqName the seq name * @param staggerMax the stagger max * @param seqModelEntity the seq model entity @@ -86,7 +85,6 @@ public class SequenceUtil { /** * Force bank refresh. - * * @param seqName the seq name * @param staggerMax the stagger max */ diff --git a/framework/entityext/src/main/java/org/apache/ofbiz/entityext/permission/EntityPermissionChecker.java b/framework/entityext/src/main/java/org/apache/ofbiz/entityext/permission/EntityPermissionChecker.java index 061ce39..b9a7851 100644 --- a/framework/entityext/src/main/java/org/apache/ofbiz/entityext/permission/EntityPermissionChecker.java +++ b/framework/entityext/src/main/java/org/apache/ofbiz/entityext/permission/EntityPermissionChecker.java @@ -60,13 +60,13 @@ public class EntityPermissionChecker { private static final String MODULE = EntityPermissionChecker.class.getName(); - protected FlexibleStringExpander entityIdExdr; - protected FlexibleStringExpander entityNameExdr; - protected boolean displayFailCond; - protected List<String> targetOperationList; - protected PermissionConditionGetter permissionConditionGetter; - protected RelatedRoleGetter relatedRoleGetter; - protected AuxiliaryValueGetter auxiliaryValueGetter; + private FlexibleStringExpander entityIdExdr; + private FlexibleStringExpander entityNameExdr; + private boolean displayFailCond; + private List<String> targetOperationList; + private PermissionConditionGetter permissionConditionGetter; + private RelatedRoleGetter relatedRoleGetter; + private AuxiliaryValueGetter auxiliaryValueGetter; public EntityPermissionChecker(Element element) { this.entityNameExdr = FlexibleStringExpander.getInstance(element.getAttribute("entity-name")); @@ -102,6 +102,11 @@ public class EntityPermissionChecker { } + /** + * Run permission check boolean. + * @param context the context + * @return the boolean + */ public boolean runPermissionCheck(Map<String, ?> context) { boolean passed = false; @@ -213,7 +218,9 @@ public class EntityPermissionChecker { } - public static boolean checkPermissionMethod(Delegator delegator, GenericValue userLogin, List<String> targetOperationList, String entityName, List<? extends Object> entityIdList, List<String> purposeList, List<String> roleList, String privilegeEnumId) throws GenericEntityException { + public static boolean checkPermissionMethod(Delegator delegator, GenericValue userLogin, List<String> targetOperationList, String entityName, + List<? extends Object> entityIdList, List<String> purposeList, List<String> roleList, String privilegeEnumId) + throws GenericEntityException { boolean passed = false; String lcEntityName = entityName.toLowerCase(); @@ -232,12 +239,14 @@ public class EntityPermissionChecker { } ModelEntity modelEntity = delegator.getModelEntity(entityName); boolean hasStatusField = false; - if (modelEntity.getField("statusId") != null) + if (modelEntity.getField("statusId") != null) { hasStatusField = true; + } boolean hasPrivilegeField = false; - if (modelEntity.getField("privilegeEnumId") != null) + if (modelEntity.getField("privilegeEnumId") != null) { hasPrivilegeField = true; + } ModelEntity modelOperationEntity = delegator.getModelEntity(entityName + "PurposeOperation"); if (modelOperationEntity == null) { modelOperationEntity = delegator.getModelEntity(entityName + "Operation"); @@ -249,14 +258,17 @@ public class EntityPermissionChecker { } boolean hasPurposeOp = false; - if (modelOperationEntity.getField(lcEntityName + "PurposeTypeId") != null) + if (modelOperationEntity.getField(lcEntityName + "PurposeTypeId") != null) { hasPurposeOp = true; + } boolean hasStatusOp = false; - if (modelOperationEntity.getField("statusId") != null) + if (modelOperationEntity.getField("statusId") != null) { hasStatusOp = true; + } boolean hasPrivilegeOp = false; - if (modelOperationEntity.getField("privilegeEnumId") != null) - hasPrivilegeOp = true; + if (modelOperationEntity.getField("privilegeEnumId") != null) { + hasPrivilegeOp = true; + } // Get all the condition operations that could apply, rather than having to go thru // entire table each time. @@ -939,16 +951,16 @@ public class EntityPermissionChecker { public static class StdPermissionConditionGetter implements PermissionConditionGetter { - protected List<GenericValue> entityList; - protected List<String> operationList; - protected ListIterator<GenericValue> iter; - protected GenericValue currentValue; - protected String operationFieldName; - protected String roleFieldName; - protected String statusFieldName; - protected String privilegeFieldName; - protected String auxiliaryFieldName; - protected String entityName; + private List<GenericValue> entityList; + private List<String> operationList; + private ListIterator<GenericValue> iter; + private GenericValue currentValue; + private String operationFieldName; + private String roleFieldName; + private String statusFieldName; + private String privilegeFieldName; + private String auxiliaryFieldName; + private String entityName; public StdPermissionConditionGetter () { @@ -1155,12 +1167,12 @@ public class EntityPermissionChecker { public static class StdAuxiliaryValueGetter implements AuxiliaryValueGetter { - protected List<String> entityList = new LinkedList<>(); - protected String auxiliaryFieldName; - protected String entityName; - protected String entityIdName; + private List<String> entityList = new LinkedList<>(); + private String auxiliaryFieldName; + private String entityName; + private String entityIdName; - public StdAuxiliaryValueGetter ( ) { + public StdAuxiliaryValueGetter() { this.auxiliaryFieldName = "contentPurposeTypeId"; this.entityName = "ContentPurpose"; @@ -1236,13 +1248,13 @@ public class EntityPermissionChecker { public static class StdRelatedRoleGetter implements RelatedRoleGetter { - protected List<String> roleIdList = new LinkedList<>(); - protected String roleTypeFieldName; - protected String partyFieldName; - protected String entityName; - protected String roleEntityIdName; - protected String roleEntityName; - protected String ownerEntityFieldName; + private List<String> roleIdList = new LinkedList<>(); + private String roleTypeFieldName; + private String partyFieldName; + private String entityName; + private String roleEntityIdName; + private String roleEntityName; + private String ownerEntityFieldName; public StdRelatedRoleGetter() { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleServiceEngine.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleServiceEngine.java index e829ace..d597cdf 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleServiceEngine.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleServiceEngine.java @@ -45,8 +45,9 @@ public final class SimpleServiceEngine extends GenericAsyncEngine { @Override public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { Map<String, Object> result = serviceInvoker(localName, modelService, context); - if (result == null) + if (result == null) { throw new GenericServiceException("Service did not return expected result"); + } return result; } @@ -61,22 +62,26 @@ public final class SimpleServiceEngine extends GenericAsyncEngine { } // Invoke the simple method from a service context - private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, ? extends Object> context) throws GenericServiceException { + private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, ? extends Object> context) + throws GenericServiceException { // static java service methods should be: public Map methodName(DispatchContext dctx, Map context) - DispatchContext dctx = dispatcher.getLocalContext(localName); + DispatchContext dctx = getDispatcher().getLocalContext(localName); // check the package and method names - if (modelService.location == null || modelService.invoke == null) + if (modelService.getLocation() == null || modelService.getInvoke() == null) { throw new GenericServiceException("Cannot locate service to invoke (location or invoke name missing)"); + } // get the classloader to use ClassLoader classLoader = null; - if (dctx != null) + if (dctx != null) { classLoader = dctx.getClassLoader(); + } // if the classLoader is null, no big deal, SimpleMethod will use the // current thread's ClassLoader by default if null passed in try { - return SimpleMethod.runSimpleService(this.getLocation(modelService), modelService.invoke, dctx, context, classLoader); + return SimpleMethod.runSimpleService(this.getLocation(modelService), modelService.getInvoke(), dctx, context, classLoader); } catch (MiniLangException e) { - throw new GenericServiceException("Error running simple method [" + modelService.invoke + "] in XML file [" + modelService.location + "]: ", e); + throw new GenericServiceException("Error running simple method [" + modelService.getInvoke() + "] in XML file [" + + modelService.getLocation() + "]: ", e); } } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/callops/CallService.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/callops/CallService.java index ebadacf..968e0cf 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/callops/CallService.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/callops/CallService.java @@ -79,11 +79,15 @@ public final class CallService extends MethodOperation { public CallService(Element element, SimpleMethod simpleMethod) throws MiniLangException { super(element, simpleMethod); if (MiniLangValidate.validationOn()) { - MiniLangValidate.attributeNames(simpleMethod, element, "service-name", "in-map-name", "include-user-login", "break-on-error", "error-code", "require-new-transaction", "transaction-timeout", "success-code"); - MiniLangValidate.constantAttributes(simpleMethod, element, "include-user-login", "break-on-error", "error-code", "require-new-transaction", "transaction-timeout", "success-code"); + MiniLangValidate.attributeNames(simpleMethod, element, "service-name", "in-map-name", "include-user-login", + "break-on-error", "error-code", "require-new-transaction", "transaction-timeout", "success-code"); + MiniLangValidate.constantAttributes(simpleMethod, element, "include-user-login", "break-on-error", "error-code", + "require-new-transaction", "transaction-timeout", "success-code"); MiniLangValidate.expressionAttributes(simpleMethod, element, "service-name", "in-map-name"); MiniLangValidate.requiredAttributes(simpleMethod, element, "service-name"); - MiniLangValidate.childElements(simpleMethod, element, "error-prefix", "error-suffix", "success-prefix", "success-suffix", "message-prefix", "message-suffix", "default-message", "results-to-map", "result-to-field", "result-to-request", "result-to-session", "result-to-result"); + MiniLangValidate.childElements(simpleMethod, element, "error-prefix", "error-suffix", "success-prefix", + "success-suffix", "message-prefix", "message-suffix", "default-message", "results-to-map", "result-to-field", + "result-to-request", "result-to-session", "result-to-result"); } serviceNameFse = FlexibleStringExpander.getInstance(element.getAttribute("service-name")); inMapFma = FlexibleMapAccessor.getInstance(element.getAttribute("in-map-name")); @@ -97,7 +101,8 @@ public final class CallService extends MethodOperation { try { timeout = Integer.parseInt(timeoutStr); } catch (NumberFormatException e) { - MiniLangValidate.handleError("Exception thrown while parsing transaction-timeout attribute: " + e.getMessage(), simpleMethod, element); + MiniLangValidate.handleError("Exception thrown while parsing transaction-timeout attribute: " + e.getMessage(), + simpleMethod, element); timeout = 0; } } @@ -109,7 +114,7 @@ public final class CallService extends MethodOperation { successSuffix = new FlexibleMessage(UtilXml.firstChildElement(element, "success-suffix"), "service.success.suffix"); messagePrefix = new FlexibleMessage(UtilXml.firstChildElement(element, "message-prefix"), "service.message.prefix"); messageSuffix = new FlexibleMessage(UtilXml.firstChildElement(element, "message-suffix"), "service.message.suffix"); - defaultMessage = new FlexibleMessage(UtilXml.firstChildElement(element, "default-message"), null);// "service.default.message" + defaultMessage = new FlexibleMessage(UtilXml.firstChildElement(element, "default-message"), null); List<? extends Element> resultsToMapElements = UtilXml.childElementList(element, "results-to-map"); if (UtilValidate.isNotEmpty(resultsToMapElements)) { List<String> resultsToMapList = new ArrayList<>(resultsToMapElements.size()); @@ -206,19 +211,21 @@ public final class CallService extends MethodOperation { Map<String, Object> result = null; try { ModelService modelService = methodContext.getDispatcher().getDispatchContext().getModelService(serviceName); - int timeout = modelService.transactionTimeout; + int timeout = modelService.getTransactionTimeout(); if (this.transactionTimeout >= 0) { timeout = this.transactionTimeout; } if (methodContext.isTraceOn()) { - outputTraceMessage(methodContext, "Invoking service \"" + serviceName + "\", require-new-transaction = " + requireNewTransaction + ", transaction-timeout = " + timeout + ", IN attributes:", inMap.toString()); + outputTraceMessage(methodContext, "Invoking service \"" + serviceName + "\", require-new-transaction = " + requireNewTransaction + + ", transaction-timeout = " + timeout + ", IN attributes:", inMap.toString()); } result = methodContext.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction); } catch (GenericServiceException e) { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Service engine threw an exception: " + e.getMessage()); } - String errMsg = "ERROR: Could not complete the " + simpleMethod.getShortDescription() + " process [problem invoking the [" + serviceName + "] service with the map named [" + inMapFma + "] containing [" + inMap + "]: " + e.getMessage() + "]"; + String errMsg = "ERROR: Could not complete the " + simpleMethod.getShortDescription() + " process [problem invoking the [" + serviceName + + "] service with the map named [" + inMapFma + "] containing [" + inMap + "]: " + e.getMessage() + "]"; Debug.logError(e, errMsg, MODULE); if (breakOnError) { if (methodContext.getMethodType() == MethodContext.EVENT) { @@ -299,17 +306,22 @@ public final class CallService extends MethodOperation { if (methodContext.getMethodType() == MethodContext.EVENT) { if (UtilValidate.isNotEmpty(errorMessage)) { if (Debug.verboseOn()) { - errorMessage += UtilProperties.getMessage(RESOURCE, "simpleMethod.error_show_service_name", UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale); + errorMessage += UtilProperties.getMessage(RESOURCE, "simpleMethod.error_show_service_name", + UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale); } methodContext.putEnv(simpleMethod.getEventErrorMessageName(), errorMessage); } else { if (Debug.verboseOn()) { - errorMessageList.add(UtilProperties.getMessage(RESOURCE, "simpleMethod.error_show_service_name", UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale)); + errorMessageList.add(UtilProperties.getMessage(RESOURCE, "simpleMethod.error_show_service_name", + UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale)); } methodContext.putEnv(simpleMethod.getEventErrorMessageListName(), errorMessageList); } } else { - ServiceUtil.addErrors(UtilMisc.<String, String> getListFromMap(methodContext.getEnvMap(), this.simpleMethod.getServiceErrorMessageListName()), UtilMisc.<String, String, Object> getMapFromMap(methodContext.getEnvMap(), this.simpleMethod.getServiceErrorMessageMapName()), result); + ServiceUtil.addErrors(UtilMisc.<String, String>getListFromMap(methodContext.getEnvMap(), + this.simpleMethod.getServiceErrorMessageListName()), + UtilMisc.<String, String, Object>getMapFromMap(methodContext.getEnvMap(), this.simpleMethod.getServiceErrorMessageMapName()), + result); Debug.logError(new Exception(errorMessage), MODULE); } } @@ -322,7 +334,8 @@ public final class CallService extends MethodOperation { } } String defaultMessageStr = defaultMessage.getMessage(methodContext.getLoader(), methodContext); - if (UtilValidate.isEmpty(errorMessage) && UtilValidate.isEmpty(errorMessageList) && UtilValidate.isEmpty(successMessage) && UtilValidate.isNotEmpty(defaultMessageStr)) { + if (UtilValidate.isEmpty(errorMessage) && UtilValidate.isEmpty(errorMessageList) && UtilValidate.isEmpty(successMessage) + && UtilValidate.isNotEmpty(defaultMessageStr)) { if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.putEnv(simpleMethod.getEventEventMessageName(), defaultMessageStr); } else { @@ -419,7 +432,7 @@ public final class CallService extends MethodOperation { private ResultToRequest(Element element) { requestFsa = new FlexibleServletAccessor<>(element.getAttribute("request-name"), element.getAttribute("result-name")); - resultFma =FlexibleMapAccessor.getInstance(element.getAttribute("result-name")); + resultFma = FlexibleMapAccessor.getInstance(element.getAttribute("result-name")); } private void exec(MethodContext methodContext, Map<String, Object> resultMap) { @@ -452,7 +465,7 @@ public final class CallService extends MethodOperation { private ResultToSession(Element element) { requestFsa = new FlexibleServletAccessor<>(element.getAttribute("session-name"), element.getAttribute("result-name")); - resultFma =FlexibleMapAccessor.getInstance(element.getAttribute("result-name")); + resultFma = FlexibleMapAccessor.getInstance(element.getAttribute("result-name")); } private void exec(MethodContext methodContext, Map<String, Object> resultMap) { diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Compare.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Compare.java index 181ee86..4f06716 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Compare.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Compare.java @@ -29,7 +29,7 @@ import org.w3c.dom.Element; */ public class Compare extends BaseCompare { - String value; + private String value; public Compare(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); @@ -38,7 +38,7 @@ public class Compare extends BaseCompare { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object fieldValue = inMap.get(fieldName); + Object fieldValue = inMap.get(getFieldName()); doCompare(fieldValue, value, messages, locale, loader, true); } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/CompareField.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/CompareField.java index 93e2ce0..b2e88c4 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/CompareField.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/CompareField.java @@ -29,7 +29,7 @@ import org.w3c.dom.Element; */ public class CompareField extends BaseCompare { - String compareName; + private String compareName; public CompareField(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); @@ -39,7 +39,7 @@ public class CompareField extends BaseCompare { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { Object compareValue = inMap.get(compareName); - Object fieldValue = inMap.get(fieldName); + Object fieldValue = inMap.get(getFieldName()); doCompare(fieldValue, compareValue, messages, locale, loader, false); } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Convert.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Convert.java index dbdf986..8d772f5 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Convert.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Convert.java @@ -35,17 +35,17 @@ public class Convert extends SimpleMapOperation { private static final String MODULE = Convert.class.getName(); - String format; - boolean replace = true; - boolean setIfNull = true; - String toField; - String type; + private String format; + private boolean replace = true; + private boolean setIfNull = true; + private String toField; + private String type; public Convert(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); this.toField = element.getAttribute("to-field"); if (UtilValidate.isEmpty(this.toField)) { - this.toField = this.fieldName; + this.toField = this.getFieldName(); } type = element.getAttribute("type"); // if anything but false it will be true @@ -57,10 +57,11 @@ public class Convert extends SimpleMapOperation { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object fieldObject = inMap.get(fieldName); + Object fieldObject = inMap.get(getFieldName()); if (fieldObject == null) { - if (setIfNull && (replace || !results.containsKey(toField))) + if (setIfNull && (replace || !results.containsKey(toField))) { results.put(toField, null); + } return; } // if an incoming string is empty, @@ -80,15 +81,18 @@ public class Convert extends SimpleMapOperation { Debug.logError(e, "Error in convert simple-map-processor operation: " + e.toString(), MODULE); return; } - if (convertedObject == null) + if (convertedObject == null) { return; + } if (replace) { results.put(toField, convertedObject); - // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Converted.exec] Put converted value \"" + convertedObject + "\" in field \"" + toField + "\"", MODULE); + // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Converted.exec] Put converted value \"" + convertedObject + "\" in field \"" + // + toField + "\"", MODULE); } else { if (!results.containsKey(toField)) { results.put(toField, convertedObject); - // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Converted.exec] Put converted value \"" + convertedObject + "\" in field \"" + toField + "\"", MODULE); + // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Converted.exec] Put converted value \"" + convertedObject + "\" in field \"" + // + toField + "\"", MODULE); } } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Copy.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Copy.java index 9fc7749..7188fa5 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Copy.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Copy.java @@ -30,15 +30,15 @@ import org.w3c.dom.Element; */ public class Copy extends SimpleMapOperation { - boolean replace = true; - boolean setIfNull = true; - String toField; + private boolean replace = true; + private boolean setIfNull = true; + private String toField; public Copy(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); toField = element.getAttribute("to-field"); if (UtilValidate.isEmpty(this.toField)) { - this.toField = this.fieldName; + this.toField = this.getFieldName(); } // if anything but false it will be true replace = !"false".equals(element.getAttribute("replace")); @@ -48,9 +48,10 @@ public class Copy extends SimpleMapOperation { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object fieldValue = inMap.get(fieldName); - if (fieldValue == null && !setIfNull) + Object fieldValue = inMap.get(getFieldName()); + if (fieldValue == null && !setIfNull) { return; + } if (fieldValue instanceof java.lang.String) { if (((String) fieldValue).length() == 0) { if (setIfNull && (replace || !results.containsKey(toField))) { @@ -65,7 +66,8 @@ public class Copy extends SimpleMapOperation { } else { if (!results.containsKey(toField)) { results.put(toField, fieldValue); - // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Copy.exec] Copied \"" + fieldValue + "\" to field \"" + toField + "\"", MODULE); + // if (Debug.infoOn()) Debug.logInfo("[SimpleMapProcessor.Copy.exec] Copied \"" + fieldValue + "\" to field \"" + toField + // + "\"", MODULE); } } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/NotEmpty.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/NotEmpty.java index 0cf63b9..feb03c3 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/NotEmpty.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/NotEmpty.java @@ -36,15 +36,16 @@ public class NotEmpty extends SimpleMapOperation { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object obj = inMap.get(fieldName); + Object obj = inMap.get(getFieldName()); if (obj instanceof java.lang.String) { String fieldValue = (java.lang.String) obj; if (UtilValidate.isEmpty(fieldValue)) { addMessage(messages, loader, locale); } } else { - if (obj == null) + if (obj == null) { addMessage(messages, loader, locale); + } } } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Regexp.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Regexp.java index f87dad5..e51a4f7 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Regexp.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/Regexp.java @@ -39,7 +39,7 @@ public class Regexp extends SimpleMapOperation { private static final String MODULE = Regexp.class.getName(); private Pattern pattern = null; - String expr; + private String expr; public Regexp(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); @@ -53,7 +53,7 @@ public class Regexp extends SimpleMapOperation { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object obj = inMap.get(fieldName); + Object obj = inMap.get(getFieldName()); String fieldValue = null; try { fieldValue = (String) ObjectType.simpleTypeOrObjectConvert(obj, "String", null, locale); diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapOperation.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapOperation.java index 85039a8..e72c5d1 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapOperation.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapOperation.java @@ -33,11 +33,11 @@ import org.w3c.dom.Element; */ public abstract class SimpleMapOperation { - String fieldName; - boolean isProperty = false; - String message = null; - String propertyResource = null; - SimpleMapProcess simpleMapProcess; + private String fieldName; + private boolean isProperty = false; + private String message = null; + private String propertyResource = null; + private SimpleMapProcess simpleMapProcess; public SimpleMapOperation(Element element, SimpleMapProcess simpleMapProcess) { Element failMessage = UtilXml.firstChildElement(element, "fail-message"); @@ -54,6 +54,20 @@ public abstract class SimpleMapOperation { this.fieldName = simpleMapProcess.getFieldName(); } + /** + * Gets field name. + * @return the field name + */ + public String getFieldName() { + return fieldName; + } + + /** + * Add message. + * @param messages the messages + * @param loader the loader + * @param locale the locale + */ public void addMessage(List<Object> messages, ClassLoader loader, Locale locale) { if (!isProperty && message != null) { messages.add(new MessageString(message, fieldName, true)); diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapProcess.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapProcess.java index 1c90843..d6579ef 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapProcess.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/SimpleMapProcess.java @@ -35,24 +35,40 @@ public class SimpleMapProcess { private static final String MODULE = SimpleMapProcess.class.getName(); - String field = ""; - List<SimpleMapOperation> simpleMapOperations = new ArrayList<>(); + private String field = ""; + private List<SimpleMapOperation> simpleMapOperations = new ArrayList<>(); public SimpleMapProcess(Element simpleMapProcessElement) { this.field = simpleMapProcessElement.getAttribute("field"); readOperations(simpleMapProcessElement); } + /** + * Exec. + * @param inMap the in map + * @param results the results + * @param messages the messages + * @param locale the locale + * @param loader the loader + */ public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { for (SimpleMapOperation simpleMapOperation : simpleMapOperations) { simpleMapOperation.exec(inMap, results, messages, locale, loader); } } + /** + * Gets field name. + * @return the field name + */ public String getFieldName() { return field; } + /** + * Read operations. + * @param simpleMapProcessElement the simple map process element + */ void readOperations(Element simpleMapProcessElement) { List<? extends Element> operationElements = UtilXml.childElementList(simpleMapProcessElement); if (UtilValidate.isNotEmpty(operationElements)) { @@ -73,7 +89,8 @@ public class SimpleMapProcess { } else if ("convert".equals(nodeName)) { simpleMapOperations.add(new Convert(curOperElem, this)); } else { - Debug.logWarning("[SimpleMapProcessor.SimpleMapProcess.readOperations] Operation element \"" + nodeName + "\" not recognized", MODULE); + Debug.logWarning("[SimpleMapProcessor.SimpleMapProcess.readOperations] Operation element \"" + nodeName + + "\" not recognized", MODULE); } } } diff --git a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/ValidateMethod.java b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/ValidateMethod.java index ba2ab6a..1645553 100644 --- a/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/ValidateMethod.java +++ b/framework/minilang/src/main/java/org/apache/ofbiz/minilang/operation/ValidateMethod.java @@ -36,8 +36,8 @@ public class ValidateMethod extends SimpleMapOperation { private static final String MODULE = ValidateMethod.class.getName(); - String className; - String methodName; + private String className; + private String methodName; public ValidateMethod(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); @@ -47,7 +47,7 @@ public class ValidateMethod extends SimpleMapOperation { @Override public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) { - Object obj = inMap.get(fieldName); + Object obj = inMap.get(getFieldName()); String fieldValue = null; try { fieldValue = (String) ObjectType.simpleTypeOrObjectConvert(obj, "String", null, locale); @@ -59,7 +59,7 @@ public class ValidateMethod extends SimpleMapOperation { loader = Thread.currentThread().getContextClassLoader(); } Class<?>[] paramTypes = new Class<?>[] {String.class }; - Object[] params = new Object[] { fieldValue }; + Object[] params = new Object[] {fieldValue }; Class<?> valClass; try { valClass = loader.loadClass(className); diff --git a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java index 4bcf3b7..8b9cc31 100644 --- a/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java +++ b/framework/security/src/main/java/org/apache/ofbiz/security/CsrfUtil.java @@ -204,7 +204,7 @@ public final class CsrfUtil { } } String tokenValue = ""; - if (requestMap != null && requestMap.securityCsrfToken) { + if (requestMap != null && requestMap.isSecurityCsrfToken()) { if (tokenMap.containsKey(requestUri)) { tokenValue = tokenMap.get(requestUri); } else { diff --git a/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java b/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java index 736597a..2bfa166 100644 --- a/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java +++ b/framework/security/src/test/java/org/apache/ofbiz/security/CsrfUtilTests.java @@ -119,12 +119,12 @@ public class CsrfUtilTests { Element requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "checkLogin"); ConfigXMLReader.RequestMap requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "entity/find/{entityName}/{pkValues: .*}"); requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); when(request.getAttribute("requestMapMap")).thenReturn(requestMapMap); @@ -156,39 +156,39 @@ public class CsrfUtilTests { Element requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "checkLogin"); ConfigXMLReader.RequestMap requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); // REST request like /entity/find/AccommodationClass requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "entity/find/{entityName}"); requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); // View override like /view/ModelInduceFromDb requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "view"); requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); requestMapElement = doc.createElement("request-map"); requestMapElement.setAttribute("uri", "ModelInduceFromDb"); requestMap = new ConfigXMLReader.RequestMap(requestMapElement); - requestMapMap.put(requestMap.uri, requestMap); + requestMapMap.put(requestMap.getUri(), requestMap); // test usual request requestMap = CsrfUtil.findRequestMap(requestMapMap, "/checkLogin"); - assertEquals(requestMap.uri, "checkLogin"); + assertEquals(requestMap.getUri(), "checkLogin"); // test usual request requestMap = CsrfUtil.findRequestMap(requestMapMap, "checkLogin"); - assertEquals(requestMap.uri, "checkLogin"); + assertEquals(requestMap.getUri(), "checkLogin"); // test REST request requestMap = CsrfUtil.findRequestMap(requestMapMap, "/entity/find/AccommodationClass"); - assertEquals(requestMap.uri, "entity/find/{entityName}"); + assertEquals(requestMap.getUri(), "entity/find/{entityName}"); // test view orderride requestMap = CsrfUtil.findRequestMap(requestMapMap, "/view/ModelInduceFromDb"); - assertEquals(requestMap.uri, "view"); + assertEquals(requestMap.getUri(), "view"); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/GeneralServiceException.java b/framework/service/src/main/java/org/apache/ofbiz/service/GeneralServiceException.java index 4eef839..4f5959a 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/GeneralServiceException.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/GeneralServiceException.java @@ -31,9 +31,9 @@ import org.apache.ofbiz.base.util.UtilMisc; @SuppressWarnings("serial") public class GeneralServiceException extends org.apache.ofbiz.base.util.GeneralException { - protected List<Object> errorMsgList = null; - protected Map<String, ? extends Object> errorMsgMap = null; - protected Map<String, ? extends Object> nestedServiceResult = null; + private List<Object> errorMsgList = null; + private Map<String, ? extends Object> errorMsgMap = null; + private Map<String, ? extends Object> nestedServiceResult = null; public GeneralServiceException() { super(); @@ -58,6 +58,11 @@ public class GeneralServiceException extends org.apache.ofbiz.base.util.GeneralE this.nestedServiceResult = nestedServiceResult; } + /** + * Return error map. + * @param module the module + * @return the map + */ public Map<String, Object> returnError(String module) { String errMsg = this.getMessage() == null ? "Error in Service" : this.getMessage(); if (this.getNested() != null) { @@ -66,6 +71,10 @@ public class GeneralServiceException extends org.apache.ofbiz.base.util.GeneralE return ServiceUtil.returnError(errMsg, this.errorMsgList, this.errorMsgMap, this.nestedServiceResult); } + /** + * Add error messages. + * @param errMsgs the err msgs + */ public void addErrorMessages(List<? extends Object> errMsgs) { if (this.errorMsgList == null) { this.errorMsgList = new LinkedList<>(); 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 f17d1c3..bb0a1ca 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,26 +38,69 @@ import org.apache.ofbiz.service.job.JobManagerException; */ public abstract class GenericAbstractDispatcher implements LocalDispatcher { - protected static final String MODULE = GenericAbstractDispatcher.class.getName(); + private static final String MODULE = GenericAbstractDispatcher.class.getName(); - protected DispatchContext ctx = null; - protected ServiceDispatcher dispatcher = null; - protected String name = null; + private DispatchContext ctx = null; + private ServiceDispatcher dispatcher = null; + private String name = null; + + /** + * Gets ctx. + * @return the ctx + */ + public DispatchContext getCtx() { + return ctx; + } + + /** + * Sets ctx. + * @param ctx the ctx + */ + public void setCtx(DispatchContext ctx) { + this.ctx = ctx; + } + + /** + * Gets dispatcher. + * @return the dispatcher + */ + public ServiceDispatcher getDispatcher() { + return dispatcher; + } + + /** + * Sets dispatcher. + * @param dispatcher the dispatcher + */ + public void setDispatcher(ServiceDispatcher dispatcher) { + this.dispatcher = dispatcher; + } + + /** + * Sets name. + * @param name the name + */ + public void setName(String name) { + this.name = name; + } public GenericAbstractDispatcher() { } @Override - public void schedule(String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws GenericServiceException { + public void schedule(String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, + int count, long endTime, int maxRetry) throws GenericServiceException { schedule(null, poolName, serviceName, context, startTime, frequency, interval, count, endTime, maxRetry); } @Override - public void schedule(String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, int maxRetry, Object... context) throws GenericServiceException { + public void schedule(String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, int maxRetry, + Object... context) throws GenericServiceException { schedule(poolName, serviceName, ServiceUtil.makeContext(context), startTime, frequency, interval, count, endTime, maxRetry); } @Override - public void schedule(String jobName, String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime, int maxRetry) throws GenericServiceException { + public void schedule(String jobName, String poolName, String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, + int interval, int count, long endTime, int maxRetry) throws GenericServiceException { Transaction suspendedTransaction = null; try { boolean beganTransaction = false; @@ -111,7 +154,8 @@ public abstract class GenericAbstractDispatcher implements LocalDispatcher { } @Override - public void schedule(String jobName, String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, int maxRetry, Object... context) throws GenericServiceException { + public void schedule(String jobName, String poolName, String serviceName, long startTime, int frequency, int interval, int count, long endTime, + int maxRetry, Object... context) throws GenericServiceException { schedule(jobName, poolName, serviceName, ServiceUtil.makeContext(context), startTime, frequency, interval, count, endTime, maxRetry); } @@ -136,33 +180,39 @@ public abstract class GenericAbstractDispatcher implements LocalDispatcher { } @Override - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, long endTime) throws GenericServiceException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count, + long endTime) throws GenericServiceException { ModelService model = ctx.getModelService(serviceName); - schedule(null, serviceName, context, startTime, frequency, interval, count, endTime, model.maxRetry); + schedule(null, serviceName, context, startTime, frequency, interval, count, endTime, model.getMaxRetry()); } @Override - public void schedule(String serviceName, long startTime, int frequency, int interval, int count, long endTime, Object... context) throws GenericServiceException { + public void schedule(String serviceName, long startTime, int frequency, int interval, int count, long endTime, Object... context) + throws GenericServiceException { schedule(serviceName, ServiceUtil.makeContext(context), startTime, frequency, interval, count, endTime); } @Override - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count) throws GenericServiceException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, int count) + throws GenericServiceException { schedule(serviceName, context, startTime, frequency, interval, count, 0); } @Override - public void schedule(String serviceName, long startTime, int frequency, int interval, int count, Object... context) throws GenericServiceException { + public void schedule(String serviceName, long startTime, int frequency, int interval, int count, Object... context) + throws GenericServiceException { schedule(serviceName, ServiceUtil.makeContext(context), startTime, frequency, interval, count); } @Override - public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, long endTime) throws GenericServiceException { + public void schedule(String serviceName, Map<String, ? extends Object> context, long startTime, int frequency, int interval, long endTime) + throws GenericServiceException { schedule(serviceName, context, startTime, frequency, interval, -1, endTime); } @Override - public void schedule(String serviceName, long startTime, int frequency, int interval, long endTime, Object... context) throws GenericServiceException { + public void schedule(String serviceName, long startTime, int frequency, int interval, long endTime, Object... context) + throws GenericServiceException { schedule(serviceName, ServiceUtil.makeContext(context), startTime, frequency, interval, endTime); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/GenericDispatcherFactory.java b/framework/service/src/main/java/org/apache/ofbiz/service/GenericDispatcherFactory.java index 6067374..6ad26f8 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/GenericDispatcherFactory.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/GenericDispatcherFactory.java @@ -29,6 +29,8 @@ import org.apache.ofbiz.entity.Delegator; */ public class GenericDispatcherFactory implements LocalDispatcherFactory { + private static final String MODULE = GenericDispatcherFactory.class.getName(); + private static boolean ecasDisabled = false; @Override @@ -38,7 +40,8 @@ public class GenericDispatcherFactory implements LocalDispatcherFactory { } // attempts to retrieve an already registered DispatchContext with the name "name" LocalDispatcher dispatcher = ServiceDispatcher.getLocalDispatcher(name, delegator); - // if not found then create a new GenericDispatcher object; the constructor will also register a new DispatchContext in the ServiceDispatcher with name "dispatcherName" + // if not found then create a new GenericDispatcher object; the constructor will also register a new DispatchContext in the + // ServiceDispatcher with name "dispatcherName" if (dispatcher == null) { dispatcher = new GenericDispatcher(name, delegator); } @@ -47,7 +50,6 @@ public class GenericDispatcherFactory implements LocalDispatcherFactory { // The default LocalDispatcher implementation. private static class GenericDispatcher extends GenericAbstractDispatcher { - private GenericDispatcher(String name, Delegator delegator) { ClassLoader loader; try { @@ -55,15 +57,15 @@ public class GenericDispatcherFactory implements LocalDispatcherFactory { } catch (SecurityException e) { loader = this.getClass().getClassLoader(); } - this.name = name; - this.dispatcher = ServiceDispatcher.getInstance(delegator); + this.setName(name); + this.setDispatcher(ServiceDispatcher.getInstance(delegator)); /* * FIXME: "this" reference escape. DispatchContext constructor uses * this object before it is fully constructed. */ DispatchContext ctx = new DispatchContext(name, loader, this); - this.dispatcher.register(ctx); - this.ctx = ctx; + this.getDispatcher().register(ctx); + this.setCtx(ctx); if (Debug.verboseOn()) { Debug.logVerbose("[GenericDispatcher] : Created Dispatcher for: " + name, MODULE); } @@ -85,128 +87,148 @@ public class GenericDispatcherFactory implements LocalDispatcherFactory { } @Override - public Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context) throws ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); - return dispatcher.runSync(this.name, service, context); + public Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context) + throws ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); + return getDispatcher().runSync(this.getName(), service, context); } @Override - public Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); + public Map<String, Object> runSync(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, + boolean requireNewTransaction) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); // clone the model service for updates ModelService cloned = new ModelService(service); - cloned.requireNewTransaction = requireNewTransaction; + cloned.setRequireNewTransaction(requireNewTransaction); if (requireNewTransaction) { - cloned.useTransaction = true; + cloned.setUseTransaction(true); } if (transactionTimeout != -1) { - cloned.transactionTimeout = transactionTimeout; + cloned.setTransactionTimeout(transactionTimeout); } - return dispatcher.runSync(this.name, cloned, context); + return getDispatcher().runSync(this.getName(), cloned, context); } @Override - public Map<String, Object> runSync(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public Map<String, Object> runSync(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { return runSync(serviceName, ServiceUtil.makeContext(context), transactionTimeout, requireNewTransaction); } @Override public void runSyncIgnore(String serviceName, Map<String, ? extends Object> context) throws GenericServiceException { - ModelService service = ctx.getModelService(serviceName); - dispatcher.runSyncIgnore(this.name, service, context); + ModelService service = getCtx().getModelService(serviceName); + getDispatcher().runSyncIgnore(this.getName(), service, context); } @Override - public void runSyncIgnore(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); + public void runSyncIgnore(String serviceName, Map<String, ? extends Object> context, int transactionTimeout, boolean requireNewTransaction) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); // clone the model service for updates ModelService cloned = new ModelService(service); - cloned.requireNewTransaction = requireNewTransaction; + cloned.setRequireNewTransaction(requireNewTransaction); if (requireNewTransaction) { - cloned.useTransaction = true; + cloned.setUseTransaction(true); } if (transactionTimeout != -1) { - cloned.transactionTimeout = transactionTimeout; + cloned.setTransactionTimeout(transactionTimeout); } - dispatcher.runSyncIgnore(this.name, cloned, context); + getDispatcher().runSyncIgnore(this.getName(), cloned, context); } @Override - public void runSyncIgnore(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runSyncIgnore(String serviceName, int transactionTimeout, boolean requireNewTransaction, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runSyncIgnore(serviceName, ServiceUtil.makeContext(context), transactionTimeout, requireNewTransaction); } @Override - public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist, int transactionTimeout, boolean requireNewTransaction) throws ServiceAuthException, ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); + public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist, + int transactionTimeout, boolean requireNewTransaction) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); // clone the model service for updates ModelService cloned = new ModelService(service); - cloned.requireNewTransaction = requireNewTransaction; + cloned.setRequireNewTransaction(requireNewTransaction); if (requireNewTransaction) { - cloned.useTransaction = true; + cloned.setUseTransaction(true); } if (transactionTimeout != -1) { - cloned.transactionTimeout = transactionTimeout; + cloned.setTransactionTimeout(transactionTimeout); } - dispatcher.runAsync(this.name, cloned, context, requester, persist); + getDispatcher().runAsync(this.getName(), cloned, context, requester, persist); } @Override - public void runAsync(String serviceName, GenericRequester requester, boolean persist, int transactionTimeout, boolean requireNewTransaction, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, GenericRequester requester, boolean persist, int transactionTimeout, + boolean requireNewTransaction, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, ServiceUtil.makeContext(context), requester, persist, transactionTimeout, requireNewTransaction); } @Override - public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); - dispatcher.runAsync(this.name, service, context, requester, persist); + public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); + getDispatcher().runAsync(this.getName(), service, context, requester, persist); } @Override - public void runAsync(String serviceName, GenericRequester requester, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, GenericRequester requester, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, ServiceUtil.makeContext(context), requester, persist); } @Override - public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, Map<String, ? extends Object> context, GenericRequester requester) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, context, requester, true); } @Override - public void runAsync(String serviceName, GenericRequester requester, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, GenericRequester requester, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, ServiceUtil.makeContext(context), requester); } @Override - public void runAsync(String serviceName, Map<String, ? extends Object> context, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException { - ModelService service = ctx.getModelService(serviceName); - dispatcher.runAsync(this.name, service, context, persist); + public void runAsync(String serviceName, Map<String, ? extends Object> context, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { + ModelService service = getCtx().getModelService(serviceName); + getDispatcher().runAsync(this.getName(), service, context, persist); } @Override - public void runAsync(String serviceName, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, ServiceUtil.makeContext(context), persist); } @Override - public void runAsync(String serviceName, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String serviceName, Map<String, ? extends Object> context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runAsync(serviceName, context, true); } @Override - public GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { GenericResultWaiter waiter = new GenericResultWaiter(); this.runAsync(serviceName, context, waiter, persist); return waiter; } @Override - public GenericResultWaiter runAsyncWait(String serviceName, boolean persist, Object... context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public GenericResultWaiter runAsyncWait(String serviceName, boolean persist, Object... context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { return runAsyncWait(serviceName, ServiceUtil.makeContext(context), persist); } @Override - public GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public GenericResultWaiter runAsyncWait(String serviceName, Map<String, ? extends Object> context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { return runAsyncWait(serviceName, context, true); } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ModelParam.java b/framework/service/src/main/java/org/apache/ofbiz/service/ModelParam.java index 846f9e8..3db0198 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ModelParam.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ModelParam.java @@ -43,57 +43,57 @@ public class ModelParam implements Serializable { private static final String MODULE = ModelParam.class.getName(); /** Parameter name */ - public String name; + private String name; /** The description of this parameter */ - public String description; + private String description; /** Paramater type */ - public String type; + private String type; /** Parameter mode (IN/OUT/INOUT) */ - public String mode; + private String mode; /** The form label */ - public String formLabel; + private String formLabel; /** The entity name */ - public String entityName; + private String entityName; /** The entity field name */ - public String fieldName; + private String fieldName; /** Request attribute to look for if not defined as a parameter */ - public String requestAttributeName; + private String requestAttributeName; /** Session attribute to look for if not defined as a parameter */ - public String sessionAttributeName; + private String sessionAttributeName; /** Parameter prefix for creating an attribute Map */ - public String stringMapPrefix; + private String stringMapPrefix; /** Parameter suffix for creating an attribute List */ - public String stringListSuffix; + private String stringListSuffix; /** Validation methods */ - public List<ModelParamValidator> validators; + private List<ModelParamValidator> validators; /** Default value */ private FlexibleStringExpander defaultValue = null; /** Is this Parameter required or optional? Default to false, or required */ - public boolean optional = false; - public boolean overrideOptional = false; + private boolean optional = false; + private boolean overrideOptional = false; /** Is this parameter to be displayed via the form tool? */ - public boolean formDisplay = true; - public boolean overrideFormDisplay = false; + private boolean formDisplay = true; + private boolean overrideFormDisplay = false; /** Default value */ - public String allowHtml = null; + private String allowHtml = null; /** Is this Parameter set internally? */ - public boolean internal = false; + private boolean internal = false; public ModelParam() { } @@ -121,14 +121,32 @@ public class ModelParam implements Serializable { this.internal = param.internal; } + /** + * Add validator. + * @param className the class name + * @param methodName the method name + * @param failMessage the fail message + */ public void addValidator(String className, String methodName, String failMessage) { validators.add(new ModelParamValidator(className, methodName, failMessage, null, null)); } + /** + * Add validator. + * @param className the class name + * @param methodName the method name + * @param failResource the fail resource + * @param failProperty the fail property + */ public void addValidator(String className, String methodName, String failResource, String failProperty) { validators.add(new ModelParamValidator(className, methodName, null, failResource, failProperty)); } + /** + * Gets primary fail message. + * @param locale the locale + * @return the primary fail message + */ public String getPrimaryFailMessage(Locale locale) { if (UtilValidate.isNotEmpty(validators)) { return validators.get(0).getFailMessage(locale); @@ -136,61 +154,340 @@ public class ModelParam implements Serializable { return null; } + /** + * Gets short display description. + * @return the short display description + */ public String getShortDisplayDescription() { return this.name + "[" + this.type + "-" + this.mode + "]" + (optional ? "" : "*"); } + /** + * Gets name. + * @return the name + */ public String getName() { return this.name; } - // Method to retrieve form-label from model parameter object in freemarker + + /** + * Sets mode. + * @param mode the mode + */ + public void setMode(String mode) { + this.mode = mode; + } + + /** + * Gets validators. + * @return the validators + */ + public List<ModelParamValidator> getValidators() { + return validators; + } + + /** + * Sets form display. + * @param formDisplay the form display + */ + public void setFormDisplay(boolean formDisplay) { + this.formDisplay = formDisplay; + } + + /** + * Sets description. + * @param description the description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Sets override optional. + * @param overrideOptional the override optional + */ + public void setOverrideOptional(boolean overrideOptional) { + this.overrideOptional = overrideOptional; + } + + /** + * Sets override form display. + * @param overrideFormDisplay the override form display + */ + public void setOverrideFormDisplay(boolean overrideFormDisplay) { + this.overrideFormDisplay = overrideFormDisplay; + } + + /** + * Sets validators. + * @param validators the validators + */ + public void setValidators(List<ModelParamValidator> validators) { + this.validators = validators; + } + + /** + * Sets internal. + * @param internal the internal + */ + public void setInternal(boolean internal) { + this.internal = internal; + } + + /** + * Sets request attribute name. + * @param requestAttributeName the request attribute name + */ + public void setRequestAttributeName(String requestAttributeName) { + this.requestAttributeName = requestAttributeName; + } + + /** + * Sets session attribute name. + * @param sessionAttributeName the session attribute name + */ + public void setSessionAttributeName(String sessionAttributeName) { + this.sessionAttributeName = sessionAttributeName; + } + + /** + * Sets string map prefix. + * @param stringMapPrefix the string map prefix + */ + public void setStringMapPrefix(String stringMapPrefix) { + this.stringMapPrefix = stringMapPrefix; + } + + /** + * Sets string list suffix. + * @param stringListSuffix the string list suffix + */ + public void setStringListSuffix(String stringListSuffix) { + this.stringListSuffix = stringListSuffix; + } + + /** + * Sets name. + * @param name the name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets allow html. + * @param allowHtml the allow html + */ + public void setAllowHtml(String allowHtml) { + this.allowHtml = allowHtml; + } + + /** + * Gets allow html. + * @return the allow html + */ + public String getAllowHtml() { + return allowHtml; + } + + /** + * Gets request attribute name. + * @return the request attribute name + */ + public String getRequestAttributeName() { + return requestAttributeName; + } + + /** + * Gets session attribute name. + * @return the session attribute name + */ + public String getSessionAttributeName() { + return sessionAttributeName; + } + + /** + * Is override optional boolean. + * @return the boolean + */ + public boolean isOverrideOptional() { + return overrideOptional; + } + + /** + * Is form display boolean. + * @return the boolean + */ + public boolean isFormDisplay() { + return formDisplay; + } + + /** + * Is override form display boolean. + * @return the boolean + */ + public boolean isOverrideFormDisplay() { + return overrideFormDisplay; + } + + /** + * Sets type. + * @param type the type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Sets form label. + * @param formLabel the form label + */ + public void setFormLabel(String formLabel) { + this.formLabel = formLabel; + } + + /** + * Sets entity name. + * @param entityName the entity name + */ + public void setEntityName(String entityName) { + this.entityName = entityName; + } + + /** + * Sets field name. + * @param fieldName the field name + */ + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + /** + * Is internal boolean. + * @return the boolean + */ + public boolean isInternal() { + return internal; + } + + /** + * Sets optional. + * @param optional the optional + */ + public void setOptional(boolean optional) { + this.optional = optional; + } + + /** + * Gets string map prefix. + * @return the string map prefix + */ + public String getStringMapPrefix() { + return stringMapPrefix; + } + + /** + * Gets string list suffix. + * @return the string list suffix + */ + public String getStringListSuffix() { + return stringListSuffix; + } + + /** + * Gets form label. + * @return the form label + */ +// Method to retrieve form-label from model parameter object in freemarker public String getFormLabel() { return this.formLabel; } + /** + * Gets type. + * @return the type + */ public String getType() { return this.type; } + /** + * Gets mode. + * @return the mode + */ public String getMode() { return this.mode; } + /** + * Gets entity name. + * @return the entity name + */ public String getEntityName() { return this.entityName; } + /** + * Gets field name. + * @return the field name + */ public String getFieldName() { return this.fieldName; } + /** + * Gets internal. + * @return the internal + */ public boolean getInternal() { return this.internal; } + /** + * Is in boolean. + * @return the boolean + */ public boolean isIn() { return ModelService.IN_PARAM.equals(this.mode) || ModelService.IN_OUT_PARAM.equals(this.mode); } + /** + * Is out boolean. + * @return the boolean + */ public boolean isOut() { return ModelService.OUT_PARAM.equals(this.mode) || ModelService.IN_OUT_PARAM.equals(this.mode); } + /** + * Is optional boolean. + * @return the boolean + */ public boolean isOptional() { return this.optional; } + /** + * Gets default value. + * @return the default value + */ public FlexibleStringExpander getDefaultValue() { return this.defaultValue; } + /** + * Gets default value. + * @param context the context + * @return the default value + */ public Object getDefaultValue(Map<String, Object> context) { Object defaultValueObj = null; if (this.type != null) { try { defaultValueObj = ObjectType.simpleTypeOrObjectConvert(this.defaultValue.expandString(context), this.type, null, null, false); } catch (Exception e) { - Debug.logWarning(e, "Service attribute [" + name + "] default value could not be converted to type [" + type + "]: " + e.toString(), MODULE); + Debug.logWarning(e, "Service attribute [" + name + "] default value could not be converted to type [" + type + "]: " + + e.toString(), MODULE); } if (defaultValueObj == null) { // uh-oh, conversion failed, set the String and see what happens @@ -201,6 +498,11 @@ public class ModelParam implements Serializable { } return defaultValueObj; } + + /** + * Sets default value. + * @param defaultValue the default value + */ public void setDefaultValue(String defaultValue) { this.defaultValue = FlexibleStringExpander.getInstance(defaultValue); if (this.defaultValue != null) { @@ -210,10 +512,20 @@ public class ModelParam implements Serializable { Debug.logVerbose("Default value for attribute [" + this.name + "] set to [" + this.defaultValue + "]", MODULE); } } + + /** + * Copy default value. + * @param param the param + */ public void copyDefaultValue(ModelParam param) { this.setDefaultValue(param.defaultValue.getOriginal()); } + /** + * Equals boolean. + * @param model the model + * @return the boolean + */ public boolean equals(ModelParam model) { return model.name.equals(this.name); } @@ -257,6 +569,11 @@ public class ModelParam implements Serializable { return buf.toString(); } + /** + * Gets wsdl part. + * @param def the def + * @return the wsdl part + */ public Part getWSDLPart(Definition def) { Part part = def.createPart(); part.setName(this.name); @@ -264,6 +581,10 @@ public class ModelParam implements Serializable { return part; } + /** + * Java 2 wsdl type string. + * @return the string + */ protected String java2wsdlType() { if (ObjectType.instanceOf(java.lang.Character.class, this.type)) { return "std-String"; @@ -311,11 +632,11 @@ public class ModelParam implements Serializable { } static class ModelParamValidator implements Serializable { - protected String className; - protected String methodName; - protected String failMessage; - protected String failResource; - protected String failProperty; + private String className; + private String methodName; + private String failMessage; + private String failResource; + private String failProperty; ModelParamValidator(String className, String methodName, String failMessage, String failResource, String failProperty) { this.className = className; diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ModelPermission.java b/framework/service/src/main/java/org/apache/ofbiz/service/ModelPermission.java index c617782..e5e45f2 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ModelPermission.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ModelPermission.java @@ -36,27 +36,27 @@ public class ModelPermission implements Serializable { private static final String MODULE = ModelPermission.class.getName(); - public static final int PERMISSION = 1; - public static final int ENTITY_PERMISSION = 2; - public static final int PERMISSION_SERVICE = 4; - - public ModelService serviceModel = null; - public int permissionType = 0; - public String nameOrRole = null; - public String action = null; - public String permissionServiceName = null; - public String permissionMainAction = null; - public String permissionResourceDesc = null; - public boolean permissionRequireNewTransaction = false; - public boolean permissionReturnErrorOnFailure = true; - public Boolean auth; + private static final int PERMISSION = 1; + private static final int ENTITY_PERMISSION = 2; + private static final int PERMISSION_SERVICE = 4; + + private ModelService serviceModel = null; + private int permissionType = 0; + private String nameOrRole = null; + private String action = null; + private String permissionServiceName = null; + private String permissionMainAction = null; + private String permissionResourceDesc = null; + private boolean permissionRequireNewTransaction = false; + private boolean permissionReturnErrorOnFailure = true; + private Boolean auth; private static final String RESOURCE = "ServiceErrorUiLabels"; @Override public String toString() { StringBuilder buf = new StringBuilder(); - buf.append(serviceModel.name).append("::"); + buf.append(serviceModel.getName()).append("::"); buf.append(permissionType).append("::"); buf.append(nameOrRole).append("::"); buf.append(action).append("::"); @@ -68,6 +68,12 @@ public class ModelPermission implements Serializable { return buf.toString(); } + /** + * Eval permission map. + * @param dctx the dctx + * @param context the context + * @return the map + */ public Map<String, Object> evalPermission(DispatchContext dctx, Map<String, ? extends Object> context) { GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); @@ -90,7 +96,8 @@ public class ModelPermission implements Serializable { case PERMISSION_SERVICE: return evalPermissionService(serviceModel, dctx, context); default: - Debug.logWarning("Invalid permission type [" + permissionType + "] for permission named : " + nameOrRole + " on service : " + serviceModel.name, MODULE); + Debug.logWarning("Invalid permission type [" + permissionType + "] for permission named : " + nameOrRole + + " on service : " + serviceModel.getName(), MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServicePermissionErrorInvalidPermissionType", locale)); } if (!hasPermission) { @@ -118,6 +125,110 @@ public class ModelPermission implements Serializable { return security.hasEntityPermission(nameOrRole, action, userLogin); } + /** + * Sets permission service name. + * @param permissionServiceName the permission service name + */ + public void setPermissionServiceName(String permissionServiceName) { + this.permissionServiceName = permissionServiceName; + } + + /** + * Sets permission type. + * @param permissionType the permission type + */ + public void setPermissionType(int permissionType) { + this.permissionType = permissionType; + } + + /** + * Sets permission main action. + * @param permissionMainAction the permission main action + */ + public void setPermissionMainAction(String permissionMainAction) { + this.permissionMainAction = permissionMainAction; + } + + /** + * Sets permission resource desc. + * @param permissionResourceDesc the permission resource desc + */ + public void setPermissionResourceDesc(String permissionResourceDesc) { + this.permissionResourceDesc = permissionResourceDesc; + } + + /** + * Sets permission require new transaction. + * @param permissionRequireNewTransaction the permission require new transaction + */ + public void setPermissionRequireNewTransaction(boolean permissionRequireNewTransaction) { + this.permissionRequireNewTransaction = permissionRequireNewTransaction; + } + + /** + * Sets permission return error on failure. + * @param permissionReturnErrorOnFailure the permission return error on failure + */ + public void setPermissionReturnErrorOnFailure(boolean permissionReturnErrorOnFailure) { + this.permissionReturnErrorOnFailure = permissionReturnErrorOnFailure; + } + + /** + * Sets name or role. + * @param nameOrRole the name or role + */ + public void setNameOrRole(String nameOrRole) { + this.nameOrRole = nameOrRole; + } + + /** + * Sets action. + * @param action the action + */ + public void setAction(String action) { + this.action = action; + } + + public static int getPERMISSION() { + return PERMISSION; + } + + public static int getEntityPermission() { + return ENTITY_PERMISSION; + } + + /** + * Gets action. + * @return the action + */ + public String getAction() { + return action; + } + + /** + * Sets auth. + * @param auth the auth + */ + public void setAuth(Boolean auth) { + this.auth = auth; + } + + /** + * Sets service model. + * @param serviceModel the service model + */ + public void setServiceModel(ModelService serviceModel) { + this.serviceModel = serviceModel; + } + + /** + * Gets permission service. + * @return the permission service + */ + public static int getPermissionService() { + return PERMISSION_SERVICE; + } + private Map<String, Object> evalPermissionService(ModelService origService, DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); ModelService permission; @@ -133,7 +244,7 @@ public class ModelPermission implements Serializable { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServicePermissionErrorDefinitionProblem", locale)); } - permission.auth = true; + permission.setAuth(true); Map<String, Object> ctx = permission.makeValid(context, ModelService.IN_PARAM); if (UtilValidate.isNotEmpty(permissionMainAction)) { ctx.put("mainAction", permissionMainAction); @@ -141,15 +252,15 @@ public class ModelPermission implements Serializable { if (UtilValidate.isNotEmpty(permissionResourceDesc)) { ctx.put("resourceDescription", permissionResourceDesc); } else if (origService != null) { - ctx.put("resourceDescription", origService.name); + ctx.put("resourceDescription", origService.getName()); } Map<String, Object> resp; String failMessage = null; try { if (permissionRequireNewTransaction) { - resp = dispatcher.runSync(permission.name, ctx, 300, true); + resp = dispatcher.runSync(permission.getName(), ctx, 300, true); } else { - resp = dispatcher.runSync(permission.name, ctx); + resp = dispatcher.runSync(permission.getName(), ctx); } failMessage = (String) resp.get("failMessage"); } catch (GenericServiceException e) { 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 9a8be40..ce6b47a 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 @@ -116,107 +116,667 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali private static final String RESOURCE = "ServiceErrorUiLabels"; /** The name of this service */ - public String name; + private String name; /** The location of the definition this service */ - public String definitionLocation; + private String definitionLocation; /** The description of this service */ - public String description; + private String description; /** The name of the service engine */ - public String engineName; + private String engineName; /** The namespace of this service */ - public String nameSpace; + private String nameSpace; /** The corresponding REST verb behaviour for this service */ - public String action; + private String action; /** The package name or location of this service */ - public String location; + private String location; /** The method or function to invoke for this service */ - public String invoke; + private String invoke; /** The default Entity to use for auto-attributes */ - public String defaultEntityName; + private String defaultEntityName; /** The loader which loaded this definition */ - public String fromLoader; + private String fromLoader; /** Does this service require authorization */ - public boolean auth; + private boolean auth; /** Can this service be exported via RPC, RMI, SOAP, etc */ - public boolean export; + private boolean export; /** Enable verbose debugging when calling this service */ - public boolean debug; + private boolean debug; /** Validate the context info for this service */ - public boolean validate; + private boolean validate; /** Create a transaction for this service (if one is not already in place...)? */ - public boolean useTransaction; + private boolean useTransaction; /** Require a new transaction for this service */ - public boolean requireNewTransaction; + private boolean requireNewTransaction; /** Override the default transaction timeout, only works if we start the transaction */ - public int transactionTimeout; + private int transactionTimeout; /** Sets the max number of times this service will retry when failed (persisted async only) */ - public int maxRetry = 0; + private int maxRetry = 0; /** Permission service*/ - ModelPermission modelPermission = null; + private ModelPermission modelPermission = null; /** Semaphore setting (wait, fail, none) */ - public String semaphore; + private String semaphore; /** Semaphore wait time (in milliseconds) */ - public int semaphoreWait; + private int semaphoreWait; /** Semaphore sleep time (in milliseconds) */ - public int semaphoreSleep; + private int semaphoreSleep; /** Require a new transaction for this service */ - public boolean hideResultInLog; + private boolean hideResultInLog; /** Set of services this service implements */ - public Set<ModelServiceIface> implServices = new LinkedHashSet<>(); + private Set<ModelServiceIface> implServices = new LinkedHashSet<>(); /** Set of override parameters */ - public Set<ModelParam> overrideParameters = new LinkedHashSet<>(); + private Set<ModelParam> overrideParameters = new LinkedHashSet<>(); /** List of permission groups for service invocation */ - public List<ModelPermGroup> permissionGroups = new LinkedList<>(); + private List<ModelPermGroup> permissionGroups = new LinkedList<>(); /** List of email-notifications for this service */ - public List<ModelNotification> notifications = new LinkedList<>(); + private List<ModelNotification> notifications = new LinkedList<>(); /** Internal Service Group */ - public GroupModel internalGroup = null; + private GroupModel internalGroup = null; /**Deprecated information*/ - public String deprecatedUseInstead = null; - public String deprecatedSince = null; - public String deprecatedReason = null; + private String deprecatedUseInstead = null; + private String deprecatedSince = null; + private String deprecatedReason = null; /** Context Information, a Map of parameters used by the service, contains ModelParam objects */ - protected Map<String, ModelParam> contextInfo = new LinkedHashMap<>(); + private Map<String, ModelParam> contextInfo = new LinkedHashMap<>(); /** Context Information, a List of parameters used by the service, contains ModelParam objects */ - protected List<ModelParam> contextParamList = new LinkedList<>(); + private List<ModelParam> contextParamList = new LinkedList<>(); /** Flag to say if we have pulled in our addition parameters from our implemented service(s) */ - protected boolean inheritedParameters = false; + private boolean inheritedParameters = false; /** * Service metrics. */ - public Metrics metrics = null; + private Metrics metrics = null; + + /** + * Sets name. + * @param name the name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets definition location. + * @param definitionLocation the definition location + */ + public void setDefinitionLocation(String definitionLocation) { + this.definitionLocation = definitionLocation; + } + + /** + * Sets description. + * @param description the description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Sets engine name. + * @param engineName the engine name + */ + public void setEngineName(String engineName) { + this.engineName = engineName; + } + + /** + * Sets name space. + * @param nameSpace the name space + */ + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + /** + * Sets action. + * @param action the action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Sets location. + * @param location the location + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Sets invoke. + * @param invoke the invoke + */ + public void setInvoke(String invoke) { + this.invoke = invoke; + } + + /** + * Sets default entity name. + * @param defaultEntityName the default entity name + */ + public void setDefaultEntityName(String defaultEntityName) { + this.defaultEntityName = defaultEntityName; + } + + /** + * Sets from loader. + * @param fromLoader the from loader + */ + public void setFromLoader(String fromLoader) { + this.fromLoader = fromLoader; + } + + /** + * Sets auth. + * @param auth the auth + */ + public void setAuth(boolean auth) { + this.auth = auth; + } + + /** + * Sets export. + * @param export the export + */ + public void setExport(boolean export) { + this.export = export; + } + + /** + * Sets debug. + * @param debug the debug + */ + public void setDebug(boolean debug) { + this.debug = debug; + } + + /** + * Sets validate. + * @param validate the validate + */ + public void setValidate(boolean validate) { + this.validate = validate; + } + + /** + * Sets use transaction. + * @param useTransaction the use transaction + */ + public void setUseTransaction(boolean useTransaction) { + this.useTransaction = useTransaction; + } + + /** + * Sets require new transaction. + * @param requireNewTransaction the require new transaction + */ + public void setRequireNewTransaction(boolean requireNewTransaction) { + this.requireNewTransaction = requireNewTransaction; + } + + /** + * Sets transaction timeout. + * @param transactionTimeout the transaction timeout + */ + public void setTransactionTimeout(int transactionTimeout) { + this.transactionTimeout = transactionTimeout; + } + + /** + * Sets max retry. + * @param maxRetry the max retry + */ + public void setMaxRetry(int maxRetry) { + this.maxRetry = maxRetry; + } + + /** + * Sets model permission. + * @param modelPermission the model permission + */ + public void setModelPermission(ModelPermission modelPermission) { + this.modelPermission = modelPermission; + } + + /** + * Sets semaphore. + * @param semaphore the semaphore + */ + public void setSemaphore(String semaphore) { + this.semaphore = semaphore; + } + + /** + * Sets semaphore wait. + * @param semaphoreWait the semaphore wait + */ + public void setSemaphoreWait(int semaphoreWait) { + this.semaphoreWait = semaphoreWait; + } + + /** + * Sets semaphore sleep. + * @param semaphoreSleep the semaphore sleep + */ + public void setSemaphoreSleep(int semaphoreSleep) { + this.semaphoreSleep = semaphoreSleep; + } + + /** + * Sets hide result in log. + * @param hideResultInLog the hide result in log + */ + public void setHideResultInLog(boolean hideResultInLog) { + this.hideResultInLog = hideResultInLog; + } + + /** + * Gets definition location. + * @return the definition location + */ + public String getDefinitionLocation() { + return definitionLocation; + } + + /** + * Sets impl services. + * @param implServices the impl services + */ + public void setImplServices(Set<ModelServiceIface> implServices) { + this.implServices = implServices; + } + + /** + * Sets override parameters. + * @param overrideParameters the override parameters + */ + public void setOverrideParameters(Set<ModelParam> overrideParameters) { + this.overrideParameters = overrideParameters; + } + + /** + * Sets permission groups. + * @param permissionGroups the permission groups + */ + public void setPermissionGroups(List<ModelPermGroup> permissionGroups) { + this.permissionGroups = permissionGroups; + } + + /** + * Sets notifications. + * @param notifications the notifications + */ + public void setNotifications(List<ModelNotification> notifications) { + this.notifications = notifications; + } + + /** + * Sets internal group. + * @param internalGroup the internal group + */ + public void setInternalGroup(GroupModel internalGroup) { + this.internalGroup = internalGroup; + } + + /** + * Sets deprecated use instead. + * @param deprecatedUseInstead the deprecated use instead + */ + public void setDeprecatedUseInstead(String deprecatedUseInstead) { + this.deprecatedUseInstead = deprecatedUseInstead; + } + + /** + * Sets deprecated since. + * @param deprecatedSince the deprecated since + */ + public void setDeprecatedSince(String deprecatedSince) { + this.deprecatedSince = deprecatedSince; + } + + /** + * Sets deprecated reason. + * @param deprecatedReason the deprecated reason + */ + public void setDeprecatedReason(String deprecatedReason) { + this.deprecatedReason = deprecatedReason; + } + + /** + * Sets context info. + * @param contextInfo the context info + */ + public void setContextInfo(Map<String, ModelParam> contextInfo) { + this.contextInfo = contextInfo; + } + + /** + * Sets context param list. + * @param contextParamList the context param list + */ + public void setContextParamList(List<ModelParam> contextParamList) { + this.contextParamList = contextParamList; + } + + /** + * Sets inherited parameters. + * @param inheritedParameters the inherited parameters + */ + public void setInheritedParameters(boolean inheritedParameters) { + this.inheritedParameters = inheritedParameters; + } + + /** + * Sets metrics. + * @param metrics the metrics + */ + public void setMetrics(Metrics metrics) { + this.metrics = metrics; + } + + /** + * Gets description. + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Gets name space. + * @return the name space + */ + public String getNameSpace() { + return nameSpace; + } + + /** + * Gets action. + * @return the action + */ + public String getAction() { + return action; + } + + /** + * Gets default entity name. + * @return the default entity name + */ + public String getDefaultEntityName() { + return defaultEntityName; + } + + /** + * Gets from loader. + * @return the from loader + */ + public String getFromLoader() { + return fromLoader; + } + + /** + * Is export boolean. + * @return the boolean + */ + public boolean isExport() { + return export; + } + + /** + * Gets semaphore wait. + * @return the semaphore wait + */ + public int getSemaphoreWait() { + return semaphoreWait; + } + + /** + * Gets semaphore sleep. + * @return the semaphore sleep + */ + public int getSemaphoreSleep() { + return semaphoreSleep; + } + + /** + * Gets impl services. + * @return the impl services + */ + public Set<ModelServiceIface> getImplServices() { + return implServices; + } + + /** + * Gets override parameters. + * @return the override parameters + */ + public Set<ModelParam> getOverrideParameters() { + return overrideParameters; + } + + /** + * Gets permission groups. + * @return the permission groups + */ + public List<ModelPermGroup> getPermissionGroups() { + return permissionGroups; + } + + /** + * Gets notifications. + * @return the notifications + */ + public List<ModelNotification> getNotifications() { + return notifications; + } + + /** + * Gets internal group. + * @return the internal group + */ + public GroupModel getInternalGroup() { + return internalGroup; + } + + /** + * Gets deprecated use instead. + * @return the deprecated use instead + */ + public String getDeprecatedUseInstead() { + return deprecatedUseInstead; + } + + /** + * Gets deprecated since. + * @return the deprecated since + */ + public String getDeprecatedSince() { + return deprecatedSince; + } + + /** + * Gets deprecated reason. + * @return the deprecated reason + */ + public String getDeprecatedReason() { + return deprecatedReason; + } + + /** + * Gets context info. + * @return the context info + */ + public Map<String, ModelParam> getContextInfo() { + return contextInfo; + } + + /** + * Gets context param list. + * @return the context param list + */ + public List<ModelParam> getContextParamList() { + return contextParamList; + } + + /** + * Is inherited parameters boolean. + * @return the boolean + */ + public boolean isInheritedParameters() { + return inheritedParameters; + } + + /** + * Gets name. + * @return the name + */ + public String getName() { + return name; + } + + /** + * Gets invoke. + * @return the invoke + */ + public String getInvoke() { + return invoke; + } + + /** + * Is hide result in log boolean. + * @return the boolean + */ + public boolean isHideResultInLog() { + return hideResultInLog; + } + + /** + * Gets metrics. + * @return the metrics + */ + public Metrics getMetrics() { + return metrics; + } + + /** + * Is auth boolean. + * @return the boolean + */ + public boolean isAuth() { + return auth; + } + + /** + * Is validate boolean. + * @return the boolean + */ + public boolean isValidate() { + return validate; + } + + /** + * Gets model permission. + * @return the model permission + */ + public ModelPermission getModelPermission() { + return modelPermission; + } + + /** + * Is use transaction boolean. + * @return the boolean + */ + public boolean isUseTransaction() { + return useTransaction; + } + + /** + * Is require new transaction boolean. + * @return the boolean + */ + public boolean isRequireNewTransaction() { + return requireNewTransaction; + } + + /** + * Gets transaction timeout. + * @return the transaction timeout + */ + public int getTransactionTimeout() { + return transactionTimeout; + } + + /** + * Gets max retry. + * @return the max retry + */ + public int getMaxRetry() { + return maxRetry; + } + + /** + * Gets engine name. + * @return the engine name + */ + public String getEngineName() { + return engineName; + } + + /** + * Gets location. + * @return the location + */ + public String getLocation() { + return location; + } + + /** + * Is debug boolean. + * @return the boolean + */ + public boolean isDebug() { + return debug; + } + + /** + * Gets semaphore. + * @return the semaphore + */ + public String getSemaphore() { + return semaphore; + } public ModelService() { } @@ -387,6 +947,10 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return buf.toString(); } + /** + * Debug info string. + * @return the string + */ public String debugInfo() { if (debug || Debug.verboseOn()) { return " [" + this.toString() + "]"; @@ -417,7 +981,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali */ public void addParam(ModelParam param) { if (param != null) { - contextInfo.put(param.name, param); + contextInfo.put(param.getName(), param); contextParamList.add(param); } } @@ -447,7 +1011,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali public Set<String> getAllParamNames() { Set<String> nameList = new TreeSet<>(); for (ModelParam p: this.contextParamList) { - nameList.add(p.name); + nameList.add(p.getName()); } return nameList; } @@ -457,7 +1021,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali for (ModelParam p: this.contextParamList) { // don't include OUT parameters in this list, only IN and INOUT if (p.isIn()) { - nameList.add(p.name); + nameList.add(p.getName()); } } return nameList; @@ -469,7 +1033,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali */ public Map<String, String> getInParamNamesMap() { // TODO : Does not yet support getting nested parameters - return getInModelParamList().stream().filter(param -> !param.internal) + return getInModelParamList().stream().filter(param -> !param.getInternal()) .collect(Collectors.toMap(ModelParam::getName, param -> param.getType())); } @@ -480,7 +1044,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali */ public Map<String, String> getOutParamNamesMap() { // TODO : Does not yet support getting nested parameters - return getModelParamList().stream().filter(param -> param.isOut() && !param.internal) + return getModelParamList().stream().filter(param -> param.isOut() && !param.getInternal()) .collect(Collectors.toMap(ModelParam::getName, param -> param.getType())); } @@ -490,7 +1054,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali for (ModelParam p: this.contextParamList) { // don't include OUT parameters in this list, only IN and INOUT - if (p.isIn() && !p.internal) { + if (p.isIn() && !p.getInternal()) { count++; } } @@ -498,24 +1062,28 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return count; } + /** + * Gets out param names. + * @return the out param names + */ public Set<String> getOutParamNames() { Set<String> nameList = new TreeSet<>(); for (ModelParam p: this.contextParamList) { // don't include IN parameters in this list, only OUT and INOUT if (p.isOut()) { - nameList.add(p.name); + nameList.add(p.getName()); } } return nameList; } - // only returns number of defined parameters (not internal) + /** only returns number of defined parameters (not internal) */ public int getDefinedOutCount() { int count = 0; for (ModelParam p: this.contextParamList) { // don't include IN parameters in this list, only OUT and INOUT - if (p.isOut() && !p.internal) { + if (p.isOut() && !p.getInternal()) { count++; } } @@ -523,15 +1091,20 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return count; } + /** + * Update default values. + * @param context the context + * @param mode the mode + */ public void updateDefaultValues(Map<String, Object> context, String mode) { List<ModelParam> params = this.getModelParamList(); for (ModelParam param: params) { if (param.getDefaultValue() != null - && (IN_OUT_PARAM.equals(param.mode) || mode.equals(param.mode))) { + && (IN_OUT_PARAM.equals(param.getMode()) || mode.equals(param.getMode()))) { Object defaultValueObj = param.getDefaultValue(context); - if (defaultValueObj != null && context.get(param.name) == null) { - context.put(param.name, defaultValueObj); - Debug.logInfo("Set default value [" + defaultValueObj + "] for parameter [" + param.name + "]", MODULE); + if (defaultValueObj != null && context.get(param.getName()) == null) { + context.put(param.getName(), defaultValueObj); + Debug.logInfo("Set default value [" + defaultValueObj + "] for parameter [" + param.getName() + "]", MODULE); } } } @@ -563,11 +1136,11 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali // get the info values for (ModelParam modelParam: this.contextParamList) { - if (IN_OUT_PARAM.equals(modelParam.mode) || mode.equals(modelParam.mode)) { - if (modelParam.optional) { - optionalInfo.put(modelParam.name, modelParam.type); + if (IN_OUT_PARAM.equals(modelParam.getMode()) || mode.equals(modelParam.getMode())) { + if (modelParam.isOptional()) { + optionalInfo.put(modelParam.getName(), modelParam.getType()); } else { - requiredInfo.put(modelParam.name, modelParam.type); + requiredInfo.put(modelParam.getName(), modelParam.getType()); } } } @@ -643,13 +1216,13 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali List<String> errorMessageList = new LinkedList<>(); for (ModelParam modelParam : this.contextInfo.values()) { // the param is a String, allow-html is not any, and we are looking at an IN parameter during input parameter validation - if (context.get(modelParam.name) != null && ("String".equals(modelParam.type) || "java.lang.String".equals(modelParam.type)) - && !"any".equals(modelParam.allowHtml) && (IN_OUT_PARAM.equals(modelParam.mode) || IN_PARAM.equals(modelParam.mode))) { - String value = (String) context.get(modelParam.name); - if ("none".equals(modelParam.allowHtml)) { - UtilCodec.checkStringForHtmlStrictNone(modelParam.name, value, errorMessageList, (Locale) context.get("locale")); - } else if ("safe".equals(modelParam.allowHtml)) { - UtilCodec.checkStringForHtmlSafe(modelParam.name, value, errorMessageList, + if (context.get(modelParam.getName()) != null && ("String".equals(modelParam.getType()) || "java.lang.String".equals(modelParam.getType())) + && !"any".equals(modelParam.getAllowHtml()) && (IN_OUT_PARAM.equals(modelParam.getMode()) || IN_PARAM.equals(modelParam.getMode()))) { + String value = (String) context.get(modelParam.getName()); + if ("none".equals(modelParam.getAllowHtml())) { + UtilCodec.checkStringForHtmlStrictNone(modelParam.getName(), value, errorMessageList, (Locale) context.get("locale")); + } else if ("safe".equals(modelParam.getAllowHtml())) { + UtilCodec.checkStringForHtmlSafe(modelParam.getName(), value, errorMessageList, (Locale) context.get("locale"), EntityUtilProperties.getPropertyAsBoolean("owasp", "sanitizer.enable", true)); } @@ -747,8 +1320,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali Object testObject = test.get(key); String infoType = info.get(key); - if (UtilValidate.isNotEmpty(param.validators)) { - for (ModelParam.ModelParamValidator val: param.validators) { + if (UtilValidate.isNotEmpty(param.getValidators())) { + for (ModelParam.ModelParamValidator val: param.getValidators()) { if (UtilValidate.isNotEmpty(val.getMethodName())) { try { if (!typeValidate(val, testObject)) { @@ -779,7 +1352,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } else { if (!ObjectType.instanceOf(testObject, infoType, null)) { String testType = testObject == null ? "null" : testObject.getClass().getName(); - String msg = "Type check failed for field [" + model.name + "." + key + "]; expected type is [" + infoType + "]; actual type is [" + testType + "]"; + String msg = "Type check failed for field [" + model.name + "." + key + "]; expected type is [" + infoType + + "]; actual type is [" + testType + "]"; typeFailMsgs.add(msg); } } @@ -843,7 +1417,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali try { resultBool = (Boolean) validatorMethod.invoke(null, param); } catch (ClassCastException e) { - throw new GeneralException("Validation method [" + vali.getMethodName() + "] in class [" + vali.getClassName() + "] did not return expected Boolean"); + throw new GeneralException("Validation method [" + vali.getMethodName() + "] in class [" + vali.getClassName() + + "] did not return expected Boolean"); } catch (Exception e) { throw new GeneralException("Unable to run validation method [" + vali.getMethodName() + "] in class [" + vali.getClassName() + "]"); } @@ -870,10 +1445,10 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return names; } for (ModelParam param: contextParamList) { - if (param.mode.equals(IN_OUT_PARAM) || param.mode.equals(mode)) { - if (optional || !param.optional) { - if (internal || !param.internal) { - names.add(param.name); + if (param.getMode().equals(IN_OUT_PARAM) || param.getMode().equals(mode)) { + if (optional || !param.isOptional()) { + if (internal || !param.getInternal()) { + names.add(param.getName()); } } } @@ -881,6 +1456,12 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return names; } + /** + * Gets parameter names. + * @param mode the mode + * @param optional the optional + * @return the parameter names + */ public List<String> getParameterNames(String mode, boolean optional) { return this.getParameterNames(mode, optional, true); } @@ -914,7 +1495,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali * @param includeInternal When false will exclude internal fields * @param locale Locale to use to do some type conversion */ - public Map<String, Object> makeValid(Map<String, ? extends Object> source, String mode, boolean includeInternal, List<Object> errorMessages, Locale locale) { + public Map<String, Object> makeValid(Map<String, ? extends Object> source, String mode, boolean includeInternal, List<Object> errorMessages, + Locale locale) { return makeValid(source, mode, includeInternal, errorMessages, null, locale); } @@ -928,7 +1510,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali * @param timeZone TimeZone to use to do some type conversion * @param locale Locale to use to do some type conversion */ - public Map<String, Object> makeValid(Map<String, ? extends Object> source, String mode, boolean includeInternal, List<Object> errorMessages, TimeZone timeZone, Locale locale) { + public Map<String, Object> makeValid(Map<String, ? extends Object> source, String mode, boolean includeInternal, List<Object> errorMessages, + TimeZone timeZone, Locale locale) { Map<String, Object> target = new HashMap<>(); if (source == null) { @@ -942,7 +1525,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } if (locale == null) { - // if statement here to avoid warning messages for Entity ECA service input validation, even though less efficient that doing a straight get + // if statement here to avoid warning messages for Entity ECA service input validation, + // even though less efficient that doing a straight get if (source.containsKey("locale")) { locale = (Locale) source.get("locale"); } @@ -952,7 +1536,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } if (timeZone == null) { - // if statement here to avoid warning messages for Entity ECA service input validation, even though less efficient that doing a straight get + // if statement here to avoid warning messages for Entity ECA service input validation, + // even though less efficient that doing a straight get if (source.containsKey("timeZone")) { timeZone = (TimeZone) source.get("timeZone"); } @@ -962,17 +1547,17 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } for (ModelParam param: contextParamList) { - if (param.mode.equals(IN_OUT_PARAM) || param.mode.equals(mode)) { - String key = param.name; + if (param.getMode().equals(IN_OUT_PARAM) || param.getMode().equals(mode)) { + String key = param.getName(); // internal map of strings - if (UtilValidate.isNotEmpty(param.stringMapPrefix) && !source.containsKey(key)) { + if (UtilValidate.isNotEmpty(param.getStringMapPrefix()) && !source.containsKey(key)) { Map<String, Object> paramMap = makePrefixMap(source, param); if (UtilValidate.isNotEmpty(paramMap)) { target.put(key, paramMap); } // internal list of strings - } else if (UtilValidate.isNotEmpty(param.stringListSuffix) && !source.containsKey(key)) { + } else if (UtilValidate.isNotEmpty(param.getStringListSuffix()) && !source.containsKey(key)) { List<Object> paramList = makeSuffixList(source, param); if (UtilValidate.isNotEmpty(paramList)) { target.put(key, paramList); @@ -980,14 +1565,14 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali // other attributes } else { if (source.containsKey(key)) { - if ((param.internal && includeInternal) || (!param.internal)) { + if ((param.getInternal() && includeInternal) || (!param.getInternal())) { Object value = source.get(key); try { // no need to fail on type conversion; the validator will catch this - value = ObjectType.simpleTypeOrObjectConvert(value, param.type, null, timeZone, locale, false); + value = ObjectType.simpleTypeOrObjectConvert(value, param.getType(), null, timeZone, locale, false); } catch (GeneralException e) { - String errMsg = "Type conversion of field [" + key + "] to type [" + param.type + "] failed for value \"" + value + "\": " + e.toString(); + String errMsg = "Type conversion of field [" + key + "] to type [" + param.getType() + "] failed for value \"" + value + "\": " + e.toString(); Debug.logWarning("[ModelService.makeValid] : " + errMsg, MODULE); if (errorMessages != null) { errorMessages.add(errMsg); @@ -1006,8 +1591,8 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali Map<String, Object> paramMap = new HashMap<>(); for (Map.Entry<String, ? extends Object> entry: source.entrySet()) { String key = entry.getKey(); - if (key.startsWith(param.stringMapPrefix)) { - key = key.replace(param.stringMapPrefix, ""); + if (key.startsWith(param.getStringMapPrefix())) { + key = key.replace(param.getStringMapPrefix(), ""); paramMap.put(key, entry.getValue()); } } @@ -1018,7 +1603,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali List<Object> paramList = new LinkedList<>(); for (Map.Entry<String, ? extends Object> entry: source.entrySet()) { String key = entry.getKey(); - if (key.endsWith(param.stringListSuffix)) { + if (key.endsWith(param.getStringListSuffix())) { paramList.add(entry.getValue()); } } @@ -1096,11 +1681,11 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } for (ModelParam modelParam: this.contextParamList) { // don't include OUT parameters in this list, only IN and INOUT - if (OUT_PARAM.equals(modelParam.mode)) { + if (OUT_PARAM.equals(modelParam.getMode())) { continue; } - Object srcObject = source.get(modelParam.name); + Object srcObject = source.get(modelParam.getName()); if (srcObject != null) { target.add(srcObject); } @@ -1126,7 +1711,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali List<ModelParam> inList = new LinkedList<>(); for (ModelParam modelParam: this.contextParamList) { // don't include OUT parameters in this list, only IN and INOUT - if (OUT_PARAM.equals(modelParam.mode)) { + if (OUT_PARAM.equals(modelParam.getMode())) { continue; } @@ -1166,14 +1751,14 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali ModelService model = dctx.getModelService(serviceName); if (model != null) { for (ModelParam newParam: model.contextParamList) { - ModelParam existingParam = this.contextInfo.get(newParam.name); + ModelParam existingParam = this.contextInfo.get(newParam.getName()); if (existingParam != null) { // if the existing param is not INOUT and the newParam.mode is different from existingParam.mode, make the existing param optional and INOUT // TODO: this is another case where having different optional/required settings for IN and OUT would be quite valuable... - if (!IN_OUT_PARAM.equals(existingParam.mode) && !existingParam.mode.equals(newParam.mode)) { - existingParam.mode = IN_OUT_PARAM; - if (existingParam.optional || newParam.optional) { - existingParam.optional = true; + if (!IN_OUT_PARAM.equals(existingParam.getMode()) && !existingParam.getMode().equals(newParam.getMode())) { + existingParam.setMode(IN_OUT_PARAM); + if (existingParam.isOptional() || newParam.isOptional()) { + existingParam.setOptional(true); } } } else { @@ -1181,7 +1766,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali if (optional) { // default option is to make this optional, however the service can override and // force the clone to use the parents setting. - newParamClone.optional = true; + newParamClone.setOptional(true); } this.addParam(newParamClone); } @@ -1195,43 +1780,43 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali // handle any override parameters if (UtilValidate.isNotEmpty(overrideParameters)) { for (ModelParam overrideParam: overrideParameters) { - ModelParam existingParam = contextInfo.get(overrideParam.name); + ModelParam existingParam = contextInfo.get(overrideParam.getName()); // keep the list clean, remove it then add it back contextParamList.remove(existingParam); if (existingParam != null) { // now re-write the parameters - if (UtilValidate.isNotEmpty(overrideParam.type)) { - existingParam.type = overrideParam.type; + if (UtilValidate.isNotEmpty(overrideParam.getType())) { + existingParam.setType(overrideParam.getType()); } - if (UtilValidate.isNotEmpty(overrideParam.mode)) { - existingParam.mode = overrideParam.mode; + if (UtilValidate.isNotEmpty(overrideParam.getMode())) { + existingParam.setMode(overrideParam.getMode()); } - if (UtilValidate.isNotEmpty(overrideParam.entityName)) { - existingParam.entityName = overrideParam.entityName; + if (UtilValidate.isNotEmpty(overrideParam.getEntityName())) { + existingParam.setEntityName(overrideParam.getEntityName()); } - if (UtilValidate.isNotEmpty(overrideParam.fieldName)) { - existingParam.fieldName = overrideParam.fieldName; + if (UtilValidate.isNotEmpty(overrideParam.getFieldName())) { + existingParam.setFieldName(overrideParam.getFieldName()); } - if (UtilValidate.isNotEmpty(overrideParam.formLabel)) { - existingParam.formLabel = overrideParam.formLabel; + if (UtilValidate.isNotEmpty(overrideParam.getFormLabel())) { + existingParam.setFormLabel(overrideParam.getFormLabel()); } if (overrideParam.getDefaultValue() != null) { existingParam.copyDefaultValue(overrideParam); } - if (overrideParam.overrideFormDisplay) { - existingParam.formDisplay = overrideParam.formDisplay; + if (overrideParam.isOverrideFormDisplay()) { + existingParam.setFormDisplay(overrideParam.isFormDisplay()); } - if (overrideParam.overrideOptional) { - existingParam.optional = overrideParam.optional; + if (overrideParam.isOverrideOptional()) { + existingParam.setOptional(overrideParam.isOptional()); } - if (UtilValidate.isNotEmpty(overrideParam.allowHtml)) { - existingParam.allowHtml = overrideParam.allowHtml; + if (UtilValidate.isNotEmpty(overrideParam.getAllowHtml())) { + existingParam.setAllowHtml(overrideParam.getAllowHtml()); } addParam(existingParam); } else { - Debug.logWarning("Override param found but no parameter existing; ignoring: " + overrideParam.name, MODULE); + Debug.logWarning("Override param found but no parameter existing; ignoring: " + overrideParam.getName(), MODULE); } } } @@ -1258,6 +1843,12 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali } } + /** + * To wsdl document. + * @param locationURI the location uri + * @return the document + * @throws WSDLException the wsdl exception + */ public Document toWSDL(String locationURI) throws WSDLException { WSDLFactory factory = WSDLFactory.newInstance(); Definition def = factory.newDefinition(); @@ -1269,6 +1860,12 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali return factory.newWSDLWriter().getDocument(def); } + /** + * Gets wsdl. + * @param def the def + * @param locationURI the location uri + * @throws WSDLException the wsdl exception + */ public void getWSDL(Definition def, String locationURI) throws WSDLException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -1295,14 +1892,14 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali Element documentation = document.createElement("wsdl:documentation"); for (String paramName : inParam) { ModelParam param = this.getParam(paramName); - if (!param.internal) { + if (!param.getInternal()) { Part part = param.getWSDLPart(def); Element attribute = document.createElement("attribute"); attribute.setAttribute("name", paramName); attribute.setAttribute("type", part.getTypeName().getLocalPart()); attribute.setAttribute("namespace", part.getTypeName().getNamespaceURI()); - attribute.setAttribute("java-class", param.type); - attribute.setAttribute("optional", Boolean.toString(param.optional)); + attribute.setAttribute("java-class", param.getType()); + attribute.setAttribute("optional", Boolean.toString(param.isOptional())); documentation.appendChild(attribute); } } @@ -1339,14 +1936,14 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali documentation = document.createElement("wsdl:documentation"); for (String paramName : outParam) { ModelParam param = this.getParam(paramName); - if (!param.internal) { + if (!param.getInternal()) { Part part = param.getWSDLPart(def); Element attribute = document.createElement("attribute"); attribute.setAttribute("name", paramName); attribute.setAttribute("type", part.getTypeName().getLocalPart()); attribute.setAttribute("namespace", part.getTypeName().getNamespaceURI()); - attribute.setAttribute("java-class", param.type); - attribute.setAttribute("optional", Boolean.toString(param.optional)); + attribute.setAttribute("java-class", param.getType()); + attribute.setAttribute("optional", Boolean.toString(param.isOptional())); documentation.appendChild(attribute); } } 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 22b0dc5..6259d3f 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 @@ -59,10 +59,10 @@ public class ModelServiceReader implements Serializable { private static final String MODULE = ModelServiceReader.class.getName(); /** is either from a URL or from a ResourceLoader (through the ResourceHandler) */ - protected boolean isFromURL; - protected URL readerURL = null; - protected ResourceHandler handler = null; - protected Delegator delegator = null; + private boolean isFromURL; + private URL readerURL = null; + private ResourceHandler handler = null; + private Delegator delegator = null; public static Map<String, ModelService> getModelServiceMap(URL readerURL, Delegator delegator) { if (readerURL == null) { @@ -143,8 +143,9 @@ public class ModelServiceReader implements Serializable { ModelService service = createModelService(curServiceElement, resourceLocation); modelServices.put(serviceName, service); - } - } while ((curChild = curChild.getNextSibling()) != null); + } + curChild = curChild.getNextSibling(); + } while (curChild != null); } else { Debug.logWarning("No child nodes found.", MODULE); } @@ -161,31 +162,32 @@ public class ModelServiceReader implements Serializable { private ModelService createModelService(Element serviceElement, String resourceLocation) { ModelService service = new ModelService(); - service.name = UtilXml.checkEmpty(serviceElement.getAttribute("name")).intern(); - service.definitionLocation = resourceLocation; - service.engineName = UtilXml.checkEmpty(serviceElement.getAttribute("engine")).intern(); - service.location = UtilXml.checkEmpty(serviceElement.getAttribute("location")).intern(); - service.invoke = UtilXml.checkEmpty(serviceElement.getAttribute("invoke")).intern(); - service.semaphore = UtilXml.checkEmpty(serviceElement.getAttribute("semaphore")).intern(); - service.defaultEntityName = UtilXml.checkEmpty(serviceElement.getAttribute("default-entity-name")).intern(); - service.fromLoader = isFromURL ? readerURL.toExternalForm() : handler.getLoaderName(); - service.action = UtilXml.checkEmpty(serviceElement.getAttribute("action")).intern(); + service.setName(UtilXml.checkEmpty(serviceElement.getAttribute("name")).intern()); + service.setDefinitionLocation(resourceLocation); + service.setEngineName(UtilXml.checkEmpty(serviceElement.getAttribute("engine")).intern()); + service.setLocation(UtilXml.checkEmpty(serviceElement.getAttribute("location")).intern()); + service.setInvoke(UtilXml.checkEmpty(serviceElement.getAttribute("invoke")).intern()); + service.setSemaphore(UtilXml.checkEmpty(serviceElement.getAttribute("semaphore")).intern()); + service.setDefaultEntityName(UtilXml.checkEmpty(serviceElement.getAttribute("default-entity-name")).intern()); + service.setFromLoader(isFromURL ? readerURL.toExternalForm() : handler.getLoaderName()); + service.setAction(UtilXml.checkEmpty(serviceElement.getAttribute("action")).intern()); // these default to true; if anything but true, make false - service.auth = "true".equalsIgnoreCase(serviceElement.getAttribute("auth")); - service.export = "true".equalsIgnoreCase(serviceElement.getAttribute("export")); - service.debug = "true".equalsIgnoreCase(serviceElement.getAttribute("debug")); + service.setAuth("true".equalsIgnoreCase(serviceElement.getAttribute("auth"))); + service.setExport("true".equalsIgnoreCase(serviceElement.getAttribute("export"))); + service.setDebug("true".equalsIgnoreCase(serviceElement.getAttribute("debug"))); // these defaults to false; if anything but false, make it true - service.validate = !"false".equalsIgnoreCase(serviceElement.getAttribute("validate")); - service.useTransaction = !"false".equalsIgnoreCase(serviceElement.getAttribute("use-transaction")); - service.requireNewTransaction = !"false".equalsIgnoreCase(serviceElement.getAttribute("require-new-transaction")); - if (service.requireNewTransaction && !service.useTransaction) { + service.setValidate(!"false".equalsIgnoreCase(serviceElement.getAttribute("validate"))); + service.setUseTransaction(!"false".equalsIgnoreCase(serviceElement.getAttribute("use-transaction"))); + service.setRequireNewTransaction(!"false".equalsIgnoreCase(serviceElement.getAttribute("require-new-transaction"))); + if (service.isRequireNewTransaction() && !service.isUseTransaction()) { // requireNewTransaction implies that a transaction is used - service.useTransaction = true; - Debug.logWarning("In service definition [" + service.name + "] the value use-transaction has been changed from false to true as required when require-new-transaction is set to true", MODULE); + service.setUseTransaction(true); + Debug.logWarning("In service definition [" + service.getName() + "] the value use-transaction has been changed from false to true as" + + "required when require-new-transaction is set to true", MODULE); } - service.hideResultInLog = !"false".equalsIgnoreCase(serviceElement.getAttribute("hideResultInLog")); + service.setHideResultInLog(!"false".equalsIgnoreCase(serviceElement.getAttribute("hideResultInLog"))); // set the semaphore sleep/wait times String semaphoreWaitStr = UtilXml.checkEmpty(serviceElement.getAttribute("semaphore-wait-seconds")); @@ -198,7 +200,7 @@ public class ModelServiceReader implements Serializable { semaphoreWait = 300; } } - service.semaphoreWait = semaphoreWait; + service.setSemaphoreWait(semaphoreWait); String semaphoreSleepStr = UtilXml.checkEmpty(serviceElement.getAttribute("semaphore-sleep")); int semaphoreSleep = 500; @@ -210,7 +212,7 @@ public class ModelServiceReader implements Serializable { semaphoreSleep = 500; } } - service.semaphoreSleep = semaphoreSleep; + service.setSemaphoreSleep(semaphoreSleep); // set the max retry field String maxRetryStr = UtilXml.checkEmpty(serviceElement.getAttribute("max-retry")); @@ -223,7 +225,7 @@ public class ModelServiceReader implements Serializable { maxRetry = 0; } } - service.maxRetry = maxRetry; + service.setMaxRetry(maxRetry); // get the timeout and convert to int String timeoutStr = UtilXml.checkEmpty(serviceElement.getAttribute("transaction-timeout"), serviceElement.getAttribute("transaction-timout")); @@ -236,13 +238,13 @@ public class ModelServiceReader implements Serializable { timeout = 0; } } - service.transactionTimeout = timeout; + service.setTransactionTimeout(timeout); - service.description = getCDATADef(serviceElement, "description"); - service.nameSpace = getCDATADef(serviceElement, "namespace"); + service.setDescription(getCDATADef(serviceElement, "description")); + service.setNameSpace(getCDATADef(serviceElement, "namespace")); // construct the context - service.contextInfo = new HashMap<>(); + service.setContextInfo(new HashMap<>()); createNotification(serviceElement, service); createAloneServicePermission(serviceElement, service); createPermGroups(serviceElement, service); @@ -255,7 +257,7 @@ public class ModelServiceReader implements Serializable { // Get metrics. Element metricsElement = UtilXml.firstChildElement(serviceElement, "metric"); if (metricsElement != null) { - service.metrics = MetricsFactory.getInstance(metricsElement); + service.setMetrics(MetricsFactory.getInstance(metricsElement)); } return service; } @@ -283,37 +285,37 @@ public class ModelServiceReader implements Serializable { // default notification groups ModelNotification nSuccess = new ModelNotification(); nSuccess.notificationEvent = "success"; - nSuccess.notificationGroupName = "default.success." + model.fromLoader; - model.notifications.add(nSuccess); + nSuccess.notificationGroupName = "default.success." + model.getFromLoader(); + model.getNotifications().add(nSuccess); ModelNotification nFail = new ModelNotification(); nFail.notificationEvent = "fail"; - nFail.notificationGroupName = "default.fail." + model.fromLoader; - model.notifications.add(nFail); + nFail.notificationGroupName = "default.fail." + model.getFromLoader(); + model.getNotifications().add(nFail); ModelNotification nError = new ModelNotification(); nError.notificationEvent = "error"; - nError.notificationGroupName = "default.error." + model.fromLoader; - model.notifications.add(nError); + nError.notificationGroupName = "default.error." + model.getFromLoader(); + model.getNotifications().add(nError); if (n != null) { for (Element e: n) { ModelNotification notify = new ModelNotification(); notify.notificationEvent = e.getAttribute("event"); notify.notificationGroupName = e.getAttribute("group"); - model.notifications.add(notify); + model.getNotifications().add(notify); } } } private static ModelPermission createServicePermission(Element e, ModelService model) { ModelPermission modelPermission = new ModelPermission(); - modelPermission.permissionType = ModelPermission.PERMISSION_SERVICE; - modelPermission.permissionServiceName = e.getAttribute("service-name"); - modelPermission.permissionMainAction = e.getAttribute("main-action"); - modelPermission.permissionResourceDesc = e.getAttribute("resource-description"); - modelPermission.permissionRequireNewTransaction = !"false".equalsIgnoreCase(e.getAttribute("require-new-transaction")); - modelPermission.serviceModel = model; + modelPermission.setPermissionType(ModelPermission.getPermissionService()); + modelPermission.setPermissionServiceName(e.getAttribute("service-name")); + modelPermission.setPermissionMainAction(e.getAttribute("main-action")); + modelPermission.setPermissionResourceDesc(e.getAttribute("resource-description")); + modelPermission.setPermissionRequireNewTransaction(!"false".equalsIgnoreCase(e.getAttribute("require-new-transaction"))); + modelPermission.setServiceModel(model); return modelPermission; } @@ -321,10 +323,10 @@ public class ModelServiceReader implements Serializable { Element e = UtilXml.firstChildElement(baseElement, "permission-service"); if (e != null) { ModelPermission modelPermission = createServicePermission(e, model); - model.modelPermission = modelPermission; + model.setModelPermission(modelPermission); // auth is always required when permissions are set - model.auth = true; + model.setAuth(true); } } @@ -333,7 +335,7 @@ public class ModelServiceReader implements Serializable { ModelPermGroup group = new ModelPermGroup(); group.joinType = element.getAttribute("join-type"); createGroupPermissions(element, group, model); - model.permissionGroups.add(group); + model.getPermissionGroups().add(group); } } @@ -341,14 +343,14 @@ public class ModelServiceReader implements Serializable { // create the simple permissions for (Element element: UtilXml.childElementList(baseElement, "check-permission")) { ModelPermission perm = new ModelPermission(); - perm.nameOrRole = element.getAttribute("permission").intern(); - perm.action = element.getAttribute("action").intern(); - if (UtilValidate.isNotEmpty(perm.action)) { - perm.permissionType = ModelPermission.ENTITY_PERMISSION; + perm.setNameOrRole(element.getAttribute("permission").intern()); + perm.setAction(element.getAttribute("action").intern()); + if (UtilValidate.isNotEmpty(perm.getAction())) { + perm.setPermissionType(ModelPermission.getEntityPermission()); } else { - perm.permissionType = ModelPermission.PERMISSION; + perm.setPermissionType(ModelPermission.getPERMISSION()); } - perm.serviceModel = service; + perm.setServiceModel(service); group.permissions.add(perm); } @@ -358,7 +360,7 @@ public class ModelServiceReader implements Serializable { } if (UtilValidate.isNotEmpty(group.permissions)) { // auth is always required when permissions are set - service.auth = true; + service.setAuth(true); } } @@ -366,11 +368,11 @@ public class ModelServiceReader implements Serializable { List<? extends Element> group = UtilXml.childElementList(baseElement, "group"); if (UtilValidate.isNotEmpty(group)) { Element groupElement = group.get(0); - groupElement.setAttribute("name", "_" + service.name + ".group"); - service.internalGroup = new GroupModel(groupElement); - service.invoke = service.internalGroup.getGroupName(); + groupElement.setAttribute("name", "_" + service.getName() + ".group"); + service.setInternalGroup(new GroupModel(groupElement)); + service.setInvoke(service.getInternalGroup().getGroupName()); if (Debug.verboseOn()) { - Debug.logVerbose("Created INTERNAL GROUP model [" + service.internalGroup + "]", MODULE); + Debug.logVerbose("Created INTERNAL GROUP model [" + service.getInternalGroup() + "]", MODULE); } } } @@ -380,7 +382,7 @@ public class ModelServiceReader implements Serializable { String serviceName = UtilXml.checkEmpty(implement.getAttribute("service")).intern(); boolean optional = UtilXml.checkBoolean(implement.getAttribute("optional"), false); if (serviceName.length() > 0) { - service.implServices.add(new ModelServiceIface(serviceName, optional)); + service.getImplServices().add(new ModelServiceIface(serviceName, optional)); } } } @@ -395,7 +397,7 @@ public class ModelServiceReader implements Serializable { // get the entity name; first from the auto-attributes then from the service def String entityName = UtilXml.checkEmpty(autoElement.getAttribute("entity-name")); if (UtilValidate.isEmpty(entityName)) { - entityName = service.defaultEntityName; + entityName = service.getDefaultEntityName(); if (UtilValidate.isEmpty(entityName)) { Debug.logWarning("Auto-Attribute does not specify an entity-name; not default-entity on service definition", MODULE); } @@ -426,18 +428,18 @@ public class ModelServiceReader implements Serializable { throw new GeneralException("Null field type from delegator for entity [" + entityName + "]"); } ModelParam param = new ModelParam(); - param.entityName = entityName; - param.fieldName = field.getName(); - param.name = field.getName(); - param.type = fieldType.getJavaType(); + param.setEntityName(entityName); + param.setFieldName(field.getName()); + param.setName(field.getName()); + param.setType(fieldType.getJavaType()); // this is a special case where we use something different in the service layer than we do in the entity/data layer - if ("java.sql.Blob".equals(param.type)) { - param.type = "java.nio.ByteBuffer"; + if ("java.sql.Blob".equals(param.getType())) { + param.setType("java.nio.ByteBuffer"); } - param.mode = UtilXml.checkEmpty(autoElement.getAttribute("mode")).intern(); - param.optional = "true".equalsIgnoreCase(autoElement.getAttribute("optional")); // default to true - param.formDisplay = !"false".equalsIgnoreCase(autoElement.getAttribute("form-display")); // default to false - param.allowHtml = UtilXml.checkEmpty(autoElement.getAttribute("allow-html"), "none").intern(); // default to none + param.setMode(UtilXml.checkEmpty(autoElement.getAttribute("mode")).intern()); + param.setOptional("true".equalsIgnoreCase(autoElement.getAttribute("optional"))); // default to true + param.setFormDisplay(!"false".equalsIgnoreCase(autoElement.getAttribute("form-display"))); // default to false + param.setAllowHtml(UtilXml.checkEmpty(autoElement.getAttribute("allow-html"), "none").intern()); // default to none modelParamMap.put(field.getName(), param); } } @@ -455,9 +457,9 @@ public class ModelServiceReader implements Serializable { service.addParam(thisParam); } } catch (GenericEntityException e) { - Debug.logError(e, "Problem loading auto-attributes [" + entityName + "] for " + service.name, MODULE); + Debug.logError(e, "Problem loading auto-attributes [" + entityName + "] for " + service.getName(), MODULE); } catch (GeneralException e) { - Debug.logError(e, "Cannot load auto-attributes : " + e.getMessage() + " for " + service.name, MODULE); + Debug.logError(e, "Cannot load auto-attributes : " + e.getMessage() + " for " + service.getName(), MODULE); } } } @@ -467,38 +469,39 @@ public class ModelServiceReader implements Serializable { for (Element attribute: UtilXml.childElementList(baseElement, "attribute")) { ModelParam param = new ModelParam(); - param.name = UtilXml.checkEmpty(attribute.getAttribute("name")).intern(); - param.description = getCDATADef(attribute, "description"); - param.type = UtilXml.checkEmpty(attribute.getAttribute("type")).intern(); - param.mode = UtilXml.checkEmpty(attribute.getAttribute("mode")).intern(); - param.entityName = UtilXml.checkEmpty(attribute.getAttribute("entity-name")).intern(); - param.fieldName = UtilXml.checkEmpty(attribute.getAttribute("field-name")).intern(); - param.requestAttributeName = UtilXml.checkEmpty(attribute.getAttribute("request-attribute-name")).intern(); - param.sessionAttributeName = UtilXml.checkEmpty(attribute.getAttribute("session-attribute-name")).intern(); - param.stringMapPrefix = UtilXml.checkEmpty(attribute.getAttribute("string-map-prefix")).intern(); - param.stringListSuffix = UtilXml.checkEmpty(attribute.getAttribute("string-list-suffix")).intern(); - param.formLabel = attribute.hasAttribute("form-label")?attribute.getAttribute("form-label").intern():null; - param.optional = "true".equalsIgnoreCase(attribute.getAttribute("optional")); // default to true - param.formDisplay = !"false".equalsIgnoreCase(attribute.getAttribute("form-display")); // default to false - param.allowHtml = UtilXml.checkEmpty(attribute.getAttribute("allow-html"), "none").intern(); // default to none + param.setName(UtilXml.checkEmpty(attribute.getAttribute("name")).intern()); + param.setDescription(getCDATADef(attribute, "description")); + param.setType(UtilXml.checkEmpty(attribute.getAttribute("type")).intern()); + param.setMode(UtilXml.checkEmpty(attribute.getAttribute("mode")).intern()); + param.setEntityName(UtilXml.checkEmpty(attribute.getAttribute("entity-name")).intern()); + param.setFieldName(UtilXml.checkEmpty(attribute.getAttribute("field-name")).intern()); + param.setRequestAttributeName(UtilXml.checkEmpty(attribute.getAttribute("request-attribute-name")).intern()); + param.setSessionAttributeName(UtilXml.checkEmpty(attribute.getAttribute("session-attribute-name")).intern()); + param.setStringMapPrefix(UtilXml.checkEmpty(attribute.getAttribute("string-map-prefix")).intern()); + param.setStringListSuffix(UtilXml.checkEmpty(attribute.getAttribute("string-list-suffix")).intern()); + param.setFormLabel(attribute.hasAttribute("form-label") ? attribute.getAttribute("form-label").intern() : null); + param.setOptional("true".equalsIgnoreCase(attribute.getAttribute("optional"))); // default to true + param.setFormDisplay(!"false".equalsIgnoreCase(attribute.getAttribute("form-display"))); // default to false + param.setAllowHtml(UtilXml.checkEmpty(attribute.getAttribute("allow-html"), "none").intern()); // default to none // default value String defValue = attribute.getAttribute("default-value"); if (UtilValidate.isNotEmpty(defValue)) { if (Debug.verboseOn()) { - Debug.logVerbose("Got a default-value [" + defValue + "] for service attribute [" + service.name + "." + param.name + "]", MODULE); + Debug.logVerbose("Got a default-value [" + defValue + "] for service attribute [" + service.getName() + "." + + param.getName() + "]", MODULE); } param.setDefaultValue(defValue.intern()); } // set the entity name to the default if not specified - if (param.entityName.length() == 0) { - param.entityName = service.defaultEntityName; + if (param.getEntityName().length() == 0) { + param.setEntityName(service.getDefaultEntityName()); } // set the field-name to the name if entity name is specified but no field-name - if (param.fieldName.length() == 0 && param.entityName.length() > 0) { - param.fieldName = param.name; + if (param.getFieldName().length() == 0 && param.getEntityName().length() > 0) { + param.setFieldName(param.getName()); } // set the validators @@ -511,91 +514,91 @@ public class ModelServiceReader implements Serializable { // responseMessage def = new ModelParam(); - def.name = ModelService.RESPONSE_MESSAGE; - def.type = "String"; - def.mode = ModelService.OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName(ModelService.RESPONSE_MESSAGE); + def.setType("String"); + def.setMode(ModelService.OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // errorMessage def = new ModelParam(); - def.name = ModelService.ERROR_MESSAGE; - def.type = "String"; - def.mode = ModelService.OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName(ModelService.ERROR_MESSAGE); + def.setType("String"); + def.setMode(ModelService.OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // errorMessageList def = new ModelParam(); - def.name = ModelService.ERROR_MESSAGE_LIST; - def.type = "java.util.List"; - def.mode = ModelService.OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName(ModelService.ERROR_MESSAGE_LIST); + def.setType("java.util.List"); + def.setMode(ModelService.OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // successMessage def = new ModelParam(); - def.name = ModelService.SUCCESS_MESSAGE; - def.type = "String"; - def.mode = ModelService.OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName(ModelService.SUCCESS_MESSAGE); + def.setType("String"); + def.setMode(ModelService.OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // successMessageList def = new ModelParam(); - def.name = ModelService.SUCCESS_MESSAGE_LIST; - def.type = "java.util.List"; - def.mode = ModelService.OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName(ModelService.SUCCESS_MESSAGE_LIST); + def.setType("java.util.List"); + def.setMode(ModelService.OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // userLogin def = new ModelParam(); - def.name = "userLogin"; - def.type = "org.apache.ofbiz.entity.GenericValue"; - def.mode = ModelService.IN_OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName("userLogin"); + def.setType("org.apache.ofbiz.entity.GenericValue"); + def.setMode(ModelService.IN_OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // login.username def = new ModelParam(); - def.name = "login.username"; - def.type = "String"; - def.mode = ModelService.IN_PARAM; - def.optional = true; - def.internal = true; + def.setName("login.username"); + def.setType("String"); + def.setMode(ModelService.IN_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // login.password def = new ModelParam(); - def.name = "login.password"; - def.type = "String"; - def.mode = ModelService.IN_PARAM; - def.optional = true; - def.internal = true; + def.setName("login.password"); + def.setType("String"); + def.setMode(ModelService.IN_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // Locale def = new ModelParam(); - def.name = "locale"; - def.type = "java.util.Locale"; - def.mode = ModelService.IN_OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName("locale"); + def.setType("java.util.Locale"); + def.setMode(ModelService.IN_OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // timeZone def = new ModelParam(); - def.name = "timeZone"; - def.type = "java.util.TimeZone"; - def.mode = ModelService.IN_OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName("timeZone"); + def.setType("java.util.TimeZone"); + def.setMode(ModelService.IN_OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); // visualTheme def = new ModelParam(); - def.name = "visualTheme"; - def.type = "org.apache.ofbiz.widget.renderer.VisualTheme"; - def.mode = ModelService.IN_OUT_PARAM; - def.optional = true; - def.internal = true; + def.setName("visualTheme"); + def.setType("org.apache.ofbiz.widget.renderer.VisualTheme"); + def.setMode(ModelService.IN_OUT_PARAM); + def.setOptional(true); + def.setInternal(true); service.addParam(def); } @@ -605,45 +608,45 @@ public class ModelServiceReader implements Serializable { ModelParam param = service.getParam(name); boolean directToParams = true; if (param == null) { - if (!service.inheritedParameters && (service.implServices.size() > 0 || "group".equals(service.engineName))) { + if (!service.isInheritedParameters() && (service.getInModelParamList().size() > 0 || "group".equals(service.getEngineName()))) { // create a temp def to place in the ModelService // this will get read when we read implemented services directToParams = false; param = new ModelParam(); - param.name = name; + param.setName(name); } else { - Debug.logWarning("No parameter found for override parameter named: " + name + " in service " + service.name, MODULE); + Debug.logWarning("No parameter found for override parameter named: " + name + " in service " + service.getName(), MODULE); } } if (param != null) { // set only modified values if (UtilValidate.isNotEmpty(overrideElement.getAttribute("type"))) { - param.type = UtilXml.checkEmpty(overrideElement.getAttribute("type")).intern(); + param.setType(UtilXml.checkEmpty(overrideElement.getAttribute("type")).intern()); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("mode"))) { - param.mode = UtilXml.checkEmpty(overrideElement.getAttribute("mode")).intern(); + param.setMode(UtilXml.checkEmpty(overrideElement.getAttribute("mode")).intern()); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("entity-name"))) { - param.entityName = UtilXml.checkEmpty(overrideElement.getAttribute("entity-name")).intern(); + param.setEntityName(UtilXml.checkEmpty(overrideElement.getAttribute("entity-name")).intern()); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("field-name"))) { - param.fieldName = UtilXml.checkEmpty(overrideElement.getAttribute("field-name")).intern(); + param.setFieldName(UtilXml.checkEmpty(overrideElement.getAttribute("field-name")).intern()); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("form-label"))) { - param.formLabel = UtilXml.checkEmpty(overrideElement.getAttribute("form-label")).intern(); + param.setFormLabel(UtilXml.checkEmpty(overrideElement.getAttribute("form-label")).intern()); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("optional"))) { - param.optional = "true".equalsIgnoreCase(overrideElement.getAttribute("optional")); // default to true - param.overrideOptional = true; + param.setOptional("true".equalsIgnoreCase(overrideElement.getAttribute("optional"))); // default to true + param.setOverrideOptional(true); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("form-display"))) { - param.formDisplay = !"false".equalsIgnoreCase(overrideElement.getAttribute("form-display")); // default to false - param.overrideFormDisplay = true; + param.setFormDisplay(!"false".equalsIgnoreCase(overrideElement.getAttribute("form-display"))); // default to false + param.setOverrideFormDisplay(true); } if (UtilValidate.isNotEmpty(overrideElement.getAttribute("allow-html"))) { - param.allowHtml = UtilXml.checkEmpty(overrideElement.getAttribute("allow-html")).intern(); + param.setAllowHtml(UtilXml.checkEmpty(overrideElement.getAttribute("allow-html")).intern()); } // default value @@ -658,7 +661,7 @@ public class ModelServiceReader implements Serializable { if (directToParams) { service.addParam(param); } else { - service.overrideParameters.add(param); + service.getOverrideParameters().add(param); } } } @@ -667,9 +670,9 @@ public class ModelServiceReader implements Serializable { private static void createDeprecated(Element baseElement, ModelService service) { Element deprecated = UtilXml.firstChildElement(baseElement, "deprecated"); if (deprecated != null) { - service.deprecatedUseInstead = deprecated.getAttribute("use-instead"); - service.deprecatedSince = deprecated.getAttribute("since"); - service.deprecatedReason = UtilXml.elementValue(deprecated); + service.setDeprecatedUseInstead(deprecated.getAttribute("use-instead")); + service.setDeprecatedSince(deprecated.getAttribute("since")); + service.setDeprecatedReason(UtilXml.elementValue(deprecated)); service.informIfDeprecated(); } } @@ -678,7 +681,7 @@ public class ModelServiceReader implements Serializable { List<? extends Element> validateElements = UtilXml.childElementList(attribute, "type-validate"); if (UtilValidate.isNotEmpty(validateElements)) { // always clear out old ones; never append - param.validators = new LinkedList<>(); + param.setValidators(new LinkedList<>()); Element validate = validateElements.get(0); String methodName = validate.getAttribute("method").intern(); 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 576e159..f9def66 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 @@ -67,10 +67,11 @@ import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; public final class ServiceDispatcher { private static final String MODULE = ServiceDispatcher.class.getName(); - public static final int lruLogSize = 200; + public static final int LRU_LOG_SIZE = 200; public static final int LOCK_RETRIES = 3; - private static final Map<RunningService, ServiceDispatcher> runLog = new ConcurrentLinkedHashMap.Builder<RunningService, ServiceDispatcher>().maximumWeightedCapacity(lruLogSize).build(); + private static final Map<RunningService, ServiceDispatcher> RUN_LOG = new ConcurrentLinkedHashMap.Builder<RunningService, + ServiceDispatcher>().maximumWeightedCapacity(LRU_LOG_SIZE).build(); private static ConcurrentHashMap<String, ServiceDispatcher> dispatchers = new ConcurrentHashMap<>(); // FIXME: These fields are not thread-safe. They are modified by EntityDataLoadContainer. // We need a better design - like have this class query EntityDataLoadContainer if data is being loaded. @@ -234,7 +235,8 @@ public final class ServiceDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - public Map<String, Object> runSync(String localName, ModelService service, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public Map<String, Object> runSync(String localName, ModelService service, Map<String, ? extends Object> context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { return runSync(localName, service, context, true); } @@ -247,7 +249,8 @@ public final class ServiceDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - public void runSyncIgnore(String localName, ModelService service, Map<String, ? extends Object> context) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runSyncIgnore(String localName, ModelService service, Map<String, ? extends Object> context) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { runSync(localName, service, context, false); } @@ -262,7 +265,8 @@ public final class ServiceDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, ? extends Object> params, boolean validateOut) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, ? extends Object> params, boolean validateOut) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { long serviceStartTime = System.currentTimeMillis(); Map<String, Object> result = new HashMap<>(); ServiceSemaphore lock = null; @@ -277,15 +281,15 @@ public final class ServiceDispatcher { boolean beganTrans = false; try { // check for semaphore and acquire a lock - if ("wait".equals(modelService.semaphore) || "fail".equals(modelService.semaphore)) { + if ("wait".equals(modelService.getSemaphore()) || "fail".equals(modelService.getSemaphore())) { lock = new ServiceSemaphore(delegator, modelService); lock.acquire(); } - if (Debug.verboseOn() || modelService.debug) { + if (Debug.verboseOn() || modelService.isDebug()) { 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.getName() + " [" + modelService.getLocation() + + "/" + modelService.getInvoke() + "] (" + modelService.getEngineName() + ")", MODULE); } } @@ -300,31 +304,32 @@ public final class ServiceDispatcher { rs = this.logService(localName, modelService, GenericEngine.SYNC_MODE); // get eventMap once for all calls for speed, don't do event calls if it is null - eventMap = ServiceEcaUtil.getServiceEventMap(modelService.name); - engine = this.getGenericEngine(modelService.engineName); + eventMap = ServiceEcaUtil.getServiceEventMap(modelService.getName()); + engine = this.getGenericEngine(modelService.getEngineName()); modelService.informIfDeprecated(); // set IN attributes with default-value as applicable modelService.updateDefaultValues(context, ModelService.IN_PARAM); - if (modelService.useTransaction) { + if (modelService.isUseTransaction()) { if (TransactionUtil.isTransactionInPlace()) { // if a new transaction is needed, do it here; if not do nothing, just use current tx - if (modelService.requireNewTransaction) { + if (modelService.isRequireNewTransaction()) { parentTransaction = TransactionUtil.suspend(); if (TransactionUtil.isTransactionInPlace()) { rs.setEndStamp(); - throw new GenericTransactionException("In service " + modelService.name + " transaction is still in place after suspend, status is " + TransactionUtil.getStatusString()); + throw new GenericTransactionException("In service " + modelService.getName() + + " transaction is still in place after suspend, status is " + TransactionUtil.getStatusString()); } // now start a new transaction - beganTrans = TransactionUtil.begin(modelService.transactionTimeout); + beganTrans = TransactionUtil.begin(modelService.getTransactionTimeout()); } } else { - beganTrans = TransactionUtil.begin(modelService.transactionTimeout); + beganTrans = TransactionUtil.begin(modelService.getTransactionTimeout()); } // enlist for XAResource debugging if (beganTrans && TransactionUtil.debugResources()) { - DebugXaResource dxa = new DebugXaResource(modelService.name); + DebugXaResource dxa = new DebugXaResource(modelService.getName()); try { dxa.enlist(); } catch (Exception e) { @@ -352,15 +357,15 @@ public final class ServiceDispatcher { // setup global transaction ECA listeners to execute later if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "global-rollback", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "global-rollback", ctx, context, result, isError, isFailure); } if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "global-commit", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "global-commit", ctx, context, result, isError, isFailure); } // pre-auth ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "auth", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "auth", ctx, context, result, isError, isFailure); } // check for pre-auth failure/errors @@ -370,9 +375,10 @@ public final class ServiceDispatcher { context = checkAuth(localName, context, modelService); GenericValue userLogin = (GenericValue) context.get("userLogin"); - if (modelService.auth && userLogin == null) { + if (modelService.isAuth() && userLogin == null) { rs.setEndStamp(); - throw new ServiceAuthException("User authorization is required for this service: " + modelService.name + modelService.debugInfo()); + throw new ServiceAuthException("User authorization is required for this service: " + modelService.getName() + + modelService.debugInfo()); } // now that we have authed, if there is a userLogin, set the EE userIdentifier @@ -382,7 +388,7 @@ public final class ServiceDispatcher { // pre-validate ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "in-validate", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "in-validate", ctx, context, result, isError, isFailure); } // check for pre-validate failure/errors @@ -390,13 +396,14 @@ public final class ServiceDispatcher { isError = ServiceUtil.isError(result); // validate the context - if (modelService.validate && !isError && !isFailure) { + if (modelService.isValidate() && !isError && !isFailure) { try { // FIXME without this line all simple test failed - context = ctx.makeValidContext(modelService.name, ModelService.IN_PARAM, context); + context = ctx.makeValidContext(modelService.getName(), ModelService.IN_PARAM, context); modelService.validate(context, ModelService.IN_PARAM, locale); } catch (ServiceValidationException e) { - Debug.logError(e, "Incoming context (in runSync : " + modelService.name + ") does not match expected requirements", MODULE); + Debug.logError(e, "Incoming context (in runSync : " + modelService.getName() + + ") does not match expected requirements", MODULE); rs.setEndStamp(); throw e; } @@ -404,7 +411,7 @@ public final class ServiceDispatcher { // pre-invoke ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "invoke", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "invoke", ctx, context, result, isError, isFailure); } // check for pre-invoke failure/errors @@ -419,7 +426,7 @@ public final class ServiceDispatcher { if (invokeResult != null) { result.putAll(invokeResult); } else { - Debug.logWarning("Service (in runSync : " + modelService.name + ") returns null result", MODULE); + Debug.logWarning("Service (in runSync : " + modelService.getName() + ") returns null result", MODULE); } } @@ -428,7 +435,8 @@ public final class ServiceDispatcher { isError = ServiceUtil.isError(result); if (beganTrans) { - // crazy stuff here: see if there was a deadlock or other such error and if so retry... which we can ONLY do if we own the transaction! + // crazy stuff here: see if there was a deadlock or other such error and if so retry... + // which we can ONLY do if we own the transaction! String errMsg = ServiceUtil.getErrorMessage(result); @@ -444,17 +452,18 @@ public final class ServiceDispatcher { //service is written to not ignore it of course! if (errMsg != null && errMsg.toUpperCase(Locale.getDefault()).indexOf("DEADLOCK") >= 0) { // it's a deadlock! retry... - String retryMsg = "RETRYING SERVICE [" + modelService.name + "]: Deadlock error found in message [" + errMsg + "]; retry [" + (LOCK_RETRIES - lockRetriesRemaining) + "] of [" + LOCK_RETRIES + "]"; + String retryMsg = "RETRYING SERVICE [" + modelService.getName() + "]: Deadlock error found in message [" + errMsg + + "]; retry [" + (LOCK_RETRIES - lockRetriesRemaining) + "] of [" + LOCK_RETRIES + "]"; // make sure the old transaction is rolled back, and then start a new one // if there is an exception in these things, let the big overall thing handle it TransactionUtil.rollback(beganTrans, retryMsg, null); - beganTrans = TransactionUtil.begin(modelService.transactionTimeout); + beganTrans = TransactionUtil.begin(modelService.getTransactionTimeout()); // enlist for XAResource debugging if (beganTrans && TransactionUtil.debugResources()) { - DebugXaResource dxa = new DebugXaResource(modelService.name); + DebugXaResource dxa = new DebugXaResource(modelService.getName()); try { dxa.enlist(); } catch (Exception e) { @@ -477,13 +486,14 @@ public final class ServiceDispatcher { Debug.logWarning(retryMsg, MODULE); } - // look for lock wait timeout error, retry in a different way by running after the parent transaction finishes, ie attach to parent tx + // look for lock wait timeout error, retry in a different way by running after the parent transaction finishes, + // ie attach to parent tx // - Derby 10.2.2.0 lock wait timeout string: "A lock could not be obtained within the time requested" // - MySQL ? lock wait timeout string: "Lock wait timeout exceeded; try restarting transaction" - if (errMsg.indexOf("A lock could not be obtained within the time requested") >= 0 - || errMsg.indexOf("Lock wait timeout exceeded") >= 0) { + //if (errMsg.indexOf("A lock could not be obtained within the time requested") >= 0 + // || errMsg.indexOf("Lock wait timeout exceeded") >= 0) { // TODO: add to run after parent tx - } + //} } } } while (needsLockRetry && lockRetriesRemaining > 0); @@ -498,23 +508,24 @@ public final class ServiceDispatcher { modelService.updateDefaultValues(context, ModelService.OUT_PARAM); // validate the result - if (modelService.validate && validateOut) { + if (modelService.isValidate() && validateOut) { // pre-out-validate ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "out-validate", ctx, ecaContext, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "out-validate", ctx, ecaContext, result, isError, isFailure); } try { - result = ctx.makeValidContext(modelService.name, ModelService.OUT_PARAM, result); + result = ctx.makeValidContext(modelService.getName(), ModelService.OUT_PARAM, result); modelService.validate(result, ModelService.OUT_PARAM, locale); } catch (ServiceValidationException e) { rs.setEndStamp(); - throw new GenericServiceException("Outgoing result (in runSync : " + modelService.name + ") does not match expected requirements", e); + throw new GenericServiceException("Outgoing result (in runSync : " + modelService.getName() + + ") does not match expected requirements", e); } } // pre-commit ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "commit", ctx, ecaContext, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "commit", ctx, ecaContext, result, isError, isFailure); } // check for pre-commit failure/errors @@ -523,18 +534,18 @@ public final class ServiceDispatcher { // global-commit-post-run ECA, like global-commit but gets the context after the service is run if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "global-commit-post-run", ctx, ecaContext, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "global-commit-post-run", ctx, ecaContext, result, isError, isFailure); } // check for failure and log on info level; this is used for debugging if (isFailure) { - Debug.logWarning("Service Failure [" + modelService.name + "]: " + ServiceUtil.getErrorMessage(result), MODULE); + Debug.logWarning("Service Failure [" + modelService.getName() + "]: " + ServiceUtil.getErrorMessage(result), MODULE); } } catch (Throwable t) { if (Debug.timingOn()) { - UtilTimer.closeTimer(localName + " / " + modelService.name, "Sync service failed...", MODULE); + UtilTimer.closeTimer(localName + " / " + modelService.getName(), "Sync service failed...", MODULE); } - String errMsg = "Service [" + modelService.name + "] threw an unexpected exception/error"; + String errMsg = "Service [" + modelService.getName() + "] threw an unexpected exception/error"; engine.sendCallbacks(modelService, context, t, GenericEngine.SYNC_MODE); try { TransactionUtil.rollback(beganTrans, errMsg, t); @@ -549,12 +560,12 @@ public final class ServiceDispatcher { } else if (t instanceof GenericServiceException) { throw (GenericServiceException) t; } else { - throw new GenericServiceException("Service [" + modelService.name + "] Failed" + modelService.debugInfo(), t); + throw new GenericServiceException("Service [" + modelService.getName() + "] Failed" + modelService.debugInfo(), t); } } finally { // if there was an error, rollback transaction, otherwise commit if (isError) { - String errMsg = "Error in Service [" + modelService.name + "]: " + ServiceUtil.getErrorMessage(result); + String errMsg = "Error in Service [" + modelService.getName() + "]: " + ServiceUtil.getErrorMessage(result); Debug.logError(errMsg, MODULE); // rollback the transaction @@ -569,7 +580,7 @@ public final class ServiceDispatcher { TransactionUtil.commit(beganTrans); } catch (GenericTransactionException e) { GenericDelegator.popUserIdentifier(); - String errMsg = "Could not commit transaction for service [" + modelService.name + "] call"; + String errMsg = "Could not commit transaction for service [" + modelService.getName() + "] call"; Debug.logError(e, errMsg, MODULE); if (e.getMessage() != null) { errMsg = errMsg + ": " + e.getMessage(); @@ -609,7 +620,7 @@ public final class ServiceDispatcher { // pre-return ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(modelService.name, eventMap, "return", ctx, ecaContext, result, isError, isFailure); + ServiceEcaUtil.evalRules(modelService.getName(), eventMap, "return", ctx, ecaContext, result, isError, isFailure); } rs.setEndStamp(); @@ -619,22 +630,24 @@ public final class ServiceDispatcher { long showSlowServiceThreshold = UtilProperties.getPropertyAsLong("service", "showSlowServiceThreshold", 1000); if (Debug.timingOn() && timeToRun > showServiceDurationThreshold) { - Debug.logTiming("Sync service [" + localName + "/" + modelService.name + "] finished in [" + timeToRun + "] milliseconds", MODULE); + Debug.logTiming("Sync service [" + localName + "/" + modelService.getName() + "] finished in [" + timeToRun + "] milliseconds", MODULE); } else if (Debug.infoOn() && timeToRun > showSlowServiceThreshold) { - Debug.logTiming("Slow sync service execution detected: service [" + localName + "/" + modelService.name + "] finished in [" + timeToRun + "] milliseconds", MODULE); + Debug.logTiming("Slow sync service execution detected: service [" + localName + "/" + modelService.getName() + "] finished in [" + + timeToRun + "] milliseconds", MODULE); } - if ((Debug.verboseOn() || modelService.debug) && timeToRun > 50 && !modelService.hideResultInLog) { + if ((Debug.verboseOn() || modelService.isDebug()) && timeToRun > 50 && !modelService.isHideResultInLog()) { // Sanity check - some service results can be multiple MB in size. Limit message size to 10K. String resultStr = result.toString(); if (resultStr.length() > 10240) { resultStr = resultStr.substring(0, 10226) + "...[truncated]"; } if (Debug.verboseOn()) { - Debug.logVerbose("Sync service [" + localName + "/" + modelService.name + "] finished with response [" + resultStr + "]", MODULE); + Debug.logVerbose("Sync service [" + localName + "/" + modelService.getName() + "] finished with response [" + resultStr + + "]", MODULE); } } - if (modelService.metrics != null) { - modelService.metrics.recordServiceRate(1, timeToRun); + if (modelService.getMetrics() != null) { + modelService.getMetrics().recordServiceRate(1, timeToRun); } return result; } @@ -650,14 +663,15 @@ public final class ServiceDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - public void runAsync(String localName, ModelService service, Map<String, ? extends Object> params, GenericRequester requester, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String localName, ModelService service, Map<String, ? extends Object> params, GenericRequester requester, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { if (Debug.timingOn()) { - UtilTimer.timerLog(localName + " / " + service.name, "ASync service started...", MODULE); + UtilTimer.timerLog(localName + " / " + service.getName(), "ASync service started...", MODULE); } - if (Debug.verboseOn() || service.debug) { + if (Debug.verboseOn() || service.isDebug()) { 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.getName() + " [" + service.getLocation() + + "/" + service.getInvoke() + "] (" + service.getEngineName() + ")", MODULE); } } @@ -678,7 +692,7 @@ public final class ServiceDispatcher { // setup the engine and context DispatchContext ctx = localContext.get(localName); - GenericEngine engine = this.getGenericEngine(service.engineName); + GenericEngine engine = this.getGenericEngine(service.getEngineName()); // for isolated transactions Transaction parentTransaction = null; @@ -686,20 +700,20 @@ public final class ServiceDispatcher { boolean beganTrans = false; try { - if (service.useTransaction) { + if (service.isUseTransaction()) { if (TransactionUtil.isTransactionInPlace()) { // if a new transaction is needed, do it here; if not do nothing, just use current tx - if (service.requireNewTransaction) { + if (service.isRequireNewTransaction()) { parentTransaction = TransactionUtil.suspend(); // now start a new transaction - beganTrans = TransactionUtil.begin(service.transactionTimeout); + beganTrans = TransactionUtil.begin(service.getTransactionTimeout()); } } else { - beganTrans = TransactionUtil.begin(service.transactionTimeout); + beganTrans = TransactionUtil.begin(service.getTransactionTimeout()); } // enlist for XAResource debugging if (beganTrans && TransactionUtil.debugResources()) { - DebugXaResource dxa = new DebugXaResource(service.name); + DebugXaResource dxa = new DebugXaResource(service.getName()); try { dxa.enlist(); } catch (Exception e) { @@ -710,23 +724,23 @@ public final class ServiceDispatcher { try { // get eventMap once for all calls for speed, don't do event calls if it is null - Map<String, List<ServiceEcaRule>> eventMap = ServiceEcaUtil.getServiceEventMap(service.name); + Map<String, List<ServiceEcaRule>> eventMap = ServiceEcaUtil.getServiceEventMap(service.getName()); // pre-auth ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(service.name, eventMap, "auth", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(service.getName(), eventMap, "auth", ctx, context, result, isError, isFailure); } context = checkAuth(localName, context, service); Object userLogin = context.get("userLogin"); - if (service.auth && userLogin == null) { - throw new ServiceAuthException("User authorization is required for this service: " + service.name + service.debugInfo()); + if (service.isAuth() && userLogin == null) { + throw new ServiceAuthException("User authorization is required for this service: " + service.getName() + service.debugInfo()); } // pre-validate ECA if (eventMap != null) { - ServiceEcaUtil.evalRules(service.name, eventMap, "in-validate", ctx, context, result, isError, isFailure); + ServiceEcaUtil.evalRules(service.getName(), eventMap, "in-validate", ctx, context, result, isError, isFailure); } // check for pre-validate failure/errors @@ -734,11 +748,12 @@ public final class ServiceDispatcher { isError = ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE)); // validate the context - if (service.validate && !isError && !isFailure) { + if (service.isValidate() && !isError && !isFailure) { try { service.validate(context, ModelService.IN_PARAM, locale); } catch (ServiceValidationException e) { - Debug.logError(e, "Incoming service context (in runAsync: " + service.name + ") does not match expected requirements", MODULE); + Debug.logError(e, "Incoming service context (in runAsync: " + service.getName() + + ") does not match expected requirements", MODULE); throw e; } } @@ -754,13 +769,13 @@ public final class ServiceDispatcher { } if (Debug.timingOn()) { - UtilTimer.closeTimer(localName + " / " + service.name, "ASync service finished...", MODULE); + UtilTimer.closeTimer(localName + " / " + service.getName(), "ASync service finished...", MODULE); } } catch (Throwable t) { if (Debug.timingOn()) { - UtilTimer.closeTimer(localName + " / " + service.name, "ASync service failed...", MODULE); + UtilTimer.closeTimer(localName + " / " + service.getName(), "ASync service failed...", MODULE); } - String errMsg = "Service [" + service.name + "] threw an unexpected exception/error"; + String errMsg = "Service [" + service.getName() + "] threw an unexpected exception/error"; Debug.logError(t, errMsg, MODULE); engine.sendCallbacks(service, context, t, GenericEngine.ASYNC_MODE); try { @@ -775,7 +790,7 @@ public final class ServiceDispatcher { } else if (t instanceof GenericServiceException) { throw (GenericServiceException) t; } else { - throw new GenericServiceException("Service [" + service.name + "] Failed" + service.debugInfo(), t); + throw new GenericServiceException("Service [" + service.getName() + "] Failed" + service.debugInfo(), t); } } finally { // always try to commit the transaction since we don't know in this case if its was an error or not @@ -812,7 +827,8 @@ public final class ServiceDispatcher { * @throws ServiceValidationException * @throws GenericServiceException */ - public void runAsync(String localName, ModelService service, Map<String, ? extends Object> context, boolean persist) throws ServiceAuthException, ServiceValidationException, GenericServiceException { + public void runAsync(String localName, ModelService service, Map<String, ? extends Object> context, boolean persist) + throws ServiceAuthException, ServiceValidationException, GenericServiceException { this.runAsync(localName, service, context, null, persist); } @@ -892,7 +908,8 @@ public final class ServiceDispatcher { } // checks if parameters were passed for authentication - private Map<String, Object> checkAuth(String localName, Map<String, Object> context, ModelService origService) throws ServiceAuthException, GenericServiceException { + private Map<String, Object> checkAuth(String localName, Map<String, Object> context, ModelService origService) + throws ServiceAuthException, GenericServiceException { String service = null; Locale locale = (Locale) context.get("locale"); try { @@ -904,7 +921,7 @@ public final class ServiceDispatcher { if (service == null) { throw new GenericServiceException("No Authentication Service Defined"); } - if (service.equals(origService.name)) { + if (service.equals(origService.getName())) { // manually calling the auth service, don't continue... return context; } @@ -926,9 +943,11 @@ public final class ServiceDispatcher { GenericValue userLogin = (GenericValue) context.get("userLogin"); if (userLogin != null) { - // Because of encrypted passwords we can't just pass in the encrypted version of the password from the data, so we'll do something different and not run the userLogin service... + // Because of encrypted passwords we can't just pass in the encrypted version of the password from the data, so we'll do something + // different and not run the userLogin service... - //The old way: GenericValue newUserLogin = getLoginObject(service, localName, userLogin.getString("userLoginId"), userLogin.getString("currentPassword"), (Locale) context.get("locale")); + //The old way: GenericValue newUserLogin = getLoginObject(service, localName, userLogin.getString("userLoginId"), + // userLogin.getString("currentPassword"), (Locale) context.get("locale")); GenericValue newUserLogin = null; try { newUserLogin = this.getDelegator().findOne("UserLogin", true, "userLoginId", userLogin.get("userLoginId")); @@ -940,11 +959,15 @@ public final class ServiceDispatcher { if (newUserLogin == null) { // uh oh, couldn't validate that one... // we'll have to remove it from the incoming context which will cause an auth error later if auth is required - Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record not found.", MODULE); + Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record not found.", + MODULE); context.remove("userLogin"); - } else if (newUserLogin.getString("currentPassword") != null && !newUserLogin.getString("currentPassword").equals(userLogin.getString("currentPassword"))) { + } else if (newUserLogin.getString("currentPassword") != null && !newUserLogin.getString("currentPassword") + .equals(userLogin.getString("currentPassword"))) { // passwords didn't match, remove the userLogin for failed auth - Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record currentPassword fields did not match; note that the UserLogin object passed into a service may need to have the currentPassword encrypted.", MODULE); + Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record" + + "currentPassword fields did not match; note that the UserLogin object passed into a service may need to have the" + + "currentPassword encrypted.", MODULE); context.remove("userLogin"); } } @@ -953,7 +976,7 @@ public final class ServiceDispatcher { // evaluate permissions for the service or throw exception if fail. DispatchContext dctx = this.getLocalContext(localName); Map<String, Object> permResp = null; - if (origService.modelPermission != null) { + if (origService.getModelPermission() != null) { permResp = origService.evalPermission(dctx, context); if (ServiceUtil.isSuccess(permResp)) { //Ok the service have authorization to run, complete the context with the permission response map @@ -964,14 +987,16 @@ public final class ServiceDispatcher { } if (ServiceUtil.isFailure(permResp) || ServiceUtil.isError(permResp)) { throw new ServiceAuthException(UtilProperties.getMessage("ServiceErrorUiLabels", "ServicePermissionError", - UtilMisc.toMap("serviceName", origService.name, "failMessage", ServiceUtil.getErrorMessage(permResp)), locale)); + UtilMisc.toMap("serviceName", origService.getName(), "failMessage", ServiceUtil.getErrorMessage(permResp)), locale)); } return origService.makeValid(context, ModelService.IN_PARAM); } // gets a value object from name/password pair - private GenericValue getLoginObject(String service, String localName, String username, String password, String jwtToken, Locale locale) throws GenericServiceException { - Map<String, Object> context = UtilMisc.toMap("login.username", username, "login.password", password, "login.token", jwtToken, "isServiceAuth", true, "locale", locale); + private GenericValue getLoginObject(String service, String localName, String username, String password, String jwtToken, Locale locale) + throws GenericServiceException { + Map<String, Object> context = UtilMisc.toMap("login.username", username, "login.password", password, "login.token", jwtToken, + "isServiceAuth", true, "locale", locale); if (Debug.verboseOn()) { Debug.logVerbose("[ServiceDispathcer.authenticate] : Invoking UserLogin Service", MODULE); @@ -982,7 +1007,7 @@ public final class ServiceDispatcher { ModelService model = dctx.getModelService(service); // get the service engine - GenericEngine engine = getGenericEngine(model.engineName); + GenericEngine engine = getGenericEngine(model.getEngineName()); // invoke the service and get the UserLogin value object Map<String, Object> result = engine.runSync(localName, model, context); @@ -1050,7 +1075,7 @@ public final class ServiceDispatcher { private RunningService logService(String localName, ModelService modelService, int mode) { // set up the running service log RunningService rs = new RunningService(localName, modelService, mode); - runLog.put(rs, this); + RUN_LOG.put(rs, this); return rs; } @@ -1082,7 +1107,7 @@ public final class ServiceDispatcher { } public static Map<RunningService, ServiceDispatcher> getServiceLogMap() { - return runLog; + return RUN_LOG; } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceSynchronization.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceSynchronization.java index 9194c4c..bc2135b 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceSynchronization.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceSynchronization.java @@ -50,12 +50,14 @@ public class ServiceSynchronization implements Synchronization { private static Map<Transaction, ServiceSynchronization> syncingleton = new WeakHashMap<>(); private List<ServiceExecution> services = new ArrayList<>(); - public static void registerCommitService(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, boolean async, boolean persist) throws GenericServiceException { + public static void registerCommitService(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, + boolean async, boolean persist) throws GenericServiceException { ServiceSynchronization sync = ServiceSynchronization.getInstance(); sync.services.add(new ServiceExecution(dctx, serviceName, runAsUser, context, async, persist, false)); } - public static void registerRollbackService(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, boolean async, boolean persist) throws GenericServiceException { + public static void registerRollbackService(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, + boolean async, boolean persist) throws GenericServiceException { ServiceSynchronization sync = ServiceSynchronization.getInstance(); sync.services.add(new ServiceExecution(dctx, serviceName, runAsUser, context, async, persist, true)); } @@ -81,17 +83,20 @@ public class ServiceSynchronization implements Synchronization { @Override public void afterCompletion(int status) { long start = System.currentTimeMillis(); - if (Debug.verboseOn()) + if (Debug.verboseOn()) { Debug.logVerbose("Running " + this.services.size() + " services on commit/rollback", MODULE); + } for (ServiceExecution serviceExec : this.services) { serviceExec.runService(status); - if (Debug.verboseOn()) + if (Debug.verboseOn()) { Debug.logVerbose("Completed service [" + serviceExec.serviceName + "] async [" + serviceExec.async + "] persisted [" + serviceExec.persist + "]", MODULE); + } } - if (Debug.verboseOn()) + if (Debug.verboseOn()) { Debug.logVerbose("Commit/rollback services complete in " - + (System.currentTimeMillis() - start) + "ms", MODULE); + + (System.currentTimeMillis() - start) + "ms", MODULE); + } } @Override @@ -100,15 +105,16 @@ public class ServiceSynchronization implements Synchronization { } static class ServiceExecution { - protected DispatchContext dctx = null; - protected String serviceName; - protected String runAsUser = null; - protected Map<String, ? extends Object> context = null; - protected boolean rollback = false; - protected boolean persist = true; - protected boolean async = false; - - ServiceExecution(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, boolean async, boolean persist, boolean rollback) { + private DispatchContext dctx = null; + private String serviceName; + private String runAsUser = null; + private Map<String, ? extends Object> context = null; + private boolean rollback = false; + private boolean persist = true; + private boolean async = false; + + ServiceExecution(DispatchContext dctx, String serviceName, String runAsUser, Map<String, ? extends Object> context, boolean async, + boolean persist, boolean rollback) { this.dctx = dctx; this.serviceName = serviceName; this.runAsUser = runAsUser; @@ -139,7 +145,7 @@ public class ServiceSynchronization implements Synchronization { // obtain the model and get the valid context ModelService model = dctx.getModelService(serviceName); Map<String, Object> thisContext; - if (model.validate) { + if (model.isValidate()) { thisContext = model.makeValid(context, ModelService.IN_PARAM); } else { thisContext = new HashMap<>(); @@ -174,12 +180,10 @@ public class ServiceSynchronization implements Synchronization { } catch (GenericTransactionException e) { Debug.logError(e, MODULE); } - } }; thread.start(); } } } - } 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 e26841b..704da49 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 @@ -465,7 +465,7 @@ public final class ServiceUtil { } outMap.putAll(modelService.makeValid(fromMap, ModelService.IN_PARAM, true, null, timeZone, locale)); - if (userLogin != null && modelService.auth) { + if (userLogin != null && modelService.isAuth()) { outMap.put("userLogin", userLogin); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceValidationException.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceValidationException.java index 2d9dfe1..ea9c8e8 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceValidationException.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceValidationException.java @@ -29,11 +29,11 @@ import org.apache.ofbiz.base.util.UtilValidate; @SuppressWarnings("serial") public class ServiceValidationException extends GenericServiceException { - protected List<String> messages = new ArrayList<>(); - protected List<String> missingFields = new ArrayList<>(); - protected List<String> extraFields = new ArrayList<>(); - protected String errorMode = null; - protected ModelService service = null; + private List<String> messages = new ArrayList<>(); + private List<String> missingFields = new ArrayList<>(); + private List<String> extraFields = new ArrayList<>(); + private String errorMode = null; + private ModelService service = null; public ServiceValidationException(ModelService service, List<String> missingFields, List<String> extraFields, String errorMode) { super(); @@ -98,10 +98,18 @@ public class ServiceValidationException extends GenericServiceException { this(messages, service, null, null, errorMode); } + /** + * Gets extra fields. + * @return the extra fields + */ public List<String> getExtraFields() { return extraFields; } + /** + * Gets missing fields. + * @return the missing fields + */ public List<String> getMissingFields() { return missingFields; } @@ -114,17 +122,29 @@ public class ServiceValidationException extends GenericServiceException { return this.messages; } + /** + * Gets model service. + * @return the model service + */ public ModelService getModelService() { return service; } + /** + * Gets mode. + * @return the mode + */ public String getMode() { return errorMode; } + /** + * Gets service name. + * @return the service name + */ public String getServiceName() { if (service != null) { - return service.name; + return service.getName(); } return null; } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceXaWrapper.java b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceXaWrapper.java index 69c4514..2167f5b 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/ServiceXaWrapper.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/ServiceXaWrapper.java @@ -304,7 +304,7 @@ public class ServiceXaWrapper extends GenericXaResource { // obtain the model and get the valid context ModelService model = dctx.getModelService(service); Map<String, Object> thisContext; - if (model.validate) { + if (model.isValidate()) { thisContext = model.makeValid(context, ModelService.IN_PARAM); } else { thisContext = new HashMap<>(); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressions.java b/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressions.java index 330e3c4..7378b79 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressions.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/calendar/TemporalExpressions.java @@ -172,7 +172,6 @@ public class TemporalExpressions implements Serializable { /** * Align day of week calendar. - * * @param cal the cal * @return the calendar */ @@ -781,7 +780,6 @@ public class TemporalExpressions implements Serializable { /** * Prepare cal calendar. - * * @param cal the cal * @return the calendar */ @@ -902,7 +900,6 @@ public class TemporalExpressions implements Serializable { /** * Gets hour range as set. - * * @return the hour range as set */ public Set<Integer> getHourRangeAsSet() { @@ -1193,7 +1190,6 @@ public class TemporalExpressions implements Serializable { /** * Gets minute range as set. - * * @return the minute range as set */ public Set<Integer> getMinuteRangeAsSet() { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceEngine.java index f02ef41..392e057 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceEngine.java @@ -88,10 +88,10 @@ public final class ServiceEngine { List<ServiceLocation> serviceLocations = new ArrayList<>(serviceLocationElementList.size()); for (Element serviceLocationElement : serviceLocationElementList) { String location = serviceLocationElement.getAttribute("location").intern(); - if (location.contains("localhost") && Start.getInstance().getConfig().portOffset != 0) { + if (location.contains("localhost") && Start.getInstance().getConfig().getPortOffset() != 0) { String s = location.substring(location.lastIndexOf(":") + 1); Integer locationPort = Integer.valueOf(s.substring(0, s.indexOf("/"))); - Integer port = locationPort + Start.getInstance().getConfig().portOffset; + Integer port = locationPort + Start.getInstance().getConfig().getPortOffset(); location = location.replace(locationPort.toString(), port.toString()); } serviceLocations.add(new ServiceLocation(serviceLocationElement, location)); diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/AbstractEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/AbstractEngine.java index e768817..9fb182a 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/AbstractEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/AbstractEngine.java @@ -38,9 +38,17 @@ public abstract class AbstractEngine implements GenericEngine { private static final String MODULE = AbstractEngine.class.getName(); /** Map containing aliases for service implementation locations. */ - protected static final Map<String, String> locationMap = createLocationMap(); + private static final Map<String, String> LOCATION_MAP = createLocationMap(); - protected ServiceDispatcher dispatcher; + /** + * Gets dispatcher. + * @return the dispatcher + */ + public ServiceDispatcher getDispatcher() { + return dispatcher; + } + + private ServiceDispatcher dispatcher; protected AbstractEngine(ServiceDispatcher dispatcher) { this.dispatcher = dispatcher; @@ -72,14 +80,14 @@ public abstract class AbstractEngine implements GenericEngine { * @return the actual location where to find the service implementation */ protected String getLocation(ModelService model) { - return locationMap.getOrDefault(model.location, model.location); + return LOCATION_MAP.getOrDefault(model.getLocation(), model.getLocation()); } @Override public void sendCallbacks(ModelService model, Map<String, Object> context, int mode) throws GenericServiceException { if (allowCallbacks(model, context, mode)) { - dispatcher.getCallbacks(model.name).forEach(gsc -> gsc.receiveEvent(context)); + dispatcher.getCallbacks(model.getName()).forEach(gsc -> gsc.receiveEvent(context)); } } @@ -87,7 +95,7 @@ public abstract class AbstractEngine implements GenericEngine { public void sendCallbacks(ModelService model, Map<String, Object> context, Throwable t, int mode) throws GenericServiceException { if (allowCallbacks(model, context, mode)) { - dispatcher.getCallbacks(model.name).forEach(gsc -> gsc.receiveEvent(context, t)); + dispatcher.getCallbacks(model.getName()).forEach(gsc -> gsc.receiveEvent(context, t)); } } @@ -95,7 +103,7 @@ public abstract class AbstractEngine implements GenericEngine { public void sendCallbacks(ModelService model, Map<String, Object> context, Map<String, Object> result, int mode) throws GenericServiceException { if (allowCallbacks(model, context, mode)) { - dispatcher.getCallbacks(model.name).forEach(gsc -> gsc.receiveEvent(context, result)); + dispatcher.getCallbacks(model.getName()).forEach(gsc -> gsc.receiveEvent(context, result)); } } 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 ce3bab0..b403fe0 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 @@ -71,22 +71,25 @@ public final class EntityAutoEngine extends GenericAsyncEngine { @Override public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> parameters) throws GenericServiceException { // static java service methods should be: public Map<String, Object> methodName(DispatchContext dctx, Map<String, Object> context) - DispatchContext dctx = dispatcher.getLocalContext(localName); + DispatchContext dctx = getDispatcher().getLocalContext(localName); Locale locale = (Locale) parameters.get("locale"); Map<String, Object> result = ServiceUtil.returnSuccess(); // check the package and method names - if (modelService.invoke == null || !availableInvokeActionNames.contains(modelService.invoke)) { - throw new GenericServiceException("In Service [" + modelService.name + "] the invoke value must be create, update, or delete for entity-auto engine"); + if (modelService.getInvoke() == null || !availableInvokeActionNames.contains(modelService.getInvoke())) { + throw new GenericServiceException("In Service [" + modelService.getName() + + "] the invoke value must be create, update, or delete for entity-auto engine"); } - if (UtilValidate.isEmpty(modelService.defaultEntityName)) { - throw new GenericServiceException("In Service [" + modelService.name + "] you must specify a default-entity-name for entity-auto engine"); + if (UtilValidate.isEmpty(modelService.getDefaultEntityName())) { + throw new GenericServiceException("In Service [" + modelService.getName() + + "] you must specify a default-entity-name for entity-auto engine"); } - ModelEntity modelEntity = dctx.getDelegator().getModelEntity(modelService.defaultEntityName); + ModelEntity modelEntity = dctx.getDelegator().getModelEntity(modelService.getDefaultEntityName()); if (modelEntity == null) { - throw new GenericServiceException("In Service [" + modelService.name + "] the specified default-entity-name [" + modelService.defaultEntityName + "] is not valid"); + throw new GenericServiceException("In Service [" + modelService.getName() + "] the specified default-entity-name [" + + modelService.getDefaultEntityName() + "] is not valid"); } try { @@ -110,7 +113,7 @@ public final class EntityAutoEngine extends GenericAsyncEngine { } } - switch (modelService.invoke) { + switch (modelService.getInvoke()) { case "create": result = invokeCreate(dctx, parameters, modelService, modelEntity, allPksInOnly, pkFieldNameOutOnly); break; @@ -135,14 +138,18 @@ public final class EntityAutoEngine extends GenericAsyncEngine { result.putAll(modelService.makeValid(crudValue, ModelService.OUT_PARAM)); } } catch (GeneralException e) { - Debug.logError(e, "Error doing entity-auto operation for entity [" + modelEntity.getEntityName() + "] in service [" + modelService.name + "]: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceEntityAutoOperation", UtilMisc.toMap("entityName", modelEntity.getEntityName(), "serviceName", modelService.name, "errorString", e.toString()), locale)); + Debug.logError(e, "Error doing entity-auto operation for entity [" + modelEntity.getEntityName() + "] in service [" + + modelService.getName() + "]: " + e.toString(), MODULE); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceEntityAutoOperation", + UtilMisc.toMap("entityName", modelEntity.getEntityName(), "serviceName", modelService.getName(), "errorString", + e.toString()), locale)); } result.put(ModelService.SUCCESS_MESSAGE, ServiceUtil.makeSuccessMessage(result, "", "", "", "")); return result; } - private static Map<String, Object> invokeCreate(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, ModelEntity modelEntity, boolean allPksInOnly, List<String> pkFieldNameOutOnly) + private static Map<String, Object> invokeCreate(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, + ModelEntity modelEntity, boolean allPksInOnly, List<String> pkFieldNameOutOnly) throws GeneralException { Locale locale = (Locale) parameters.get("locale"); @@ -173,7 +180,7 @@ public final class EntityAutoEngine extends GenericAsyncEngine { doublePkPrimaryInParam = secondPkParam; doublePkSecondaryOutParam = firstPkParam; doublePkSecondaryOutField = firstPkField; - } else { + //} else { // we don't have an IN and an OUT... so do nothing and leave them null } } @@ -215,7 +222,7 @@ public final class EntityAutoEngine extends GenericAsyncEngine { * */ - Object pkValue = parameters.get(singlePkModelParam.name); + Object pkValue = parameters.get(singlePkModelParam.getName()); if (UtilValidate.isEmpty(pkValue)) { pkValue = dctx.getDelegator().getNextSeqId(modelEntity.getEntityName()); } else { @@ -224,14 +231,16 @@ public final class EntityAutoEngine extends GenericAsyncEngine { if (pkValue instanceof String) { StringBuffer errorDetails = new StringBuffer(); if (!UtilValidate.isValidDatabaseId((String) pkValue, errorDetails)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceParameterValueNotValid", UtilMisc.toMap("parameterName", singlePkModelParam.name, "errorDetails", errorDetails), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceParameterValueNotValid", + UtilMisc.toMap("parameterName", singlePkModelParam.getName(), "errorDetails", errorDetails), locale)); } } } newEntity.set(singlePkModeField.getName(), pkValue); GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null); if (lookedUpValue != null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceValueFound", UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceValueFound", + UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale)); } } else if (isDoublePk && doublePkPrimaryInParam != null && doublePkSecondaryOutParam != null) { /* @@ -266,7 +275,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { //with all pks present on parameters, check if the entity is not already exists. GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null); if (lookedUpValue != null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceValueFound", UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceValueFound", + UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale)); } } else { /* We haven't all Pk and their are 3 or more, now check if isn't a associate entity with own sequence @@ -283,7 +293,8 @@ 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: " + throw new GenericServiceException("In Service [" + modelService.getName() + + "] 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, " @@ -293,7 +304,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { } } - // handle the case where there is a fromDate in the pk of the entity, and it is optional or undefined in the service def, populate automatically + // handle the case where there is a fromDate in the pk of the entity, and it is optional or undefined in the service def, + // populate automatically ModelField fromDateField = modelEntity.getField("fromDate"); if (fromDateField != null && fromDateField.getIsPk()) { ModelParam fromDateParam = modelService.getParam("fromDate"); @@ -328,7 +340,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { if (userLogin != null) { newEntity.set("changeByUserLoginId", userLogin.get("userLoginId")); } else { - throw new GenericServiceException("You call a creation on entity that require the userLogin to track the activity, please controle that your service definition has auth='true'"); + throw new GenericServiceException("You call a creation on entity that require the userLogin to track the activity," + + " please control that your service definition has auth='true'"); } //Oh changeByUserLoginId detected, check if an EntityStatus concept @@ -356,12 +369,14 @@ public final class EntityAutoEngine extends GenericAsyncEngine { } } newEntity.create(); - Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityCreatedSuccessfully", UtilMisc.toMap("label", modelEntity.getTitle()), locale)); + Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityCreatedSuccessfully", + UtilMisc.toMap("label", modelEntity.getTitle()), locale)); result.put("crudValue", newEntity); return result; } - private static Map<String, Object> invokeUpdate(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, ModelEntity modelEntity, boolean allPksInOnly) + private static Map<String, Object> invokeUpdate(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, + ModelEntity modelEntity, boolean allPksInOnly) throws GeneralException { Locale locale = (Locale) parameters.get("locale"); Map<String, Object> localContext = new HashMap<>(); @@ -376,7 +391,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { // check to make sure that all primary key fields are defined as IN attributes if (!allPksInOnly) { - throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the update invoke option not all pk fields have the mode IN"); + throw new GenericServiceException("In Service [" + modelService.getName() + "] which uses the entity-auto engine with the update" + + " invoke option not all pk fields have the mode IN"); } GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null); @@ -431,10 +447,12 @@ public final class EntityAutoEngine extends GenericAsyncEngine { String lookedUpStatusId = (String) lookedUpValue.get(statusField); if (UtilValidate.isNotEmpty(lookedUpStatusId) && !statusIdParamValue.equals(lookedUpStatusId)) { // there was an old status, and in this call we are trying to change it, so do the StatusValidChange check - GenericValue statusValidChange = dctx.getDelegator().findOne("StatusValidChange", true, "statusId", lookedUpStatusId, "statusIdTo", statusIdParamValue); + GenericValue statusValidChange = dctx.getDelegator().findOne("StatusValidChange", true, "statusId", + lookedUpStatusId, "statusIdTo", statusIdParamValue); if (statusValidChange == null) { // uh-oh, no valid change... - return ServiceUtil.returnError(UtilProperties.getMessage("CommonUiLabels", "CommonErrorNoStatusValidChange", localContext, locale)); + return ServiceUtil.returnError(UtilProperties.getMessage("CommonUiLabels", "CommonErrorNoStatusValidChange", + localContext, locale)); } } } @@ -465,23 +483,27 @@ public final class EntityAutoEngine extends GenericAsyncEngine { if (modelEntity.getField("changeByUserLoginId") != null) { if (modelEntity.getEntityName().endsWith("Status")) { //Oh update on EntityStatus concept detected ... not possible, return invalid request - throw new GenericServiceException("You call a updating operation on entity that track the activity, sorry I can't do that, please amazing developer check your service definition;)"); + throw new GenericServiceException("You call a updating operation on entity that track the activity, sorry I can't do that," + + "please amazing developer check your service definition;)"); } GenericValue userLogin = (GenericValue) parameters.get("userLogin"); if (userLogin != null) { lookedUpValue.set("changeByUserLoginId", userLogin.get("userLoginId")); } else { - throw new GenericServiceException("You call a updating operation on entity that track the activity, sorry I can't do that, please amazing developer check your service definition;)"); + throw new GenericServiceException("You call a updating operation on entity that track the activity, sorry I can't do that," + + "please amazing developer check your service definition;)"); } } lookedUpValue.store(); result.put("crudValue", lookedUpValue); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage("ServiceUiLabels", "EntityUpdatedSuccessfully", UtilMisc.toMap("label", modelEntity.getTitle()), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage("ServiceUiLabels", "EntityUpdatedSuccessfully", + UtilMisc.toMap("label", modelEntity.getTitle()), locale)); return result; } - private static Map<String, Object> invokeDelete(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, ModelEntity modelEntity, boolean allPksInOnly) + private static Map<String, Object> invokeDelete(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, + ModelEntity modelEntity, boolean allPksInOnly) throws GeneralException { Locale locale = (Locale) parameters.get("locale"); /* @@ -492,13 +514,15 @@ public final class EntityAutoEngine extends GenericAsyncEngine { // check to make sure that all primary key fields are defined as IN attributes if (!allPksInOnly) { - throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the delete invoke option not all pk fields have the mode IN"); + throw new GenericServiceException("In Service [" + modelService.getName() + "] which uses the entity-auto engine with the delete" + + "invoke option not all pk fields have the mode IN"); } if (modelEntity.getField("changeByUserLoginId") != null) { if (modelEntity.getEntityName().endsWith("Status")) { //Oh update on EntityStatus concept detected ... not possible, return invalid request - throw new GenericServiceException("You call a deleting operation on entity that track the activity, sorry I can't do that, please amazing developer check your service definition;)"); + throw new GenericServiceException("You call a deleting operation on entity that track the activity, sorry I can't do that," + + "please amazing developer check your service definition;)"); } } @@ -507,7 +531,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ServiceValueNotFoundForRemove", locale)); } lookedUpValue.remove(); - Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityDeletedSuccessfully", UtilMisc.toMap("label", modelEntity.getTitle()), locale)); + Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityDeletedSuccessfully", + UtilMisc.toMap("label", modelEntity.getTitle()), locale)); return result; } @@ -517,12 +542,12 @@ public final class EntityAutoEngine extends GenericAsyncEngine { * @param parameters * @param modelService * @param modelEntity - * @param lookedUpValue * @param allPksInOnly * @return * @throws GeneralException */ - private static Map<String, Object> invokeExpire(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, ModelEntity modelEntity, boolean allPksInOnly) + private static Map<String, Object> invokeExpire(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, + ModelEntity modelEntity, boolean allPksInOnly) throws GeneralException { Locale locale = (Locale) parameters.get("locale"); List<String> fieldThruDates = new LinkedList<>(); @@ -531,7 +556,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { // check to make sure that all primary key fields are defined as IN attributes if (!allPksInOnly) { - throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the update invoke option not all pk fields have the mode IN"); + throw new GenericServiceException("In Service [" + modelService.getName() + "] which uses the entity-auto engine with the update" + + "invoke option not all pk fields have the mode IN"); } GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null); if (lookedUpValue == null) { @@ -581,7 +607,8 @@ public final class EntityAutoEngine extends GenericAsyncEngine { if (Debug.infoOn()) { Debug.logInfo(" parameters OUT : " + parameters, MODULE); } - Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityExpiredSuccessfully", UtilMisc.toMap("label", modelEntity.getTitle()), locale)); + Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityExpiredSuccessfully", + UtilMisc.toMap("label", modelEntity.getTitle()), locale)); return result; } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericAsyncEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericAsyncEngine.java index dbec976..d447995 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericAsyncEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GenericAsyncEngine.java @@ -55,7 +55,8 @@ public abstract class GenericAsyncEngine extends AbstractEngine { } @Override - public abstract Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; + public abstract Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) + throws GenericServiceException; @Override public abstract void runSyncIgnore(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException; @@ -66,13 +67,14 @@ public abstract class GenericAsyncEngine extends AbstractEngine { } @Override - public void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) throws GenericServiceException { - DispatchContext dctx = dispatcher.getLocalContext(localName); + public void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) + throws GenericServiceException { + DispatchContext dctx = getDispatcher().getLocalContext(localName); Job job = null; if (persist) { // check for a delegator - if (dispatcher.getDelegator() == null) { + if (getDispatcher().getDelegator() == null) { throw new GenericServiceException("No reference to delegator; cannot run persisted services."); } @@ -80,9 +82,9 @@ public abstract class GenericAsyncEngine extends AbstractEngine { // Build the value object(s). try { // Create the runtime data - String dataId = dispatcher.getDelegator().getNextSeqId("RuntimeData"); + String dataId = getDispatcher().getDelegator().getNextSeqId("RuntimeData"); - GenericValue runtimeData = dispatcher.getDelegator().makeValue("RuntimeData", "runtimeDataId", dataId); + GenericValue runtimeData = getDispatcher().getDelegator().makeValue("RuntimeData", "runtimeDataId", dataId); runtimeData.set("runtimeInfo", XmlSerializer.serialize(context)); runtimeData.create(); @@ -95,22 +97,22 @@ public abstract class GenericAsyncEngine extends AbstractEngine { } // Create the job info - String jobId = dispatcher.getDelegator().getNextSeqId("JobSandbox"); + String jobId = getDispatcher().getDelegator().getNextSeqId("JobSandbox"); String jobName = Long.toString(System.currentTimeMillis()); Map<String, Object> jFields = UtilMisc.toMap("jobId", jobId, "jobName", jobName, "runTime", UtilDateTime.nowTimestamp()); jFields.put("poolId", ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool()); jFields.put("statusId", "SERVICE_PENDING"); - jFields.put("serviceName", modelService.name); + jFields.put("serviceName", modelService.getName()); jFields.put("loaderName", localName); - jFields.put("maxRetry", (long) modelService.maxRetry); + jFields.put("maxRetry", (long) modelService.getMaxRetry()); jFields.put("runtimeDataId", dataId); jFields.put("priority", JobPriority.NORMAL); if (UtilValidate.isNotEmpty(authUserLoginId)) { jFields.put("authUserLoginId", authUserLoginId); } - jobV = dispatcher.getDelegator().makeValue("JobSandbox", jFields); + jobV = getDispatcher().getDelegator().makeValue("JobSandbox", jFields); jobV.create(); } catch (GenericEntityException e) { throw new GenericServiceException("Unable to create persisted job", e); @@ -122,13 +124,13 @@ public abstract class GenericAsyncEngine extends AbstractEngine { Debug.logInfo("Persisted job queued : " + jobV.getString("jobName"), MODULE); } else { - JobManager jMgr = dispatcher.getJobManager(); + JobManager jMgr = getDispatcher().getJobManager(); if (jMgr != null) { String name = Long.toString(System.currentTimeMillis()); - String jobId = modelService.name + "." + name; - job = new GenericServiceJob(dctx, jobId, name, modelService.name, context, requester); + String jobId = modelService.getName() + "." + name; + job = new GenericServiceJob(dctx, jobId, name, modelService.getName(), context, requester); try { - dispatcher.getJobManager().runJob(job); + getDispatcher().getJobManager().runJob(job); } catch (JobManagerException jse) { throw new GenericServiceException("Cannot run job.", jse); } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GroovyEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GroovyEngine.java index 2b0124a..a3d6be3 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/GroovyEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/GroovyEngine.java @@ -49,7 +49,7 @@ public final class GroovyEngine extends GenericAsyncEngine { private static final String MODULE = GroovyEngine.class.getName(); private static final Object[] EMPTY_ARGS = {}; - private static final Set<String> protectedKeys = createProtectedKeys(); + private static final Set<String> PROTECTED_KEYS = createProtectedKeys(); private static Set<String> createProtectedKeys() { Set<String> newSet = new HashSet<>(); @@ -78,7 +78,7 @@ public final class GroovyEngine extends GenericAsyncEngine { @Override public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { - if (UtilValidate.isEmpty(modelService.location)) { + if (UtilValidate.isEmpty(modelService.getLocation())) { throw new GenericServiceException("Cannot run Groovy service with empty location"); } Map<String, Object> params = new HashMap<>(); @@ -88,13 +88,13 @@ public final class GroovyEngine extends GenericAsyncEngine { gContext.putAll(context); gContext.put(ScriptUtil.PARAMETERS_KEY, params); - DispatchContext dctx = dispatcher.getLocalContext(localName); + DispatchContext dctx = getDispatcher().getLocalContext(localName); gContext.put("dctx", dctx); gContext.put("security", dctx.getSecurity()); gContext.put("dispatcher", dctx.getDispatcher()); - gContext.put("delegator", dispatcher.getDelegator()); + gContext.put("delegator", getDispatcher().getDelegator()); try { - ScriptContext scriptContext = ScriptUtil.createScriptContext(gContext, protectedKeys); + ScriptContext scriptContext = ScriptUtil.createScriptContext(gContext, PROTECTED_KEYS); ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY); if (scriptHelper != null) { gContext.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper); @@ -105,9 +105,9 @@ public final class GroovyEngine extends GenericAsyncEngine { GroovyUtil.getBinding(gContext)); // Groovy services can either be implemented as a stand-alone script or with a method inside a script. - Object resultObj = UtilValidate.isEmpty(modelService.invoke) + Object resultObj = UtilValidate.isEmpty(modelService.getInvoke()) ? script.run() - : script.invokeMethod(modelService.invoke, EMPTY_ARGS); + : script.invokeMethod(modelService.getInvoke(), EMPTY_ARGS); if (resultObj == null) { resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY); @@ -126,8 +126,8 @@ public final class GroovyEngine extends GenericAsyncEngine { // detailMessage can be null. If it is null, the exception won't be properly returned and logged, // and that will make spotting problems very difficult. // Disabling this for now in favor of returning a proper exception. - throw new GenericServiceException("Error running Groovy method [" + modelService.invoke + "]" - + " in Groovy file [" + modelService.location + "]: ", e); + throw new GenericServiceException("Error running Groovy method [" + modelService.getInvoke() + "]" + + " in Groovy file [" + modelService.getLocation() + "]: ", e); } } } diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/HttpEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/HttpEngine.java index ce7a5ea..0f92efb 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/HttpEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/HttpEngine.java @@ -44,7 +44,7 @@ import org.apache.ofbiz.service.ServiceDispatcher; public class HttpEngine extends GenericAsyncEngine { private static final String MODULE = HttpEngine.class.getName(); - private static final boolean exportAll = false; + private static final boolean EXPORT_ALL = false; public HttpEngine(ServiceDispatcher dispatcher) { super(dispatcher); @@ -55,7 +55,7 @@ public class HttpEngine extends GenericAsyncEngine { */ @Override public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { - DispatchContext dctx = dispatcher.getLocalContext(localName); + DispatchContext dctx = getDispatcher().getLocalContext(localName); String xmlContext = null; try { @@ -68,7 +68,7 @@ public class HttpEngine extends GenericAsyncEngine { } Map<String, Object> parameters = new HashMap<>(); - parameters.put("serviceName", modelService.invoke); + parameters.put("serviceName", modelService.getInvoke()); if (xmlContext != null) { parameters.put("serviceContext", xmlContext); } @@ -151,7 +151,7 @@ public class HttpEngine extends GenericAsyncEngine { if (!result.containsKey(ModelService.ERROR_MESSAGE)) { try { ModelService model = dispatcher.getDispatchContext().getModelService(serviceName); - if (model.export || exportAll) { + if (model.isExport() || EXPORT_ALL) { if ("ASYNC".equals(serviceMode)) { dispatcher.runAsync(serviceName, context); } else { diff --git a/framework/service/src/main/java/org/apache/ofbiz/service/engine/SOAPClientEngine.java b/framework/service/src/main/java/org/apache/ofbiz/service/engine/SOAPClientEngine.java index 8747f1f..ab5e5d1 100644 --- a/framework/service/src/main/java/org/apache/ofbiz/service/engine/SOAPClientEngine.java +++ b/framework/service/src/main/java/org/apache/ofbiz/service/engine/SOAPClientEngine.java @@ -81,8 +81,8 @@ public final class SOAPClientEngine extends GenericAsyncEngine { // Invoke the remote SOAP service private Map<String, Object> serviceInvoker(ModelService modelService, Map<String, Object> context) throws GenericServiceException { - Delegator delegator = dispatcher.getDelegator(); - if (modelService.location == null || modelService.invoke == null) { + Delegator delegator = getDispatcher().getDelegator(); + if (modelService.getLocation() == null || modelService.getInvoke() == null) { throw new GenericServiceException("Cannot locate service to invoke"); } @@ -94,7 +94,8 @@ public final class SOAPClientEngine extends GenericAsyncEngine { String axis2XmlFileLocation = System.getProperty("ofbiz.home") + axis2XmlFile; try { - ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2RepoLocation, axis2XmlFileLocation); + ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2RepoLocation, + axis2XmlFileLocation); client = new ServiceClient(configContext, null); Options options = new Options(); EndpointReference endPoint = new EndpointReference(this.getLocation(modelService)); @@ -110,10 +111,10 @@ public final class SOAPClientEngine extends GenericAsyncEngine { Debug.logInfo("[SOAPClientEngine.invoke] : Parameter length - " + inModelParamList.size(), MODULE); } - if (UtilValidate.isNotEmpty(modelService.nameSpace)) { - serviceName = new QName(modelService.nameSpace, modelService.invoke); + if (UtilValidate.isNotEmpty(modelService.getNameSpace())) { + serviceName = new QName(modelService.getNameSpace(), modelService.getInvoke()); } else { - serviceName = new QName(modelService.invoke); + serviceName = new QName(modelService.getInvoke()); } int i = 0; @@ -121,12 +122,12 @@ public final class SOAPClientEngine extends GenericAsyncEngine { Map<String, Object> parameterMap = new HashMap<>(); for (ModelParam p: inModelParamList) { if (Debug.infoOn()) { ... 9100 lines suppressed ... |
Free forum by Nabble | Edit this page |