You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ofbiz.apache.org by de...@apache.org on 2026/06/16 04:43:10 UTC
(ofbiz-framework) branch trunk updated: Improved: Move REST-API plugin into framework OFBIZ-13415 (#1325)
This is an automated email from the ASF dual-hosted git repository.
dixitdeepak 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 33ccd74f29 Improved: Move REST-API plugin into framework OFBIZ-13415 (#1325)
33ccd74f29 is described below
commit 33ccd74f29f1226f925fb5b5e638d683befdeed3
Author: Lukas-Finster <lu...@ecomify.de>
AuthorDate: Tue Jun 16 06:43:05 2026 +0200
Improved: Move REST-API plugin into framework OFBIZ-13415 (#1325)
Moves the rest-api plugin into the ofbiz-framework repository while
preserving commit history.
Thanks: Deepak Dixit and Ashish Vijaywargiya
---------
Signed-off-by: dependabot[bot] <su...@github.com>
Co-authored-by: Michael Brohl <mi...@ecomify.de>
Co-authored-by: Girish Vasmatkar <gi...@hotwaxsystems.com>
Co-authored-by: Jacques Le Roux <ja...@les7arts.com>
Co-authored-by: cgaetan <ga...@nereide.fr>
Co-authored-by: ArashPreet <66...@users.noreply.github.com>
Co-authored-by: ArashPreet Singh <ar...@insonix.com>
Co-authored-by: Jacopo Cappellato <ja...@gmail.com>
Co-authored-by: Deepak Dixit <de...@apache.org>
Co-authored-by: Deepak Dixit <de...@hotwax.co>
Co-authored-by: Anahita Goljahani <an...@gmail.com>
Co-authored-by: dependabot[bot] <49...@users.noreply.github.com>
---
framework/component-load.xml | 1 +
framework/rest-api/README.md | 2 +
framework/rest-api/build.gradle | 28 ++
framework/rest-api/config/ApiUiLabels.xml | 38 ++
framework/rest-api/dtd/rest-api.xsd | 90 ++++
framework/rest-api/ofbiz-component.xml | 50 +++
framework/rest-api/servicedef/services.xml | 35 ++
framework/rest-api/src/docs/asciidoc/rest-api.adoc | 232 ++++++++++
.../org/apache/ofbiz/ws/rs/ApiServiceRequest.java | 38 ++
.../ofbiz/ws/rs/MethodNotAllowedException.java | 41 ++
.../ofbiz/ws/rs/ServiceNameContextHolder.java | 53 +++
.../ofbiz/ws/rs/ServiceNotFoundException.java | 37 ++
.../apache/ofbiz/ws/rs/ServiceRequestFilter.java | 126 ++++++
.../ofbiz/ws/rs/ServiceRequestProcessor.java | 90 ++++
.../apache/ofbiz/ws/rs/annotation/AuthToken.java | 49 +++
.../org/apache/ofbiz/ws/rs/annotation/Secured.java | 49 +++
.../ws/rs/annotation/ServiceRequestValidator.java | 46 ++
.../ofbiz/ws/rs/common/AuthenticationScheme.java | 39 ++
.../apache/ofbiz/ws/rs/core/OFBizApiConfig.java | 197 +++++++++
.../apache/ofbiz/ws/rs/core/ResponseStatus.java | 98 +++++
.../ws/rs/filters/ServiceContextCleanupFilter.java | 37 ++
.../ofbiz/ws/rs/listener/ApiContextListener.java | 96 +++++
.../org/apache/ofbiz/ws/rs/model/ModelApi.java | 151 +++++++
.../apache/ofbiz/ws/rs/model/ModelApiReader.java | 119 ++++++
.../apache/ofbiz/ws/rs/model/ModelOperation.java | 241 +++++++++++
.../apache/ofbiz/ws/rs/model/ModelResource.java | 265 ++++++++++++
.../ofbiz/ws/rs/openapi/OFBizOpenApiReader.java | 338 +++++++++++++++
.../ofbiz/ws/rs/openapi/OFBizResourceScanner.java | 79 ++++
.../ofbiz/ws/rs/process/RestRequestHandler.java | 294 +++++++++++++
.../ofbiz/ws/rs/process/ServiceRequestHandler.java | 105 +++++
.../ofbiz/ws/rs/resources/ApiRootResource.java | 120 ++++++
.../ws/rs/resources/AuthenticationResource.java | 146 +++++++
.../ws/rs/resources/OFBizServiceResource.java | 237 +++++++++++
.../ofbiz/ws/rs/resources/OpenApiResource.java | 160 +++++++
.../org/apache/ofbiz/ws/rs/response/Error.java | 251 +++++++++++
.../org/apache/ofbiz/ws/rs/response/Success.java | 120 ++++++
.../ofbiz/ws/rs/security/auth/APIAuthFilter.java | 164 +++++++
.../ofbiz/ws/rs/security/auth/APICorsFilter.java | 81 ++++
.../ws/rs/security/auth/HttpBasicAuthFilter.java | 130 ++++++
.../apache/ofbiz/ws/rs/services/RestServices.java | 72 ++++
.../rs/spi/impl/GenericServiceExceptionMapper.java | 126 ++++++
.../ws/rs/spi/impl/GlobalExceptionMapper.java | 55 +++
.../apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java | 73 ++++
.../spi/impl/JsonifiedParamConverterProvider.java | 98 +++++
.../ofbiz/ws/rs/spi/impl/LinkSerializer.java | 49 +++
.../org/apache/ofbiz/ws/rs/util/OpenApiUtil.java | 469 +++++++++++++++++++++
.../org/apache/ofbiz/ws/rs/util/RestApiUtil.java | 182 ++++++++
.../ofbiz/ws/rs/util/ServiceRequestWorker.java | 42 ++
framework/rest-api/testdef/rest-apiTests.xml | 26 ++
framework/rest-api/webapp/docs/README.adoc | 15 +
framework/rest-api/webapp/docs/WEB-INF/web.xml | 27 ++
framework/rest-api/webapp/docs/favicon-16x16.png | Bin 0 -> 665 bytes
framework/rest-api/webapp/docs/favicon-32x32.png | Bin 0 -> 628 bytes
.../rest-api/webapp/docs/oauth2-redirect.html | 74 ++++
framework/rest-api/webapp/docs/redoc.html | 47 +++
framework/rest-api/webapp/docs/redoc.standalone.js | 3 +
.../rest-api/webapp/docs/swagger-ui-bundle.js | 3 +
.../rest-api/webapp/docs/swagger-ui-bundle.js.map | 1 +
.../webapp/docs/swagger-ui-es-bundle-core.js | 3 +
.../webapp/docs/swagger-ui-es-bundle-core.js.map | 1 +
.../rest-api/webapp/docs/swagger-ui-es-bundle.js | 3 +
.../webapp/docs/swagger-ui-es-bundle.js.map | 1 +
.../webapp/docs/swagger-ui-standalone-preset.js | 3 +
.../docs/swagger-ui-standalone-preset.js.map | 1 +
framework/rest-api/webapp/docs/swagger-ui.css | 4 +
framework/rest-api/webapp/docs/swagger-ui.css.map | 1 +
framework/rest-api/webapp/docs/swagger-ui.html | 63 +++
framework/rest-api/webapp/docs/swagger-ui.js | 3 +
framework/rest-api/webapp/docs/swagger-ui.js.map | 1 +
framework/rest-api/webapp/rest-api/WEB-INF/web.xml | 54 +++
.../org/apache/ofbiz/service/ModelService.java | 2 +-
71 files changed, 5974 insertions(+), 1 deletion(-)
diff --git a/framework/component-load.xml b/framework/component-load.xml
index 1156327ab8..e9273d2eec 100644
--- a/framework/component-load.xml
+++ b/framework/component-load.xml
@@ -33,4 +33,5 @@ under the License.
<load-component component-location="widget"/>
<load-component component-location="testtools"/>
<load-component component-location="webtools"/>
+ <load-component component-location="rest-api"/>
</component-loader>
diff --git a/framework/rest-api/README.md b/framework/rest-api/README.md
new file mode 100644
index 0000000000..6477be2637
--- /dev/null
+++ b/framework/rest-api/README.md
@@ -0,0 +1,2 @@
+# REST API component
+For more information about this component visit [https://nightlies.apache.org/ofbiz/trunk/plugins/](https://nightlies.apache.org/ofbiz/trunk/plugins/) page.
diff --git a/framework/rest-api/build.gradle b/framework/rest-api/build.gradle
new file mode 100644
index 0000000000..d9e14704fe
--- /dev/null
+++ b/framework/rest-api/build.gradle
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+dependencies {
+ pluginLibsCompile 'org.glassfish.jersey.containers:jersey-container-servlet:3.1.11'
+ pluginLibsCompile 'org.glassfish.jersey.inject:jersey-hk2:3.1.11'
+ pluginLibsCompile 'org.glassfish.jersey.media:jersey-media-multipart:3.1.11'
+ pluginLibsCompile 'org.glassfish.jersey.media:jersey-media-json-jackson:3.1.11'
+ pluginLibsCompile 'io.swagger.core.v3:swagger-jaxrs2:2.2.50'
+ pluginLibsCompile 'io.swagger.core.v3:swagger-jaxrs2-servlet-initializer:2.2.50'
+ pluginLibsCompile 'io.swagger.core.v3:swagger-annotations:2.2.50'
+}
diff --git a/framework/rest-api/config/ApiUiLabels.xml b/framework/rest-api/config/ApiUiLabels.xml
new file mode 100644
index 0000000000..751a5f0e35
--- /dev/null
+++ b/framework/rest-api/config/ApiUiLabels.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:noNamespaceSchemaLocation="https://ofbiz.apache.org/dtds/ofbiz-properties.xsd">
+ <property key="GenericServiceValidationErrorMessage">
+ <value xml:lang="en">${service} validation failed. The request contained invalid information and could not be processed.</value>
+ </property>
+ <property key="GenericServiceExecutionGenericEntityOperationErrorMessage">
+ <value xml:lang="en">${service} execution failed. The request contained invalid information and could not be processed.</value>
+ </property>
+ <property key="GenericServiceExecutionGenericExceptionErrorMessage">
+ <value xml:lang="en">${service} execution failed. The service encountered an error; please try again later.</value>
+ </property>
+ <property key="NoSuchEntityDefaultMessage">
+ <value xml:lang="en">${service} execution failed. The requested entity does not exist.</value>
+ </property>
+ <property key="GenericServiceErrorMessage">
+ <value xml:lang="en">${service} returned error. The request contained invalid information and could not be processed.</value>
+ </property>
+</resource>
diff --git a/framework/rest-api/dtd/rest-api.xsd b/framework/rest-api/dtd/rest-api.xsd
new file mode 100644
index 0000000000..43273abb34
--- /dev/null
+++ b/framework/rest-api/dtd/rest-api.xsd
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<!-- NOTE: files using this schema are found in the service directory in a component when named *.rest.xml -->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
+ <xs:element name="api">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element minOccurs="0" maxOccurs="unbounded" ref="resource"/>
+ </xs:sequence>
+ <xs:attribute name="name" type="xs:string" use="required"/>
+ <xs:attribute name="path" type="xs:string" use="required"/>
+ <xs:attribute name="displayName" type="xs:string"/>
+ <xs:attribute name="description" type="xs:string"/>
+ <xs:attribute name="publish" type="xs:boolean" default="true"/>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="resource">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element minOccurs="0" maxOccurs="unbounded" ref="resource"/> <!-- allow nesting -->
+ <xs:element minOccurs="0" maxOccurs="unbounded" ref="operation"/>
+ </xs:sequence>
+ <xs:attribute name="name" type="xs:string" use="required"/>
+ <xs:attribute name="path" type="xs:string" use="required"/>
+ <xs:attribute name="displayName" type="xs:string"/>
+ <xs:attribute name="description" type="xs:string"/>
+ <xs:attribute name="publish" type="xs:boolean" default="true"/>
+ <xs:attribute name="auth" type="xs:boolean" default="true"/>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="operation">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element minOccurs="1" maxOccurs="1" ref="service"/>
+ </xs:sequence>
+ <xs:attribute name="verb" use="required">
+ <xs:simpleType>
+ <xs:restriction base="xs:token">
+ <xs:enumeration value="get"/>
+ <xs:enumeration value="patch"/>
+ <xs:enumeration value="put"/>
+ <xs:enumeration value="post"/>
+ <xs:enumeration value="delete"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+ <xs:attribute name="produces" use="optional">
+ <xs:simpleType>
+ <xs:restriction base="xs:token">
+ <xs:enumeration value="application/xml"/>
+ <xs:enumeration value="application/json"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+ <xs:attribute name="consumes" use="optional">
+ <xs:simpleType>
+ <xs:restriction base="xs:token">
+ <xs:enumeration value="application/xml"/>
+ <xs:enumeration value="application/json"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+ <xs:attribute name="path" type="xs:string" use="optional"/>
+ <xs:attribute name="description" type="xs:string"/>
+ <xs:attribute name="auth" type="xs:boolean" default="true"/>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="service">
+ <xs:complexType>
+ <xs:attribute name="name" type="xs:string" use="required"/>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
diff --git a/framework/rest-api/ofbiz-component.xml b/framework/rest-api/ofbiz-component.xml
new file mode 100644
index 0000000000..ff6785703b
--- /dev/null
+++ b/framework/rest-api/ofbiz-component.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<ofbiz-component name="rest-api"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:noNamespaceSchemaLocation="https://ofbiz.apache.org/dtds/ofbiz-component.xsd">
+ <!-- define resource loaders; most common is to use the component resource loader -->
+ <resource-loader name="main" type="component"/>
+
+ <!-- place the config directory on the classpath to access configuration files -->
+ <classpath type="dir" location="config"/>
+
+ <!-- service resources: model(s), eca(s) and group definitions -->
+ <service-resource type="model" loader="main" location="servicedef/services.xml"/>
+
+ <!--
+ <test-suite loader="main" location="testdef/rest-apiTests.xml"/>
+ -->
+
+ <!-- web applications; will be mounted when using the embedded container -->
+ <webapp name="rest-api"
+ title="REST API"
+ server="default-server"
+ location="webapp/rest-api"
+ mount-point="/rest"/>
+
+ <webapp name="api-docs"
+ title="REST API Docs"
+ app-bar-display="false"
+ server="default-server"
+ location="webapp/docs"
+ mount-point="/docs"/>
+</ofbiz-component>
diff --git a/framework/rest-api/servicedef/services.xml b/framework/rest-api/servicedef/services.xml
new file mode 100644
index 0000000000..611d2ef520
--- /dev/null
+++ b/framework/rest-api/servicedef/services.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:noNamespaceSchemaLocation="https://ofbiz.apache.org/dtds/services.xsd">
+ <description>rest-api Services</description>
+ <vendor></vendor>
+ <version>1.0</version>
+
+ <service name="generateAuthTokenService" engine="java" require-new-transaction="true" max-retry="3"
+ location="org.apache.ofbiz.ws.rs.services.RestServices" invoke="generateAuthToken">
+ <description>Generates Authorization Token for the userLogin</description>
+ <attribute name="access_token" type="String" mode="OUT" optional="false"/>
+ <attribute name="expires_in" type="String" mode="OUT" optional="false"/>
+ <attribute name="token_type" type="String" mode="OUT" optional="false"/>
+ </service>
+
+</services>
diff --git a/framework/rest-api/src/docs/asciidoc/rest-api.adoc b/framework/rest-api/src/docs/asciidoc/rest-api.adoc
new file mode 100644
index 0000000000..3b02d985a8
--- /dev/null
+++ b/framework/rest-api/src/docs/asciidoc/rest-api.adoc
@@ -0,0 +1,232 @@
+= Apache OFBiz® plugin for REST
+
+This initial implementation helps to expose existing or new OFBiz services as REST.
+To facilitate this, added a new "action" attribute to service elements that helps to determine how a particular service can be accessed via REST.
+
+== Important URLs
+* API https://localhost:8443/rest
+* WADL https://localhost:8443/rest/application.wadl
+* OpenAPI docs https://localhost:8443/docs/swagger-ui.html
+
+== Endpoints
+Once deployed, following URLs can be accessed
+
+* GET /rest/services
+* GET /rest/services/{serviceName}?inParams=<URLEncodedJSON>
+* POST /rest/services/{serviceName} (For this endpoint, the service in parameters must be part of Request Body)
+
+== Authentication
+API is protected by JWT tokens, although other forms of access tokens may be supported in future.
+An API client must first needs to authenticate itself using Basic Auth using username and password.
+Username is nothing but OFBiz 'userLogin'. Token can also be generated using Swagger UI.
+[source, json]
+----
+curl -X POST "https://localhost:8443/rest/auth/token" -H "accept: application/json" -H "Authorization: Basic YWRtaW46b2ZiaXo="
+----
+If successfully validated, generated token should be received in response
+[source, json]
+----
+{
+ "statusCode": 200,
+ "statusDescription": "OK",
+ "successMessage": "Token granted.",
+ "data": {
+ "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyTG9naW5JZCI6ImFkbWluIiwiaXNzIjoiQXBhY2hlT0ZCaXoiLCJleHAiOjE1OTY3MDk4MjAsImlhdCI6MTU5NjcwODAyMH0.9Hj4pkkeQowAMxPLrI_To0WTohxxgVR6FoViyx5HoboTACQZ4iqDyqiIBodkuCVsZwOTPT1RSAQJ0L_oSVMqBA",
+ "token_type": "Bearer",
+ "expires_in": "1800"
+ }
+}
+----
+
+Subsequent API calls must use received token using Bearer Authentication scheme as shown below -
+
+[source, json]
+----
+GET /rest/services HTTP/1.1
+Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyTG9naW5JZCI6ImFkbWluIiwiaXNzIjoiQXBhY2hlT0ZCaXoiLCJleHAiOjE1OTY3MDk4MjAsImlhdCI6MTU5NjcwODAyMH0.9Hj4pkkeQowAMxPLrI_To0WTohxxgVR6FoViyx5HoboTACQZ4iqDyqiIBodkuCVsZwOTPT1RSAQJ0L_oSVMqBA
+----
+
+== Example
+
+* List All Services (export="true" and verb = "get|post")
+[source, json]
+----
+GET /rest/services HTTP/1.1
+Content-Type: application/json
+Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJBcGFjaGVPRkJpeiIsImlhdCI6MTU0NzczOTM0OCwiZXhwIjoxNjc5Mjc1MzQ4LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1lIjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsInVzZXJMb2dpbklkIjoiYWRtaW4iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.fwafgrgpodBJcXxNTQdZknKeWKb3sDOsQrcR2vcRw97FznD6mkE79p10Tu7cqpUx7LiXuROUAnXEgqDice-BSg
+----
+
+Response :
+[source, json]
+----
+{
+ "statusCode" : 200,
+ "statusDescription" : "OK",
+ "successMessage" : "OK",
+ "data" : [ {
+ "name" : "findProductById",
+ "description" : "Finds productId(s) corresponding to a product reference, productId or a GoodIdentification idValue",
+ "link" : {
+ "href" : "https://localhost:8443/rest/services/findProductById",
+ "rel" : "self",
+ "type" : "get"
+ }
+ }, {
+ "name" : "searchProductsByGoodIdentificationValue",
+ "description" : "Search Products by Good Identification Value",
+ "link" : {
+ "href" : "https://localhost:8443/rest/services/searchProductsByGoodIdentificationValue",
+ "rel" : "self",
+ "type" : "post"
+ }
+ } ]
+}
+----
+
+* Call OFBiz service via GET(export="true" and verb = "get|post")
+
+
+[source, json]
+----
+GET /rest/services/findProductById?inParams=%7B%22idToFind%22:%22GZ-1001%22%7D HTTP/1.1 +
+Content-Type: application/json +
+Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJBcGFjaGVPRkJpeiIsImlhdCI6MTU0NzczOTM0OCwiZXhwIjoxNjc5Mjc1MzQ4LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1lIjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsInVzZXJMb2dpbklkIjoiYWRtaW4iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.fwafgrgpodBJcXxNTQdZknKeWKb3sDOsQrcR2vcRw97FznD6mkE79p10Tu7cqpUx7LiXuROUAnXEgqDice-BSg
+----
+
+Response :
+[source, json]
+----
+{
+ "statusCode" : 200,
+ "statusDescription" : "OK",
+ "data" : {
+ "product" : {
+ "createdStamp" : "2020-06-11T15:29:58.182+0000",
+ "productName" : "Nan Gizmo",
+ "createdByUserLogin" : "admin",
+ "productId" : "GZ-1001",
+ "taxable" : "Y",
+ "primaryProductCategoryId" : "101",
+ "createdTxStamp" : "2020-06-11T15:29:57.523+0000",
+ "lastUpdatedTxStamp" : "2020-06-11T15:29:57.523+0000",
+ "isVirtual" : "N",
+ "autoCreateKeywords" : "Y",
+ "description" : "Indian style Nan gizmo",
+ "chargeShipping" : "Y",
+ "internalName" : "Nan Gizmo",
+ "lastModifiedByUserLogin" : "admin",
+ "lastUpdatedStamp" : "2020-06-11T15:29:58.182+0000",
+ "lastModifiedDate" : "2001-05-13T06:30:00.000+0000",
+ "productTypeId" : "FINISHED_GOOD",
+ "createdDate" : "2001-05-13T06:30:00.000+0000",
+ "isVariant" : "N"
+ }
+ }
+}
+----
+
+* Call OFBiz Service via POST +
+[source, json]
+----
+POST rest/services/searchProductsByGoodIdentificationValue HTTP/1.1
+Content-Type: application/json
+Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJBcGFjaGVPRkJpeiIsImlhdCI6MTU0NzczOTM0OCwiZXhwIjoxNjc5Mjc1MzQ4LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1lIjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsInVzZXJMb2dpbklkIjoiYWRtaW4iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.fwafgrgpodBJcXxNTQdZknKeWKb3sDOsQrcR2vcRw97FznD6mkE79p10Tu7cqpUx7LiXuROUAnXEgqDice-BSg
+{
+ "idFragment": "2644"
+}
+----
+
+Response +
+[source, json]
+----
+{
+ "statusCode" : 200,
+ "statusDescription" : "OK",
+ "data" : {
+ "products" : [ {
+ "internalName" : "Round Gizmo",
+ "productId" : "GZ-2644",
+ "primaryProductCategoryId" : "101",
+ "isVariant" : "N",
+ "goodIdentificationTypeId" : "INVOICE_EXPORT",
+ "idValue" : "GZ-2644-replaced",
+ "isVirtual" : "N"
+ } ]
+ }
+}
+----
+
+== Refresh Token Mechanism
+
+The authentication system now supports a refresh token mechanism.
+This allows clients to obtain a new `access_token` using a previously issued `refresh_token`.
+This improves user experience by reducing frequent authentication prompts.
+It helps in maintaining seamless user sessions while minimising exposure of credentials,
+making authentication more efficient and secure.
+
+[CAUTION]
+====
+Of course it's not that simple on the security side. Because a `refresh_token` can be stolen!
+This is well explained by this https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/[auth0.com article].
+====
+
+
+To preserve security auth0 is using a https://auth0.com/docs/secure/tokens/refresh-tokens/refresh-token-rotation[rotation mechanism] that sounds like a wise solution.
+This is not implement OOTB in OFBiz, so you might implement it or possibly use auth0 for that.
+
+The idea is to have short term refresh tokens replaced each time a refresh token is called. Here is an Auth0 article excerpt:
+[TIP]
+====
+With refresh token rotation enabled in the Auth0 Dashboard, every time an application exchanges a refresh token to get a new access token, a new refresh token is also returned. Therefore, you no longer have a long-lived refresh token that, if compromised, could provide illegitimate access to resources. As refresh tokens are continually exchanged and invalidated, the threat is reduced.
+
+====
+
+The complete process is explained simply but well https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/#Refresh-Token-Automatic-Reuse-Detection[here].
+A priori, this would be while calling AuthenticationResource::refreshToken. BTW this allows to store refresh tokens in local storage, which is quite safe.
+
+
+=== Login API Enhancement
+This said, upon successful login, the response includes both `access_token` and `refresh_token`.
+
+.Response Example
+[source,json]
+----
+{
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
+ "refresh_token": "dGhpc19pc19hX3JlZnJlc2hfdG9rZW4..."
+}
+----
+
+=== Get Access Token Using Refresh Token
+
+A new endpoint has been introduced to obtain a new `access_token` using a valid `refresh_token`.
+
+*URL:* `POST https://localhost:8443/rest/auth/refresh-token`
+
+==== Request
+
+The request should contain the `refresh_token` in the body.
+
+.Request Example
+[source,json]
+----
+{
+ "Refresh-Token": "dGhpc19pc19hX3JlZnJlc2hfdG9rZW4..."
+}
+----
+
+==== Response
+
+If the refresh token is valid, a new `access_token` is returned.
+
+.Response Example
+[source,json]
+----
+{
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
+}
+----
+
+==== Errors
+
+- `401 Unauthorized`: If the provided refresh token is missing, expired, or invalid.
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ApiServiceRequest.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ApiServiceRequest.java
new file mode 100644
index 0000000000..d3541cfef2
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ApiServiceRequest.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+import java.util.Map;
+
+public final class ApiServiceRequest {
+ private Map<String, Object> inParams;
+
+ public Map<String, Object> getInParams() {
+ return inParams;
+ }
+
+ public ApiServiceRequest(Map<String, Object> inParams) {
+ this.inParams = inParams;
+ }
+
+ @Override
+ public String toString() {
+ return inParams != null ? inParams.toString() : super.toString();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.java
new file mode 100644
index 0000000000..9f3f4ad3b6
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+import jakarta.ws.rs.ClientErrorException;
+import jakarta.ws.rs.core.Response;
+
+/**
+ *
+ */
+public class MethodNotAllowedException extends ClientErrorException {
+
+ private static final long serialVersionUID = -3002310435429546325L;
+
+ /**
+ * Constructs a new {@link MethodNotAllowedException} with the given message
+ * and HTTP status 405 Method Not Allowed.
+ *
+ * @param message a human-readable description of why the method is not allowed
+ */
+ public MethodNotAllowedException(String message) {
+ super(message, Response.Status.METHOD_NOT_ALLOWED);
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNameContextHolder.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNameContextHolder.java
new file mode 100644
index 0000000000..14d4cbd9a7
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNameContextHolder.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+public final class ServiceNameContextHolder {
+
+ private static final ThreadLocal<String> SERVICE_NAME = new ThreadLocal<>();
+
+ private ServiceNameContextHolder() {
+ // Prevent instantiation
+ }
+
+ /**
+ * Sets the current service name for this thread.
+ *
+ * @param serviceName the name of the service being executed
+ */
+ public static void set(String serviceName) {
+ SERVICE_NAME.set(serviceName);
+ }
+
+ /**
+ * Returns the current service name for this thread, or null if none is set.
+ *
+ * @return the service name
+ */
+ public static String get() {
+ return SERVICE_NAME.get();
+ }
+
+ /**
+ * Clears the stored service name from the current thread context.
+ */
+ public static void clear() {
+ SERVICE_NAME.remove();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNotFoundException.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNotFoundException.java
new file mode 100644
index 0000000000..022a556896
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceNotFoundException.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+import jakarta.ws.rs.NotFoundException;
+
+public class ServiceNotFoundException extends NotFoundException {
+
+ private static final long serialVersionUID = -3002310435429546325L;
+
+ /**
+ * Constructs a new {@link ServiceNotFoundException} for the given OFBiz
+ * service name.
+ *
+ * @param service the name of the service that could not be found
+ */
+ public ServiceNotFoundException(String service) {
+ super("Service '" + service + "' not found.");
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestFilter.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestFilter.java
new file mode 100644
index 0000000000..207bca012c
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestFilter.java
@@ -0,0 +1,126 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+import java.io.IOException;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.webapp.WebAppUtil;
+import org.apache.ofbiz.ws.rs.annotation.ServiceRequestValidator;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+
+import jakarta.annotation.Priority;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.ResourceInfo;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.UriInfo;
+import jakarta.ws.rs.ext.Provider;
+
+@Provider
+@ServiceRequestValidator
+@Priority(Priorities.USER)
+public class ServiceRequestFilter implements ContainerRequestFilter {
+
+ private static final String MODULE = ServiceRequestFilter.class.getName();
+
+ private static final String SVC_IN_PARAMS = "inParams";
+
+ @Context
+ private UriInfo uriInfo;
+
+ @Context
+ private ResourceInfo resourceInfo;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ @Context
+ private ServletContext servletContext;
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Validates the incoming service request against the OFBiz service
+ * definition before the request reaches the resource method. The following
+ * checks are performed in order:</p>
+ * <ul>
+ * <li>The service exists — throws {@link ServiceNotFoundException} if not</li>
+ * <li>The service is marked as exportable — throws {@link NotFoundException} if not</li>
+ * <li>The service has an HTTP action defined — throws {@link NotFoundException} if not</li>
+ * <li>The HTTP method matches the service action — throws {@link MethodNotAllowedException} if not</li>
+ * <li>GET requests include the {@code inParams} query parameter —
+ * throws {@link BadRequestException} if absent</li>
+ * </ul>
+ *
+ * <p>On successful validation, the service name is stored in
+ * {@link ServiceNameContextHolder} for use by downstream filters and
+ * exception mappers.</p>
+ */
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ Debug.logInfo("Service request is going to get validated!", MODULE);
+ String service = (String) RestApiUtil.extractParams(uriInfo.getPathParameters()).get("serviceName");
+ String method = requestContext.getMethod();
+ String action = null;
+ if (UtilValidate.isNotEmpty(service)) {
+ ModelService mdService = null;
+ try {
+ mdService = WebAppUtil.getDispatcher(servletContext).getDispatchContext().getModelService(service);
+ } catch (GenericServiceException e) {
+ Debug.logError(e.getMessage(), MODULE);
+ }
+
+ if (mdService == null) {
+ throw new ServiceNotFoundException(service);
+ }
+
+ if (mdService != null && !mdService.isExport()) {
+ throw new NotFoundException("Service '" + service + "' is not exportable.");
+ }
+
+ action = mdService.getAction();
+ if (mdService != null && UtilValidate.isEmpty(action)) {
+ throw new NotFoundException("Service '" + service + "' does not have HTTP action defined.");
+ }
+
+ if (!action.equalsIgnoreCase(method)) {
+ throw new MethodNotAllowedException("HTTP " + method + " is not allowed on service '" + service + "'");
+ }
+
+ if (action.equalsIgnoreCase(HttpMethod.GET) && UtilValidate.isNotEmpty(mdService.getInParamNamesMap())
+ && UtilValidate.isEmpty(httpRequest.getParameter(SVC_IN_PARAMS))) {
+ throw new BadRequestException("Missing Parameter: 'inParams'");
+ }
+ // If everything looks good, set the 'requestForService' property in the
+ // context. Indicates which service this request is for.
+ ServiceNameContextHolder.set(service);
+ }
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java
new file mode 100644
index 0000000000..9625e8f489
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs;
+
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.service.DispatchContext;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.service.ServiceUtil;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+import org.apache.ofbiz.ws.rs.util.ServiceRequestWorker;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.core.Response;
+
+public class ServiceRequestProcessor {
+
+ /**
+ * Processes an incoming REST API request by executing the mapped OFBiz service
+ * and returning a JSON response.
+ *
+ * <p>The following keys are expected in {@code requestContext}:</p>
+ * <ul>
+ * <li>{@code serviceName} — the OFBiz service to invoke</li>
+ * <li>{@code httpVerb} — the HTTP method of the request (e.g. {@code GET}, {@code POST})</li>
+ * <li>{@code requestMap} — the request parameters</li>
+ * <li>{@code dispatcher} — the {@link LocalDispatcher} to use for service invocation</li>
+ * <li>{@code request} — the {@link HttpServletRequest} providing the authenticated user</li>
+ * </ul>
+ *
+ * <p>If the service result indicates success, the non-internal output parameters
+ * are returned in the response data. If the service fails, an HTTP 422
+ * Unprocessable Entity error response is returned.</p>
+ *
+ * @param requestContext a map containing the request execution context
+ * @return a JSON {@link Response} with the service output on success, or an
+ * error response on failure
+ * @throws GenericServiceException if the service invocation fails unexpectedly
+ * @throws NotFoundException if the requested service does not exist
+ * @throws MethodNotAllowedException if the HTTP verb is not permitted for the service
+ */
+ @SuppressWarnings("unchecked")
+ public Response process(Map<String, Object> requestContext) throws GenericServiceException {
+ String serviceName = (String) requestContext.get("serviceName");
+ String httpVerb = (String) requestContext.get("httpVerb");
+ Map<String, Object> requestMap = (Map<String, Object>) requestContext.get("requestMap");
+ LocalDispatcher dispatcher = (LocalDispatcher) requestContext.get("dispatcher");
+ HttpServletRequest request = (HttpServletRequest) requestContext.get("request");
+ GenericValue userLogin = (GenericValue) request.getAttribute("userLogin");
+ DispatchContext dispatchContext = dispatcher.getDispatchContext();
+ ModelService service = null;
+ try {
+ service = dispatchContext.getModelService(serviceName);
+ } catch (GenericServiceException gse) {
+ throw new NotFoundException(gse.getMessage());
+ }
+ if (UtilValidate.isNotEmpty(service.getAction()) && !service.getAction().equalsIgnoreCase(httpVerb)) {
+ throw new MethodNotAllowedException("HTTP " + httpVerb + " is not allowed on this service.");
+ }
+ Map<String, Object> serviceContext = dispatchContext.makeValidContext(serviceName, ModelService.IN_PARAM, requestMap);
+ serviceContext.put("userLogin", userLogin);
+ Map<String, Object> result = dispatcher.runSync(serviceName, serviceContext);
+ if (ServiceUtil.isSuccess(result)) {
+ Map<String, Object> responseData = ServiceRequestWorker.extractResponseData(service, result);
+ return RestApiUtil.success((String) result.get(ModelService.SUCCESS_MESSAGE), responseData);
+ }
+ return RestApiUtil.buildErrorFromServiceResult(serviceName, result, request.getLocale());
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/AuthToken.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/AuthToken.java
new file mode 100644
index 0000000000..53ea1d7018
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/AuthToken.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import jakarta.ws.rs.NameBinding;
+
+
+/**
+ * JAX-RS name binding annotation that binds {@link org.apache.ofbiz.ws.rs.security.auth.HttpBasicAuthFilter}
+ * to the resource classes or methods it annotates.
+ *
+ * <p>When applied to a JAX-RS resource class or method, the JAX-RS runtime
+ * will execute {@link org.apache.ofbiz.ws.rs.security.auth.HttpBasicAuthFilter} before the request is processed,
+ * validating the HTTP Basic Auth credentials in the {@code Authorization}
+ * header against OFBiz user logins.</p>
+ *
+ * <p>This annotation is used on the token issuance endpoint
+ * ({@code POST /auth/token}), which requires Basic Auth to authenticate
+ * the user before issuing a JWT access token.</p>
+ *
+ * @see org.apache.ofbiz.ws.rs.security.auth.HttpBasicAuthFilter
+ */
+@NameBinding
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.METHOD})
+public @interface AuthToken {
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/Secured.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/Secured.java
new file mode 100644
index 0000000000..7ea10b1e87
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/Secured.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import jakarta.ws.rs.NameBinding;
+
+
+/**
+ * JAX-RS name binding annotation that binds {@link org.apache.ofbiz.ws.rs.security.auth.APIAuthFilter}
+ * to the resource classes or methods it annotates.
+ *
+ * <p>When applied to a JAX-RS resource class or method, the JAX-RS runtime
+ * will execute {@link org.apache.ofbiz.ws.rs.security.auth.APIAuthFilter} before the request is processed,
+ * validating the Bearer JWT token in the {@code Authorization} header.
+ * Requests without a valid token are rejected with HTTP 401 Unauthorized.</p>
+ *
+ * <p>This annotation is applied to all protected API endpoints, such as
+ * {@link org.apache.ofbiz.ws.rs.resources.OFBizServiceResource}, which require a valid JWT obtained from
+ * {@code POST /auth/token}.</p>
+ *
+ * @see org.apache.ofbiz.ws.rs.security.auth.APIAuthFilter
+ */
+@NameBinding
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.METHOD})
+public @interface Secured {
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/ServiceRequestValidator.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/ServiceRequestValidator.java
new file mode 100644
index 0000000000..1de22c6b2b
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/annotation/ServiceRequestValidator.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import jakarta.ws.rs.NameBinding;
+
+
+/**
+ * JAX-RS name binding annotation that binds {@link org.apache.ofbiz.ws.rs.ServiceRequestFilter}
+ * to the resource class it annotates.
+ *
+ * <p>When applied to a JAX-RS resource class, the JAX-RS runtime will
+ * execute {@link org.apache.ofbiz.ws.rs.ServiceRequestFilter} before each request is processed,
+ * validating the incoming request parameters against the OFBiz service
+ * definition. Requests that fail validation are rejected before reaching
+ * the resource method.</p>
+ *
+ * @see org.apache.ofbiz.ws.rs.ServiceRequestFilter
+ */
+@NameBinding
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.TYPE })
+public @interface ServiceRequestValidator {
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/common/AuthenticationScheme.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/common/AuthenticationScheme.java
new file mode 100644
index 0000000000..06d8daf210
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/common/AuthenticationScheme.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.common;
+
+public enum AuthenticationScheme {
+
+ BASIC("Basic"),
+ BEARER("Bearer");
+ private String scheme;
+ public static final String REALM = "OFBiz";
+ AuthenticationScheme(String scheme) {
+ this.scheme = scheme;
+ }
+ /**
+ * Returns the scheme string as used in HTTP {@code Authorization}
+ * and {@code WWW-Authenticate} headers.
+ *
+ * @return the scheme name, either {@code "Basic"} or {@code "Bearer"}
+ */
+ public String getScheme() {
+ return scheme;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java
new file mode 100644
index 0000000000..aec2953bcd
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java
@@ -0,0 +1,197 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.core;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.ofbiz.base.component.ComponentConfig;
+import org.apache.ofbiz.base.component.ComponentException;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.ws.rs.ServiceRequestFilter;
+import org.apache.ofbiz.ws.rs.annotation.Secured;
+import org.apache.ofbiz.ws.rs.filters.ServiceContextCleanupFilter;
+import org.apache.ofbiz.ws.rs.model.ModelApi;
+import org.apache.ofbiz.ws.rs.model.ModelApiReader;
+import org.apache.ofbiz.ws.rs.model.ModelOperation;
+import org.apache.ofbiz.ws.rs.model.ModelResource;
+import org.apache.ofbiz.ws.rs.process.ServiceRequestHandler;
+import org.glassfish.jersey.jackson.JacksonFeature;
+import org.glassfish.jersey.logging.LoggingFeature;
+import org.glassfish.jersey.media.multipart.MultiPartFeature;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.server.model.Resource;
+import org.glassfish.jersey.server.model.ResourceMethod;
+
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.core.MediaType;
+
+public class OFBizApiConfig extends ResourceConfig {
+ private static final String MODULE = OFBizApiConfig.class.getName();
+ private static final Map<String, ModelApi> MICRO_APIS = new HashMap<>();
+
+ /**
+ * Configures the OFBiz JAX-RS application by registering built-in resource
+ * packages, features, filters, and all DSL-defined REST API resources loaded
+ * from {@code *.rest.xml} files found in each OFBiz component's {@code api}
+ * directory.
+ */
+ public OFBizApiConfig() {
+ packages("org.apache.ofbiz.ws.rs.resources");
+ packages("org.apache.ofbiz.ws.rs.security.auth");
+ packages("org.apache.ofbiz.ws.rs.spi.impl");
+ // packages("io.swagger.v3.jaxrs2.integration.resources"); //commenting it out
+ // to generate customized OpenApi Spec
+ register(JacksonFeature.class);
+ register(ServiceRequestFilter.class);
+ register(MultiPartFeature.class);
+ register(ServiceContextCleanupFilter.class);
+ //property(ServerProperties.TRACING, "ALL");
+ if (Debug.verboseOn()) {
+ register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO,
+ LoggingFeature.Verbosity.PAYLOAD_ANY, 10000));
+ }
+ registerDSLResources();
+ }
+
+ /**
+ * Returns all loaded REST API definitions keyed by their root path.
+ *
+ * <p>Each entry maps the API path (e.g. {@code "party"}) to the
+ * corresponding {@link ModelApi} loaded from a {@code *.rest.xml}
+ * definition file.</p>
+ *
+ * @return registered API definitions
+ */
+ public static Map<String, ModelApi> getModelApis() {
+ return MICRO_APIS;
+ }
+
+ private void registerDSLResources() {
+ loadApiDefinitions();
+ traverseAndRegisterApiDefinitions();
+ }
+
+ private void loadApiDefinitions() {
+ Collection<ComponentConfig> components = ComponentConfig.getAllComponents();
+ for (ComponentConfig component : components) {
+ String componentName = component.getComponentName();
+ try {
+ String apiDirPath = ComponentConfig.getRootLocation(componentName) + "/api";
+ File apiDir = new File(apiDirPath);
+ if (!apiDir.exists() || !apiDir.isDirectory()) {
+ continue;
+ }
+ File[] restXmlFiles = apiDir.listFiles((dir, name) -> name.endsWith(".rest.xml"));
+ if (restXmlFiles == null) {
+ continue;
+ }
+ for (File restXmlFile : restXmlFiles) {
+ ModelApi api = ModelApiReader.getModelApi(restXmlFile);
+ if (!api.isPublish()) {
+ Debug.logInfo("API %s[%s] is declared non-publish, ignoring...", api.getName(), api.getPath(), MODULE);
+ continue;
+ }
+ String path = api.getPath();
+ if (MICRO_APIS.containsKey(path)) {
+ Debug.logWarning("Duplicate REST API definition for path: %s at: %s, overriding component: %s",
+ path, restXmlFile, componentName, MODULE);
+ } else {
+ Debug.logInfo("Processing REST API path: %s from component: %s", path, componentName, MODULE);
+ }
+ MICRO_APIS.put(path, api);
+ }
+ } catch (ComponentException | RuntimeException e) {
+ Debug.logError(e, MODULE);
+ }
+ }
+ }
+
+ private void traverseAndRegisterApiDefinitions() {
+ if (UtilValidate.isEmpty(MICRO_APIS)) {
+ Debug.logInfo("No API definitions to process", MODULE);
+ return;
+ }
+
+ MICRO_APIS.forEach((apiPath, modelApi) -> {
+ Debug.logInfo("Registering Resource Definitions from API - " + apiPath, MODULE);
+ for (ModelResource resource : modelApi.getResources()) {
+ String resourcePath = buildCleanPath(apiPath, resource.getPath());
+ registerModelResource(resource, resourcePath);
+ }
+ });
+ }
+ private void registerModelResource(ModelResource modelResource, String basePath) {
+ if (!modelResource.isPublish()) return;
+
+ Resource.Builder resourceBuilder = Resource.builder("/" + basePath)
+ .name(modelResource.getName());
+
+ for (ModelOperation op : modelResource.getOperations()) {
+ String verb = op.getVerb().toUpperCase();
+ boolean isOtherThanGet = verb.matches(HttpMethod.POST + "|" + HttpMethod.PUT + "|" + HttpMethod.PATCH);
+ String opPath = op.getPath();
+
+ ResourceMethod.Builder methodBuilder;
+ if (UtilValidate.isEmpty(opPath)) {
+ methodBuilder = resourceBuilder.addMethod(verb);
+ } else {
+ Resource.Builder childBuilder = resourceBuilder.addChildResource(opPath);
+ methodBuilder = childBuilder.addMethod(verb);
+ }
+
+ methodBuilder.produces(MediaType.APPLICATION_JSON);
+ if (isOtherThanGet) {
+ methodBuilder.consumes(MediaType.APPLICATION_JSON);
+ }
+ if (op.isAuth()) {
+ methodBuilder.nameBindings(Secured.class);
+ }
+ methodBuilder.handledBy(new ServiceRequestHandler(op.getService()));
+ }
+
+ // Register the current resource
+ registerResources(resourceBuilder.build());
+
+ // Recursively process nested sub-resources
+ if (UtilValidate.isNotEmpty(modelResource.getSubResources())) {
+ for (ModelResource sub : modelResource.getSubResources()) {
+ String subPath = buildCleanPath(basePath, sub.getPath());
+ registerModelResource(sub, subPath);
+ }
+ }
+ }
+ private String buildCleanPath(String... parts) {
+ StringBuilder pathBuilder = new StringBuilder();
+ for (String part : parts) {
+ if (part == null || part.trim().isEmpty()) continue;
+ part = part.replaceAll("^/+", "").replaceAll("/+$", ""); // trim slashes
+ if (!part.isEmpty()) {
+ if (pathBuilder.length() > 0) pathBuilder.append('/');
+ pathBuilder.append(part);
+ }
+ }
+ return pathBuilder.toString();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/ResponseStatus.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/ResponseStatus.java
new file mode 100644
index 0000000000..d85791f280
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/core/ResponseStatus.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.core;
+
+import jakarta.ws.rs.core.Response.Status.Family;
+import jakarta.ws.rs.core.Response.StatusType;
+
+public final class ResponseStatus {
+
+ public enum Custom implements StatusType {
+ /**
+ * 422 Unprocessable Entity, see <a href=
+ * "https://tools.ietf.org/html/rfc4918#section-11.2">https://tools.ietf.org/html/rfc4918#section-11.2</a>
+ */
+ UNPROCESSABLE_ENTITY(422, "Unprocessable Entity");
+
+ private final int code;
+ private final String reason;
+ private final Family family;
+
+ Custom(final int statusCode, final String reasonPhrase) {
+ this.code = statusCode;
+ this.reason = reasonPhrase;
+ this.family = Family.familyOf(statusCode);
+ }
+
+ /**
+ * Get the class of status code.
+ *
+ * @return the class of status code.
+ */
+ @Override
+ public Family getFamily() {
+ return family;
+ }
+
+ /**
+ * Get the associated status code.
+ *
+ * @return the status code.
+ */
+ @Override
+ public int getStatusCode() {
+ return code;
+ }
+
+ /**
+ * Get the reason phrase.
+ *
+ * @return the reason phrase.
+ */
+ @Override
+ public String getReasonPhrase() {
+ return toString();
+ }
+
+ /**
+ * Get the reason phrase.
+ *
+ * @return the reason phrase.
+ */
+ @Override
+ public String toString() {
+ return reason;
+ }
+
+ /**
+ * Convert a numerical status code into the corresponding Status.
+ *
+ * @param code
+ * @return the matching Status or null is no matching Status is defined.
+ */
+ public static ResponseStatus.Custom fromStatusCode(int code) {
+ for (Custom s : Custom.values()) {
+ if (s.code == code) {
+ return s;
+ }
+ }
+ return null;
+ }
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/filters/ServiceContextCleanupFilter.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/filters/ServiceContextCleanupFilter.java
new file mode 100644
index 0000000000..2de4c60265
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/filters/ServiceContextCleanupFilter.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.filters;
+
+import java.io.IOException;
+
+import org.apache.ofbiz.ws.rs.ServiceNameContextHolder;
+
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.container.ContainerResponseFilter;
+import jakarta.ws.rs.ext.Provider;
+
+@Provider
+public class ServiceContextCleanupFilter implements ContainerResponseFilter {
+ @Override
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
+ throws IOException {
+ ServiceNameContextHolder.clear(); // ✅ runs after ExceptionMapper
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java
new file mode 100644
index 0000000000..cad3b46102
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java
@@ -0,0 +1,96 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.listener;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.DelegatorFactory;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ServiceContainer;
+
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.ServletContextEvent;
+import jakarta.servlet.ServletContextListener;
+
+/**
+ * Servlet context listener that initializes and destroys the OFBiz
+ * {@link Delegator} and {@link LocalDispatcher} instances for the REST API
+ * web application.
+ *
+ * <p>On startup, the delegator and dispatcher are retrieved using the
+ * {@code entityDelegatorName} and {@code localDispatcherName} init parameters
+ * from {@code web.xml} and stored as servlet context attributes, making them
+ * available to all JAX-RS resources via {@code @Context ServletContext}.</p>
+ *
+ * <p>On shutdown, both attributes are removed from the servlet context.</p>
+ */
+public class ApiContextListener implements ServletContextListener {
+
+ public static final String MODULE = ApiContextListener.class.getName();
+ // TODO: remove after the refactoring of OFBizOpenApiReader
+ private static ServletContext servletContext = null;
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Retrieves the {@link Delegator} and {@link LocalDispatcher} using the
+ * {@code entityDelegatorName} and {@code localDispatcherName} init parameters
+ * from {@code web.xml} and stores them as servlet context attributes for use
+ * by JAX-RS resources.</p>
+ */
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+ servletContext = sce.getServletContext();
+ Delegator delegator = DelegatorFactory.getDelegator(servletContext.getInitParameter("entityDelegatorName"));
+ LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(servletContext.getInitParameter("localDispatcherName"), delegator);
+ Debug.logInfo("Api Jersey Context initialized, delegator " + delegator + ", dispatcher", MODULE);
+ servletContext.setAttribute("delegator", delegator);
+ servletContext.setAttribute("dispatcher", dispatcher);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Removes the {@code delegator} and {@code dispatcher} attributes
+ * from the servlet context.</p>
+ */
+ @Override
+ public void contextDestroyed(ServletContextEvent sce) {
+ ServletContext context = sce.getServletContext();
+ Debug.logInfo("Api Jersey Context destroyed, removing delegator and dispatcher ", MODULE);
+ context.removeAttribute("delegator");
+ context.removeAttribute("dispatcher");
+ context = null;
+ }
+
+
+ /**
+ * Returns the servlet context stored at initialization time.
+ *
+ * @return the application {@link ServletContext}, or {@code null} if the
+ * context has not yet been initialized
+ * @deprecated Temporary workaround to provide servlet context access to
+ * {@code OFBizOpenApiReader}; will be removed once that class
+ * is refactored
+ */
+ // TODO: remove after the refactoring of OFBizOpenApiReader
+ public static ServletContext getApplicationCntx() {
+ return servletContext;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApi.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApi.java
new file mode 100644
index 0000000000..985191a8c3
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApi.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ModelApi {
+
+ private List<ModelResource> resources;
+ private String name;
+ private String path;
+ private String displayName;
+ private String description;
+ private boolean publish;
+
+ /**
+ * Returns the List of ModelResources. Creates an empty
+ * List if no resources set.
+ *
+ * @return the resources value
+ */
+ public List<ModelResource> getResources() {
+ if (resources == null) {
+ resources = new ArrayList<ModelResource>();
+ }
+ return this.resources;
+ }
+
+ /**
+ * Adds a resource to this API definition and returns the current instance
+ * to support method chaining.
+ *
+ * @param resource the {@link ModelResource} to add
+ * @return this {@link ModelApi} instance
+ */
+ public ModelApi addResource(ModelResource resource) {
+ if (this.resources == null) {
+ this.resources = new ArrayList<>();
+ }
+ this.resources.add(resource);
+ return this;
+ }
+
+ /**
+ * Returns the name.
+ *
+ * @return the name value
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Returns the path.
+ *
+ * @return the path value
+ */
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * Sets the name.
+ *
+ * @param value the name value to set
+ */
+ public void setName(String value) {
+ this.name = value;
+ }
+
+ /**
+ * Sets the path.
+ *
+ * @param path the path value to set
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Returns the display name.
+ *
+ * @return the display name value
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * Sets the display name.
+ *
+ * @param value the display name value to set
+ */
+ public void setDisplayName(String value) {
+ this.displayName = value;
+ }
+
+ /**
+ * Returns the description.
+ *
+ * @return the description value
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Sets the description.
+ *
+ * @param value the description value to set
+ */
+ public void setDescription(String value) {
+ this.description = value;
+ }
+
+ /**
+ * Returns whether publish is enabled.
+ *
+ * @return true if publish is enabled, otherwise false
+ */
+ public boolean isPublish() {
+ return publish;
+ }
+
+ /**
+ * Sets whether publish is enabled.
+ *
+ * @param publish true to enable publish, false to disable it
+ */
+ public void setPublish(boolean publish) {
+ this.publish = publish;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApiReader.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApiReader.java
new file mode 100644
index 0000000000..af099d3156
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelApiReader.java
@@ -0,0 +1,119 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.model;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilXml;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+public final class ModelApiReader {
+ private static final String MODULE = ModelApiReader.class.getName();
+
+ private ModelApiReader() {
+
+ }
+
+ /**
+ * Parses the given {@code *.rest.xml} file and returns a fully populated
+ * {@link ModelApi} instance including all nested resources and operations.
+ *
+ * @param apiDef the {@code *.rest.xml} file to parse.
+ * @return the parsed {@link ModelApi}, or {@code null} if the file could
+ * not be read or parsed
+ */
+ public static ModelApi getModelApi(final File apiDef) {
+ Element docElement;
+ try {
+ docElement = UtilXml.readXmlDocument(new FileInputStream(apiDef), true, "REST API file", true)
+ .getDocumentElement();
+ } catch (SAXException | ParserConfigurationException | IOException e) {
+ e.printStackTrace();
+ throw new RuntimeException("Failed to parse REST API definition: " + apiDef, e);
+ }
+ docElement.normalize();
+ ModelApi api = new ModelApi();
+
+ api.setDisplayName(UtilXml.checkEmpty(docElement.getAttribute("displayName")).intern());
+ api.setName(UtilXml.checkEmpty(docElement.getAttribute("name")).intern());
+ api.setDescription(UtilXml.checkEmpty(docElement.getAttribute("description")).intern());
+ api.setPath(UtilXml.checkEmpty(docElement.getAttribute("path")).intern());
+ api.setPublish(Boolean.parseBoolean(UtilXml.checkEmpty(docElement.getAttribute("publish")).intern()));
+ for (Element resourceEle : UtilXml.childElementList(docElement, "resource")) {
+ createModelResource(resourceEle, api);
+ }
+ return api;
+ }
+
+ private static void createModelResource(Element resourceEle, ModelApi api) {
+ ModelResource resource = buildResource(resourceEle);
+ createOperations(resourceEle, resource);
+
+ // recursive children
+ for (Element nestedResourceEle : UtilXml.childElementList(resourceEle, "resource")) {
+ createModelResource(nestedResourceEle, resource);
+ }
+
+ Debug.logInfo(resource.toString(), MODULE);
+ api.addResource(resource);
+ }
+
+ private static void createModelResource(Element resourceEle, ModelResource parentResource) {
+ ModelResource resource = buildResource(resourceEle);
+ createOperations(resourceEle, resource);
+
+ for (Element nestedResourceEle : UtilXml.childElementList(resourceEle, "resource")) {
+ createModelResource(nestedResourceEle, resource);
+ }
+
+ Debug.logInfo(resource.toString(), MODULE);
+ parentResource.addSubResource(resource);
+ }
+ private static ModelResource buildResource(Element resourceEle) {
+ return new ModelResource()
+ .name(UtilXml.checkEmpty(resourceEle.getAttribute("name")).intern())
+ .description(UtilXml.checkEmpty(resourceEle.getAttribute("description")).intern())
+ .displayName(UtilXml.checkEmpty(resourceEle.getAttribute("displayName")).intern())
+ .path(UtilXml.checkEmpty(resourceEle.getAttribute("path")).intern())
+ .publish(Boolean.parseBoolean(UtilXml.checkEmpty(resourceEle.getAttribute("publish")).intern()))
+ .auth(Boolean.parseBoolean(UtilXml.checkEmpty(resourceEle.getAttribute("auth")).intern()));
+ }
+
+ private static void createOperations(Element resourceEle, ModelResource resource) {
+ for (Element operationEle : UtilXml.childElementList(resourceEle, "operation")) {
+ Element serviceEle = UtilXml.firstChildElement(operationEle, "service");
+ String serviceName = UtilXml.checkEmpty(serviceEle.getAttribute("name")).intern();
+ ModelOperation op = new ModelOperation()
+ .path(UtilXml.checkEmpty(operationEle.getAttribute("path")).intern())
+ .verb(UtilXml.checkEmpty(operationEle.getAttribute("verb")).intern()).service(serviceName)
+ .produces(UtilXml.checkEmpty(operationEle.getAttribute("produces")).intern())
+ .consumes(UtilXml.checkEmpty(operationEle.getAttribute("consumes")).intern())
+ .description(UtilXml.checkEmpty(operationEle.getAttribute("description")).intern())
+ .auth(Boolean.parseBoolean(UtilXml.checkEmpty(operationEle.getAttribute("auth")).intern()));
+ resource.addOperation(op);
+ }
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelOperation.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelOperation.java
new file mode 100644
index 0000000000..19ece9f210
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelOperation.java
@@ -0,0 +1,241 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.model;
+
+public class ModelOperation {
+
+ private String service;
+ private String verb;
+ private String produces;
+ private String consumes;
+ private String path;
+ private String description;
+ private boolean auth;
+
+ /**
+ * Returns whether the user is authenticated.
+ *
+ * @return true if authenticated, false otherwise
+ */
+ public boolean isAuth() {
+ return auth;
+ }
+
+ /**
+ * Sets the authentication state.
+ *
+ * @param auth true to mark as authenticated, false otherwise
+ */
+ public void setAuth(boolean auth) {
+ this.auth = auth;
+ }
+
+ /**
+ * Sets whether this operation requires JWT authentication and returns
+ * this instance.
+ *
+ * @param auth {@code true} if a valid JWT is required; {@code false} otherwise
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation auth(boolean auth) {
+ this.auth = auth;
+ return this;
+ }
+
+ /**
+ * Returns the service name.
+ *
+ * @return the service value
+ */
+ public String getService() {
+ return service;
+ }
+
+ /**
+ * Sets the service name.
+ *
+ * @param value the service value to set
+ */
+ public void setService(String value) {
+ this.service = value;
+ }
+
+ /**
+ * Sets the OFBiz service name for this operation and returns this instance.
+ *
+ * @param value the service name
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation service(String value) {
+ this.service = value;
+ return this;
+ }
+
+ /**
+ * Returns the HTTP verb.
+ *
+ * @return the verb value (e.g., GET, POST, PUT, DELETE)
+ */
+ public String getVerb() {
+ return verb;
+ }
+
+ /**
+ * Sets the HTTP verb.
+ *
+ * @param value the verb to set (e.g., GET, POST, PUT, DELETE)
+ */
+ public void setVerb(String value) {
+ this.verb = value;
+ }
+
+ /**
+ * Sets the HTTP verb for this operation and returns this instance.
+ *
+ * @param value the HTTP verb (e.g. {@code GET}, {@code POST})
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation verb(String value) {
+ this.verb = value;
+ return this;
+ }
+
+ /**
+ * Returns the response media type produced by the service.
+ *
+ * @return the produces value (e.g., application/json)
+ */
+ public String getProduces() {
+ return produces;
+ }
+
+ /**
+ * Sets the response media type produced by the service.
+ *
+ * @param value the produces value to set (e.g., application/json)
+ */
+ public void setProduces(String value) {
+ this.produces = value;
+ }
+
+ /**
+ * Sets the media type this operation produces and returns this instance.
+ *
+ * @param value the media type (e.g. {@code application/json})
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation produces(String value) {
+ this.produces = value;
+ return this;
+ }
+
+ /**
+ * Returns the request media type consumed by the service.
+ *
+ * @return the consumes value (e.g., application/json)
+ */
+ public String getConsumes() {
+ return consumes;
+ }
+
+ /**
+ * Sets the request media type consumed by the service.
+ *
+ * @param value the consumes value to set (e.g., application/json)
+ */
+ public void setConsumes(String value) {
+ this.consumes = value;
+ }
+
+ /**
+ * Sets the media type this operation consumes and returns this instance.
+ *
+ * @param value the media type (e.g. {@code application/json})
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation consumes(String value) {
+ this.consumes = value;
+ return this;
+ }
+
+ /**
+ * Returns the path.
+ *
+ * @return the current path value
+ */
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * Sets the path.
+ *
+ * @param value the path to set
+ */
+ public void setPath(String value) {
+ this.path = value;
+ }
+
+ /**
+ * Sets the sub-path for this operation and returns this instance.
+ *
+ * @param value the sub-path relative to the parent resource path
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation path(String value) {
+ this.path = value;
+ return this;
+ }
+
+ /**
+ * Returns the description.
+ *
+ * @return the description value
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Sets the description.
+ *
+ * @param value the description to set
+ */
+ public void setDescription(String value) {
+ this.description = value;
+ }
+
+ /**
+ * Sets the description for this operation and returns this instance.
+ *
+ * @param value the operation description
+ * @return this {@link ModelOperation} instance
+ */
+ public ModelOperation description(String value) {
+ this.description = value;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return "service: " + service + ", path: " + path + ", verb: " + verb + ", description: " + description
+ + ", produces: " + produces;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelResource.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelResource.java
new file mode 100644
index 0000000000..624599e226
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/model/ModelResource.java
@@ -0,0 +1,265 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ModelResource {
+
+ private List<ModelOperation> operations;
+ private List<ModelResource> subResources = new ArrayList<>();
+ private String name;
+ private String path;
+ private String displayName;
+ private String description;
+ private boolean publish;
+ private boolean auth;
+
+ /**
+ * Returns whether the user is authenticated.
+ *
+ * @return true if the user is authenticated, false otherwise
+ */
+ public boolean isAuth() {
+ return auth;
+ }
+
+ /**
+ * Sets the authentication status of the user.
+ *
+ * @param auth true to mark the user as authenticated, false otherwise
+ */
+ public void setAuth(boolean auth) {
+ this.auth = auth;
+ }
+
+ /**
+ * Sets whether this resource requires JWT authentication and returns
+ * this instance to support method chaining.
+ *
+ * @param auth {@code true} if a valid JWT is required; {@code false} otherwise
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource auth(boolean auth) {
+ this.auth = auth;
+ return this;
+ }
+
+ /**
+ * Sets whether the item is published.
+ *
+ * @param publish true to mark as published, false otherwise
+ */
+ protected void setPublish(boolean publish) {
+ this.publish = publish;
+ }
+
+ /**
+ * Returns the operations defined for this resource, or an empty list if
+ * no operations have been added yet.
+ *
+ * @return the list of {@link ModelOperation} instances; never {@code null}
+ */
+ public List<ModelOperation> getOperations() {
+ return operations == null ? new ArrayList<ModelOperation>() : operations;
+ }
+
+ /**
+ * Adds an operation to this resource and returns this instance
+ * to support method chaining.
+ *
+ * @param operation the {@link ModelOperation} to add
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource addOperation(ModelOperation operation) {
+ if (this.operations == null) {
+ this.operations = new ArrayList<>();
+ }
+ this.operations.add(operation);
+ return this;
+ }
+
+ /**
+ * Returns the name.
+ *
+ * @return the current name value
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name.
+ *
+ * @param name the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Sets the name of this resource and returns this instance
+ * to support method chaining.
+ *
+ * @param name the resource name
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Sets the path of this resource and returns this instance
+ * to support method chaining.
+ *
+ * @param path the URL path segment for this resource
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource path(String path) {
+ this.path = path;
+ return this;
+ }
+
+ /**
+ * Returns the path.
+ *
+ * @return the current path value
+ */
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * Sets the path.
+ *
+ * @param path the path to set
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Returns the display name.
+ *
+ * @return the display name
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * Sets the display name of this resource and returns this instance
+ * to support method chaining.
+ *
+ * @param displayName the human-readable display name
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource displayName(String displayName) {
+ this.displayName = displayName;
+ return this;
+ }
+
+ /**
+ * Sets the display name.
+ *
+ * @param displayName the display name to set
+ */
+ public void setDisplayName(String displayName) {
+ this.displayName = displayName;
+ }
+
+ /**
+ * Returns the description.
+ *
+ * @return the description value
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Sets the description.
+ *
+ * @param description the description to set
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Adds a nested sub-resource to this resource.
+ *
+ * @param resource the child {@link ModelResource} to add
+ */
+ public void addSubResource(ModelResource resource) {
+ this.subResources.add(resource);
+ }
+
+ /**
+ * Returns the nested sub-resources of this resource.
+ *
+ * @return the list of child {@link ModelResource} instances; never {@code null}
+ */
+ public List<ModelResource> getSubResources() {
+ return subResources;
+ }
+
+ /**
+ * Sets the description of this resource and returns this instance
+ * to support method chaining.
+ *
+ * @param description the resource description
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource description(String description) {
+ this.description = description;
+ return this;
+ }
+
+ /**
+ * Returns whether the item is published.
+ *
+ * @return true if the item is published, false otherwise
+ */
+ public boolean isPublish() {
+ return publish;
+ }
+
+ /**
+ * Sets whether this resource is published and returns this instance
+ * to support method chaining.
+ *
+ * @param publish {@code true} if this resource should be published; {@code false} otherwise
+ * @return this {@link ModelResource} instance
+ */
+ public ModelResource publish(boolean publish) {
+ this.publish = publish;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ // TODO Auto-generated method stub
+ return "name: " + name + ", path: " + path + ", displayName: " + displayName + ", description: " + description
+ + ", publish: " + publish;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java
new file mode 100644
index 0000000000..2c93d8ea18
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java
@@ -0,0 +1,338 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.openapi;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import jakarta.servlet.ServletContext;
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.service.DispatchContext;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ModelParam;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.webapp.WebAppUtil;
+import org.apache.ofbiz.ws.rs.core.OFBizApiConfig;
+import org.apache.ofbiz.ws.rs.listener.ApiContextListener;
+import org.apache.ofbiz.ws.rs.model.ModelApi;
+import org.apache.ofbiz.ws.rs.model.ModelOperation;
+import org.apache.ofbiz.ws.rs.model.ModelResource;
+import org.apache.ofbiz.ws.rs.util.OpenApiUtil;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+
+import io.swagger.v3.jaxrs2.Reader;
+import io.swagger.v3.oas.integration.api.OpenAPIConfiguration;
+import io.swagger.v3.oas.integration.api.OpenApiReader;
+import io.swagger.v3.oas.models.Components;
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.Operation;
+import io.swagger.v3.oas.models.PathItem;
+import io.swagger.v3.oas.models.Paths;
+import io.swagger.v3.oas.models.media.Content;
+import io.swagger.v3.oas.models.media.MediaType;
+import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.oas.models.media.StringSchema;
+import io.swagger.v3.oas.models.parameters.HeaderParameter;
+import io.swagger.v3.oas.models.parameters.Parameter;
+import io.swagger.v3.oas.models.parameters.PathParameter;
+import io.swagger.v3.oas.models.parameters.QueryParameter;
+import io.swagger.v3.oas.models.parameters.RequestBody;
+import io.swagger.v3.oas.models.responses.ApiResponse;
+import io.swagger.v3.oas.models.responses.ApiResponses;
+import io.swagger.v3.oas.models.security.SecurityRequirement;
+import io.swagger.v3.oas.models.tags.Tag;
+
+public final class OFBizOpenApiReader extends Reader implements OpenApiReader {
+ private static final String MODULE = OFBizOpenApiReader.class.getName();
+ private Components components;
+ private Paths paths;
+ @SuppressWarnings("rawtypes")
+ private Map<String, Schema> schemas;
+ private OpenAPI openApi;
+ private DispatchContext context;
+ private static final Parameter HEADER_CONTENT_TYPE_JSON = new HeaderParameter().name(HttpHeaders.CONTENT_TYPE)
+ .schema(new StringSchema()).example(jakarta.ws.rs.core.MediaType.APPLICATION_JSON).required(true);
+ private static final Parameter HEADER_ACCEPT_JSON = new HeaderParameter().name(HttpHeaders.ACCEPT)
+ .schema(new StringSchema()).example(jakarta.ws.rs.core.MediaType.APPLICATION_JSON).required(true);
+
+ @Override
+ public void setConfiguration(OpenAPIConfiguration openApiConfiguration) {
+ super.setConfiguration(openApiConfiguration);
+ }
+
+ @Override
+ public OpenAPI read(Set<Class<?>> classes, Map<String, Object> resources) {
+ openApi = super.read(classes, resources);
+ ServletContext servletContext = ApiContextListener.getApplicationCntx();
+ LocalDispatcher dispatcher = WebAppUtil.getDispatcher(servletContext);
+ context = dispatcher.getDispatchContext();
+ initializeStdOpenApiComponents();
+ addPredefinedSchemas();
+ addExportableServices();
+ addApiResources();
+ openApi.setPaths(paths);
+ openApi.setComponents(components);
+ return openApi;
+ }
+
+ private void addApiResources() {
+ Map<String, ModelApi> apis = OFBizApiConfig.getModelApis();
+ SecurityRequirement security = new SecurityRequirement();
+ security.addList("jwtToken");
+
+ apis.forEach((k, api) -> {
+ if (!api.isPublish()) return;
+
+ List<String> baseSegments = new ArrayList<>();
+ baseSegments.add(api.getPath());
+
+ for (ModelResource resource : api.getResources()) {
+ processResourceRecursive(resource, baseSegments, security);
+ }
+ });
+ }
+ private void processResourceRecursive(ModelResource resource, List<String> parentSegments, SecurityRequirement security) {
+ List<String> currentSegments = new ArrayList<>(parentSegments);
+ currentSegments.add(resource.getPath());
+
+ Tag resourceTag = new Tag().name(resource.getDisplayName()).description(resource.getDescription());
+ openApi.addTagsItem(resourceTag);
+
+ for (ModelOperation op : resource.getOperations()) {
+ List<String> fullPathSegments = new ArrayList<>(currentSegments);
+ fullPathSegments.add(op.getPath());
+ String uri = buildNestedUrl(fullPathSegments);
+
+ PathItem pathItemObject = paths.get(uri);
+ boolean pathExists = pathItemObject != null;
+ if (!pathExists) {
+ pathItemObject = new PathItem();
+ }
+
+ String serviceName = op.getService();
+ ModelService service;
+ try {
+ service = context.getModelService(serviceName);
+ } catch (GenericServiceException e) {
+ Debug.logError("Service '" + serviceName + "' not found while trying to map REST resource " + uri + "; ignoring. ", MODULE);
+ continue;
+ }
+
+ Operation operation = new Operation()
+ .summary(op.getDescription())
+ .description(op.getDescription())
+ .addTagsItem(resource.getDisplayName())
+ .operationId(serviceName)
+ .deprecated(false)
+ .addSecurityItem(security);
+
+ String verb = op.getVerb().toUpperCase();
+ if (verb.equalsIgnoreCase(HttpMethod.GET)) {
+ QueryParameter serviceInParam = (QueryParameter) new QueryParameter().required(true)
+ .description("Operation Input Parameters in JSON").name("input");
+
+ Schema<?> refSchema = new Schema<>().$ref("#/components/schemas/api.request." + service.getName());
+ serviceInParam.content(new Content().addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON,
+ new MediaType().schema(refSchema)));
+ operation.addParametersItem(serviceInParam);
+ } else if (verb.matches(HttpMethod.POST + "|" + HttpMethod.PUT + "|" + HttpMethod.PATCH)) {
+ RequestBody request = new RequestBody()
+ .description("Request Body for operation " + op.getDescription())
+ .content(new Content().addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON,
+ new MediaType().schema(new Schema<>().$ref("#/components/schemas/api.request." + service.getName()))));
+ operation.setRequestBody(request);
+ operation.addParametersItem(HEADER_CONTENT_TYPE_JSON);
+ }
+
+ List<String> pathParams = RestApiUtil.getPathParameters(uri);
+ for (String pathParam : pathParams) {
+ ModelParam mdParam = service.getInModelParamList().stream()
+ .filter(param -> (!param.getInternal() && pathParam.equals(param.getName())))
+ .findFirst().orElse(null);
+ PathParameter pathParameter = new PathParameter();
+ pathParameter.setRequired(true);
+ pathParameter.setName(pathParam);
+ pathParameter.setDescription(mdParam != null ? mdParam.getShortDisplayDescription() : "");
+ pathParameter.setSchema(OpenApiUtil.getAttributeSchema(service, mdParam));
+ operation.addParametersItem(pathParameter);
+ }
+
+ addServiceOutSchema(service);
+ addServiceInSchema(service);
+ addServiceOperationApiResponses(service, operation);
+ setPathItemOperation(pathItemObject, verb.toUpperCase(), operation);
+
+ if (!pathExists) {
+ paths.addPathItem(uri, pathItemObject);
+ }
+ }
+
+ //Recursively process nested resources
+ if (resource.getSubResources() != null) {
+ for (ModelResource sub : resource.getSubResources()) {
+ processResourceRecursive(sub, currentSegments, security);
+ }
+ }
+ }
+
+ public static String buildNestedUrl(List<String> segments) {
+ StringBuilder pathBuilder = new StringBuilder();
+ for (String segment : segments) {
+ if (segment == null || segment.trim().isEmpty()) {
+ continue;
+ }
+
+ // Trim leading/trailing slashes
+ segment = segment.replaceAll("^/+", "").replaceAll("/+$", "");
+ if (!segment.isEmpty()) {
+ pathBuilder.append("/").append(segment);
+ }
+ }
+ return pathBuilder.toString();
+ }
+ private void addExportableServices() {
+ Set<String> serviceNames = context.getAllServiceNames();
+ for (String serviceName : serviceNames) {
+ ModelService service = null;
+ try {
+ service = context.getModelService(serviceName);
+ } catch (GenericServiceException e) {
+ e.printStackTrace();
+ }
+ if (service != null && service.isExport() && UtilValidate.isNotEmpty(service.getAction())) {
+ String action = service.getAction().toUpperCase();
+ SecurityRequirement security = new SecurityRequirement();
+ security.addList("jwtToken");
+ final Operation operation = new Operation().summary(service.getDescription())
+ .description(service.getDescription()).addTagsItem("Exported Services")
+ .operationId(service.getName()).deprecated(false).addSecurityItem(security);
+ PathItem pathItemObject = new PathItem();
+ if (service.getAction().equalsIgnoreCase(HttpMethod.GET)) {
+ boolean inParamsEmpty = UtilValidate.isEmpty(service.getInParamNamesMap());
+ if (!inParamsEmpty) {
+ QueryParameter serviceInParam = new QueryParameter();
+ serviceInParam.setRequired(true);
+ serviceInParam.setDescription("Operation Input Parameters in JSON");
+ serviceInParam.setName("input");
+
+ Schema<?> refSchema = new Schema<>();
+ refSchema.$ref("#/components/schemas/" + "api.request." + service.getName());
+ serviceInParam.content(new Content().addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON,
+ new MediaType().schema(refSchema)));
+ operation.addParametersItem(serviceInParam);
+ }
+ operation.addParametersItem(HEADER_ACCEPT_JSON);
+ } else if (action.matches(HttpMethod.POST + "|" + HttpMethod.PUT + "|" + HttpMethod.PATCH)) {
+ RequestBody request = new RequestBody().description("Request Body for service " + service.getName())
+ .content(new Content().addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON,
+ new MediaType().schema(new Schema<>().$ref("#/components/schemas/" + "api.request." + service.getName()))));
+ operation.setRequestBody(request);
+ operation.addParametersItem(HEADER_CONTENT_TYPE_JSON);
+ }
+ addServiceOutSchema(service);
+ addServiceInSchema(service);
+ addServiceOperationApiResponses(service, operation);
+ setPathItemOperation(pathItemObject, service.getAction().toUpperCase(), operation);
+ paths.addPathItem("/services/" + service.getName(), pathItemObject);
+ }
+ }
+ }
+
+ private void initializeStdOpenApiComponents() {
+ Tag serviceResourceTag = new Tag().name("Exported Services")
+ .description("OFBiz services that are exposed via REST interface with export attribute set to true");
+ openApi.addTagsItem(serviceResourceTag);
+ components = openApi.getComponents();
+ if (components == null) {
+ components = new Components();
+ }
+ schemas = components.getSchemas();
+ if (schemas == null) {
+ schemas = new HashMap<>();
+ components.schemas(schemas);
+ }
+ paths = openApi.getPaths();
+ if (paths == null) {
+ paths = new Paths();
+ }
+ }
+
+ private void setPathItemOperation(PathItem pathItemObject, String method, Operation operation) {
+ switch (method) {
+ case HttpMethod.POST:
+ pathItemObject.post(operation);
+ break;
+ case HttpMethod.GET:
+ pathItemObject.get(operation);
+ break;
+ case HttpMethod.DELETE:
+ pathItemObject.delete(operation);
+ break;
+ case HttpMethod.PUT:
+ pathItemObject.put(operation);
+ break;
+ case HttpMethod.PATCH:
+ pathItemObject.patch(operation);
+ break;
+ case HttpMethod.HEAD:
+ pathItemObject.head(operation);
+ break;
+ case HttpMethod.OPTIONS:
+ pathItemObject.options(operation);
+ break;
+ default:
+ // Do nothing here
+ break;
+ }
+ }
+
+ private void addServiceOutSchema(ModelService service) {
+ schemas.put("api.response." + service.getName() + ".success", OpenApiUtil.getOutSchema(service));
+ }
+
+ private void addServiceInSchema(ModelService service) {
+ schemas.put("api.request." + service.getName(), OpenApiUtil.getInSchema(service));
+ }
+
+ private void addPredefinedSchemas() {
+ OpenApiUtil.getStandardApiResponseSchemas().forEach((name, schema) -> {
+ schemas.put(name, schema);
+ });
+ }
+
+ private void addServiceOperationApiResponses(ModelService service, Operation operation) {
+ ApiResponses apiResponsesObject = new ApiResponses();
+ ApiResponse successResponse = OpenApiUtil.buildSuccessResponse(service);
+ apiResponsesObject.addApiResponse(String.valueOf(Response.Status.OK.getStatusCode()), successResponse);
+ OpenApiUtil.getStandardApiResponses().forEach((code, response) -> {
+ apiResponsesObject.addApiResponse(code, response);
+ });
+ operation.setResponses(apiResponsesObject);
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java
new file mode 100644
index 0000000000..3e3033858f
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.openapi;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.ofbiz.base.util.UtilValidate;
+
+import io.swagger.v3.jaxrs2.integration.JaxrsApplicationAndResourcePackagesAnnotationScanner;
+
+public class OFBizResourceScanner extends JaxrsApplicationAndResourcePackagesAnnotationScanner {
+
+ private static final Set<String> IGNORED = new HashSet<>();
+
+ static {
+ IGNORED.add("org.apache.ofbiz.ws.rs.resources.OFBizServiceResource");
+ }
+
+ /**
+ * Constructs a new {@link OFBizResourceScanner} configured to scan only
+ * packages explicitly registered as resource packages.
+ */
+ public OFBizResourceScanner() {
+ onlyConsiderResourcePackages = true;
+ }
+
+ /**
+ * Returns the set of resource classes discovered by the parent scanner,
+ * excluding classes configured in the ignore list.
+ *
+ * @return the filtered set of resource classes
+ */
+ public Set<Class<?>> classes() {
+ Set<Class<?>> classes = super.classes();
+ Set<Class<?>> outputClasses = new HashSet<>();
+ for (Class<?> clz : classes) {
+ if (!isIgnored(clz.getName())) {
+ outputClasses.add(clz);
+ }
+ }
+ return outputClasses;
+ }
+
+ /**
+ * Determines whether a class or package name should be excluded from
+ * OpenAPI resource scanning.
+ *
+ * <p>A name is considered ignored if it is empty or starts with one of the
+ * configured ignore prefixes.</p>
+ *
+ * @param classOrPackageName the fully qualified class or package name
+ * @return {@code true} if the name should be ignored; {@code false} otherwise
+ */
+ protected boolean isIgnored(String classOrPackageName) {
+ if (UtilValidate.isEmpty(classOrPackageName)) {
+ return true;
+ }
+ boolean isIgnored = IGNORED.stream().anyMatch(classOrPackageName::startsWith);
+ return isIgnored;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/RestRequestHandler.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/RestRequestHandler.java
new file mode 100644
index 0000000000..d1d205bc18
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/RestRequestHandler.java
@@ -0,0 +1,294 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.process;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.glassfish.jersey.message.internal.MediaTypes;
+import org.glassfish.jersey.process.Inflector;
+import org.glassfish.jersey.server.ContainerRequest;
+import org.glassfish.jersey.server.ExtendedUriInfo;
+import org.glassfish.jersey.spi.ExceptionMappers;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Provider;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ResourceInfo;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+
+/**
+ * Base request handler for REST endpoints.
+ *
+ * <p>This class provides access to commonly injected JAX-RS and servlet
+ * resources and dispatches requests based on the HTTP method. Request
+ * parameters from the path, query string, and request body are collected
+ * into a single argument map before being passed to
+ * {@link #execute(ContainerRequestContext, Map)}.</p>
+ */
+public abstract class RestRequestHandler implements Inflector<ContainerRequestContext, Response> {
+
+ @Inject
+ private HttpHeaders httpHeaders;
+
+ @Inject
+ private UriInfo uriInfo;
+
+ @Inject
+ private ExtendedUriInfo extendedUriInfo;
+
+ @Inject
+ private ResourceInfo resourceInfo;
+
+ @Inject
+ private ServletContext servletContext;
+
+ @Inject
+ private HttpServletRequest httpRequest;
+
+ @Inject
+ private Provider<ExceptionMappers> mappers;
+
+ /**
+ * Returns the HTTP headers associated with the current request.
+ *
+ * @return the request headers
+ */
+ protected HttpHeaders getHttpHeaders() {
+ return httpHeaders;
+ }
+
+ /**
+ * Returns URI information for the current request.
+ *
+ * @return the request URI information
+ */
+ protected UriInfo getUriInfo() {
+ return uriInfo;
+ }
+
+ /**
+ * Returns extended URI metadata provided by Jersey.
+ *
+ * @return the extended URI information
+ */
+ protected ExtendedUriInfo getExtendedUriInfo() {
+ return extendedUriInfo;
+ }
+
+ /**
+ * Returns information about the matched resource class and method.
+ *
+ * @return the current resource information
+ */
+ protected ResourceInfo getResourceInfo() {
+ return resourceInfo;
+ }
+
+ /**
+ * Returns the servlet context associated with the current request.
+ *
+ * @return the servlet context
+ */
+ protected ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ /**
+ * Returns the underlying servlet request.
+ *
+ * @return the HTTP servlet request
+ */
+ protected HttpServletRequest getHttpRequest() {
+ return httpRequest;
+ }
+
+ /**
+ * Dispatches the request to the appropriate HTTP method handler.
+ *
+ * @param ctx the request context
+ * @return the response produced by the request handler
+ */
+ @Override
+ public Response apply(ContainerRequestContext ctx) {
+ String method = ctx.getMethod();
+ switch (method) {
+ case HttpMethod.POST:
+ return doPost(ctx);
+ case HttpMethod.GET:
+ return doGet(ctx);
+ case HttpMethod.DELETE:
+ return doDelete(ctx);
+ case HttpMethod.PUT:
+ return doPut(ctx);
+ case HttpMethod.PATCH:
+ return doPatch(ctx);
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Executes the request using the extracted request arguments.
+ *
+ * <p>The supplied argument map may contain values from path parameters,
+ * query parameters, and the request body, depending on the HTTP method.</p>
+ *
+ * @param data the request context
+ * @param arguments the extracted request arguments
+ * @return the response to return to the client
+ */
+ protected abstract Response execute(ContainerRequestContext data, Map<String, Object> arguments);
+
+ /**
+ * Extracts a JSON request body into a map of argument values.
+ *
+ * <p>If the request does not contain a JSON entity, an empty map is
+ * returned.</p>
+ *
+ * @param requestContext the request context
+ * @return the extracted request body arguments
+ */
+ @SuppressWarnings("unchecked")
+ protected Map<String, Object> extractRequestBody(ContainerRequestContext requestContext) {
+ if (requestContext instanceof ContainerRequest) {
+ ContainerRequest request = (ContainerRequest) requestContext;
+ if (requestContext.hasEntity()) {
+ request.bufferEntity();
+ if (isJson(requestContext)) {
+ Map<String, Object> entity = request.readEntity(Map.class);
+ if (entity == null) {
+ return Collections.emptyMap();
+ }
+ return entity;
+ }
+ }
+ }
+ return Collections.emptyMap();
+ }
+
+ /**
+ * Extracts path parameters from the request.
+ *
+ * @param requestContext the request context
+ * @return a map containing path parameter values
+ */
+ protected Map<String, Object> extractPathParameters(ContainerRequestContext requestContext) {
+ return extract(requestContext.getUriInfo().getPathParameters());
+ }
+
+ /**
+ * Extracts query parameters from the request.
+ *
+ * @param requestContext the request context
+ * @return a map containing query parameter values
+ */
+ protected Map<String, Object> extractQueryParameters(ContainerRequestContext requestContext) {
+ return extract(requestContext.getUriInfo().getQueryParameters());
+ }
+
+ /**
+ * Converts a multivalued parameter map into a standard argument map.
+ *
+ * <p>Single-value parameters are stored as strings, while parameters with
+ * multiple values are stored as a list of strings.</p>
+ *
+ * @param multivaluedMap the source parameter map
+ * @return the converted argument map
+ */
+ protected Map<String, Object> extract(MultivaluedMap<String, String> multivaluedMap) {
+ Map<String, Object> result = new HashMap<>();
+ multivaluedMap.forEach((name, values) -> {
+ if (UtilValidate.isNotEmpty(values)) {
+ result.put(name, (values.size() != 1) ? values : values.get(0));
+ }
+ });
+ return result;
+ }
+
+ /**
+ * Determines whether the request content type is JSON.
+ *
+ * @param requestContext the request context
+ * @return {@code true} if the request content type is JSON;
+ * {@code false} otherwise
+ */
+ private boolean isJson(ContainerRequestContext requestContext) {
+ final MediaType mediaType = requestContext.getMediaType();
+ return UtilValidate.isNotEmpty(mediaType)
+ && MediaTypes.typeEqual(mediaType, MediaType.APPLICATION_JSON_TYPE);
+ }
+
+ private Response doGet(ContainerRequestContext requestContext) {
+ Map<String, Object> arguments = new HashMap<>();
+ arguments.putAll(extractPathParameters(requestContext));
+ arguments.putAll(extractQueryParameters(requestContext));
+ return execute(requestContext, arguments);
+ }
+
+ private Response doPost(ContainerRequestContext requestContext) {
+ Map<String, Object> arguments = new HashMap<>();
+ arguments.putAll(extractRequestBody(requestContext));
+ arguments.putAll(extractPathParameters(requestContext));
+ arguments.putAll(extractQueryParameters(requestContext));
+ return execute(requestContext, arguments);
+ }
+
+ private Response doPut(ContainerRequestContext requestContext) {
+ Map<String, Object> arguments = new HashMap<>();
+ arguments.putAll(extractRequestBody(requestContext));
+ arguments.putAll(extractPathParameters(requestContext));
+ arguments.putAll(extractQueryParameters(requestContext));
+ return execute(requestContext, arguments);
+ }
+
+ private Response doPatch(ContainerRequestContext requestContext) {
+ Map<String, Object> arguments = new HashMap<>();
+ arguments.putAll(extractRequestBody(requestContext));
+ arguments.putAll(extractPathParameters(requestContext));
+ arguments.putAll(extractQueryParameters(requestContext));
+ return execute(requestContext, arguments);
+ }
+
+ private Response doDelete(ContainerRequestContext requestContext) {
+ Map<String, Object> arguments = new HashMap<>();
+ arguments.putAll(extractPathParameters(requestContext));
+ arguments.putAll(extractQueryParameters(requestContext));
+ return execute(requestContext, arguments);
+ }
+
+ /**
+ * Returns the exception mapper provider used to resolve JAX-RS exception
+ * mappers.
+ *
+ * @return the exception mapper provider
+ */
+ public Provider<ExceptionMappers> getMappers() {
+ return mappers;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/ServiceRequestHandler.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/ServiceRequestHandler.java
new file mode 100644
index 0000000000..e1cb7256dd
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/process/ServiceRequestHandler.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.process;
+
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.service.DispatchContext;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.service.ServiceUtil;
+import org.apache.ofbiz.ws.rs.ServiceNameContextHolder;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+import org.apache.ofbiz.ws.rs.util.ServiceRequestWorker;
+
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
+
+public final class ServiceRequestHandler extends RestRequestHandler {
+
+ private static final String MODULE = ServiceRequestHandler.class.getName();
+ private String service;
+
+ public ServiceRequestHandler(String service) {
+ this.service = service;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Executes the mapped OFBiz service synchronously and returns a JSON
+ * response. The execution proceeds as follows:</p>
+ * <ul>
+ * <li>A valid service context is built from the request arguments using
+ * {@link DispatchContext#makeValidContext}</li>
+ * <li>The authenticated {@code userLogin} is added to the service context</li>
+ * <li>The service is executed synchronously via {@link LocalDispatcher#runSync}</li>
+ * <li>On success, non-internal output parameters are collected and returned
+ * as a JSON success response</li>
+ * <li>On service result failure, an HTTP 422 error response is returned</li>
+ * <li>On {@link GenericServiceException} from either context building or
+ * execution, the registered {@link ExceptionMapper} is used to map the
+ * exception to an appropriate error response</li>
+ * </ul>
+ */
+ @Override
+ protected Response execute(ContainerRequestContext ctx, Map<String, Object> arguments) {
+ ServiceNameContextHolder.set(service);
+ LocalDispatcher dispatcher = (LocalDispatcher) getServletContext().getAttribute("dispatcher");
+ Map<String, Object> serviceContext = null;
+ try {
+ serviceContext = dispatcher.getDispatchContext().makeValidContext(service, ModelService.IN_PARAM, arguments);
+ } catch (GenericServiceException e) {
+ Debug.logError(e, MODULE);
+ final ExceptionMapper<GenericServiceException> mapper = getMappers().get().findMapping(e);
+ return mapper.toResponse(e);
+ }
+ ModelService svc = getModelService(dispatcher.getDispatchContext());
+ GenericValue userLogin = (GenericValue) getHttpRequest().getAttribute("userLogin");
+ serviceContext.put("userLogin", userLogin);
+ Map<String, Object> result = null;
+ try {
+ result = dispatcher.runSync(service, serviceContext);
+ } catch (GenericServiceException e) {
+ Debug.logError(e, MODULE);
+ final ExceptionMapper<GenericServiceException> mapper = getMappers().get().findMapping(e);
+ return mapper.toResponse(e);
+ }
+ if (ServiceUtil.isSuccess(result)) {
+ Map<String, Object> responseData = ServiceRequestWorker.extractResponseData(svc, result);
+ return RestApiUtil.success((String) result.get(ModelService.SUCCESS_MESSAGE), responseData);
+ }
+ return RestApiUtil.buildErrorFromServiceResult(service, result, getHttpRequest().getLocale());
+ }
+
+ private ModelService getModelService(DispatchContext dispatchContext) {
+ ModelService svc = null;
+ try {
+ svc = dispatchContext.getModelService(service);
+ } catch (GenericServiceException gse) {
+ throw new NotFoundException(gse.getMessage());
+ }
+ return svc;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/ApiRootResource.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/ApiRootResource.java
new file mode 100644
index 0000000000..4619124e2d
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/ApiRootResource.java
@@ -0,0 +1,120 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.resources;
+
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+import org.glassfish.jersey.server.model.Resource;
+import org.glassfish.jersey.server.model.ResourceMethod;
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+@Path("/")
+@SuppressWarnings({"unchecked", "rawtypes"})
+public class ApiRootResource {
+
+ /**
+ * Returns a JSON document describing all available REST resources in the
+ * current application.
+ *
+ * <p>The output includes each resource path and the HTTP methods supported
+ * by each endpoint.</p>
+ *
+ * @param application the JAX-RS application containing registered classes
+ * @param request the current HTTP servlet request, used to determine the base URL
+ * @return a JSON response containing all discovered REST resources
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response listAllResources(@Context Application application, @Context HttpServletRequest request) {
+ String basePath = request.getRequestURL().toString();
+
+ ObjectNode root = JsonNodeFactory.instance.objectNode();
+ ArrayNode resources = JsonNodeFactory.instance.arrayNode();
+ root.set("resources", resources);
+ for (Class<?> aClass : application.getClasses()) {
+ if (isAnnotatedResourceClass(aClass)) {
+ Resource resource = Resource.from(aClass);
+ ObjectNode resourceNode = JsonNodeFactory.instance.objectNode();
+ String uriPrefix = resource.getPath();
+ for (ResourceMethod srm : resource.getResourceMethods()) {
+ addTo(resourceNode, uriPrefix, srm, joinUri(basePath, uriPrefix));
+ }
+ resources.add(resourceNode);
+ }
+ }
+ return RestApiUtil.success("OFBiz Resources.", root);
+ }
+
+ private void addTo(ObjectNode resourceNode, String uriPrefix, ResourceMethod srm, String path) {
+ if (resourceNode.get(uriPrefix) == null) {
+ ObjectNode inner = JsonNodeFactory.instance.objectNode();
+ inner.put("path", path);
+ inner.set("verbs", JsonNodeFactory.instance.arrayNode());
+ resourceNode.set(uriPrefix, inner);
+ }
+ ArrayNode arrayNode = (ArrayNode) resourceNode.get(uriPrefix).get("verbs");
+ arrayNode.add(srm.getHttpMethod());
+ }
+
+ private boolean isAnnotatedResourceClass(Class rc) {
+ if (rc.isAnnotationPresent(Path.class)) {
+ return true;
+ }
+ for (Class i : rc.getInterfaces()) {
+ if (i.isAnnotationPresent(Path.class)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Joins multiple URI path segments into a single normalized URI.
+ *
+ * <p>This method ensures that duplicate or missing slashes between segments
+ * are handled correctly.</p>
+ *
+ * @param parts the URI segments to join
+ * @return the combined and normalized URI string
+ */
+ public static String joinUri(String... parts) {
+ StringBuilder result = new StringBuilder();
+ for (String part : parts) {
+ if (result.length() > 0 && result.charAt(result.length() - 1) == '/') {
+ result.setLength(result.length() - 1);
+ }
+ if (result.length() > 0 && !part.startsWith("/")) {
+ result.append('/');
+ }
+ result.append(part);
+ }
+ return result.toString();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java
new file mode 100644
index 0000000000..f0fffab9b3
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java
@@ -0,0 +1,146 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.resources;
+
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.util.EntityUtilProperties;
+import org.apache.ofbiz.webapp.control.JWTManager;
+import org.apache.ofbiz.ws.rs.annotation.AuthToken;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.enums.ParameterIn;
+import io.swagger.v3.oas.annotations.security.SecurityRequirement;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+
+@Path("/auth")
+@Tag(name = "Authentication Token Generating Resource", description = "Intended to provide generation of authentication tokens.")
+public class AuthenticationResource {
+
+ @Context
+ private ServletContext servletContext;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ @Context
+ private HttpServletResponse httpResponse;
+
+ /**
+ * Generates a JWT access token and refresh token for authenticated users.
+ *
+ * <p>This endpoint uses Basic Authentication credentials to authenticate the
+ * user and issues a signed JWT token that can be used for subsequent API
+ * requests. A refresh token is also generated to allow renewal of the access
+ * token without re-authentication.</p>
+ *
+ * <p><b>Security:</b> This operation requires HTTP Basic Authentication and is
+ * protected by {@code @AuthToken}.</p>
+ *
+ * <p>The method retrieves the current {@code Delegator} and dispatcher from the
+ * servlet context and expects a resolved {@code userLogin} attribute on the
+ * HTTP request.</p>
+ *
+ * @param creds the HTTP Authorization header containing Basic Authentication credentials
+ * @return a JSON response containing:
+ * <ul>
+ * <li>{@code access_token} - the JWT access token</li>
+ * <li>{@code refresh_token} - token used to obtain new access tokens</li>
+ * <li>{@code expires_in} - token expiration time in seconds</li>
+ * <li>{@code token_type} - token type (Bearer)</li>
+ * </ul>
+ */
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/token")
+ @AuthToken
+ @Operation(security = @SecurityRequirement(name = "basicAuth"),
+ operationId = "getAuthToken", description = "Generates JWT token for subsequent API calles.")
+ public Response getAuthToken(@Parameter(in = ParameterIn.HEADER, name = "Authorization",
+ description = "Authorization header using Basic Authentication", example = HttpHeaders.AUTHORIZATION + ": Basic YWRtaW46b2ZiaXo=")
+ @HeaderParam(HttpHeaders.AUTHORIZATION) String creds) {
+ Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
+ httpRequest.setAttribute("delegator", delegator);
+ httpRequest.setAttribute("dispatcher", servletContext.getAttribute("dispatcher"));
+ GenericValue userLogin = (GenericValue) httpRequest.getAttribute("userLogin");
+ //TODO : Move this into an OFBiz service. All such implementations should be inside an OFBiz service.
+ String jwtToken = JWTManager.createJwt(delegator,
+ UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")));
+ String refreshToken = JWTManager.createRefreshToken(delegator, userLogin.getString("userLoginId"));
+
+ Map<String, Object> tokenPayload = UtilMisc.toMap("access_token", jwtToken, "refresh_token", refreshToken,
+ "expires_in", EntityUtilProperties.getPropertyValue("security", "security.jwt.token.expireTime", "1800", delegator),
+ "token_type", "Bearer");
+ return RestApiUtil.success("Token granted.", tokenPayload);
+ }
+
+ /**
+ * Generates a new access token using a refresh token.
+ * <p>
+ * Subclasses overriding this method should ensure they call the parent implementation
+ * or handle JWT validation and token generation securely.
+ * </p>
+ *
+ * @param refreshToken The refresh token provided in the request header.
+ * @return A response containing the new access and refresh tokens.
+ ]*/
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/refresh-token")
+ @Operation(description = "Generates a new access token using a refresh token.")
+ public Response refreshToken(@HeaderParam("Refresh-Token") String refreshToken) {
+
+ Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
+ httpRequest.setAttribute("delegator", delegator);
+ httpRequest.setAttribute("dispatcher", delegator);
+ Map<String, Object> claims = JWTManager.validateRefreshToken(delegator, refreshToken);
+
+ // Fetch delegator, dispatcher, and userLogin
+ if (claims.containsKey("errorMessage")) {
+ System.out.println("Error with JWT token: ");
+ }
+
+ String userLoginId = (String) claims.get("userLoginId");
+
+ String newAccessToken = JWTManager.createJwt(delegator, UtilMisc.toMap("userLoginId", userLoginId));
+ String newRefreshToken = JWTManager.createRefreshToken(delegator, userLoginId);
+
+ Map<String, Object> tokenPayload = UtilMisc.toMap("access_token", newAccessToken, "refresh_token", newRefreshToken, "expires_in",
+ EntityUtilProperties.getPropertyValue("security", "security.jwt.token.expireTime", "1800", delegator), "token_type", "Bearer");
+
+ return RestApiUtil.success("Token refreshed.", tokenPayload);
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java
new file mode 100644
index 0000000000..44cd5f2eaa
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java
@@ -0,0 +1,237 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.resources;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.service.DispatchContext;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.ws.rs.ApiServiceRequest;
+import org.apache.ofbiz.ws.rs.ServiceRequestProcessor;
+import org.apache.ofbiz.ws.rs.annotation.Secured;
+import org.apache.ofbiz.ws.rs.annotation.ServiceRequestValidator;
+import org.apache.ofbiz.ws.rs.response.Success;
+
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.PATCH;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.Link;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+
+@Secured
+@Path(OFBizServiceResource.BASE_PATH)
+@ServiceRequestValidator
+public class OFBizServiceResource {
+
+ public static final String BASE_PATH = "/services";
+
+ @Context
+ private ServletContext servletContext;
+
+ @Context
+ private UriInfo uriInfo;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ /**
+ * Returns a list of all OFBiz services that are marked as exported and have a valid action.
+ *
+ * <p>Each service entry contains:
+ * <ul>
+ * <li>Service name</li>
+ * <li>Description</li>
+ * <li>Self link for invocation using the configured HTTP method</li>
+ * </ul>
+ *
+ * @return HTTP 200 response containing a JSON payload with available services
+ * @throws GenericServiceException if service model lookup fails
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response serviceList() throws GenericServiceException {
+ LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher");
+ DispatchContext context = dispatcher.getDispatchContext();
+ Set<String> serviceNames = context.getAllServiceNames();
+ List<Map<String, Object>> serviceList = new ArrayList<>();
+ for (String serviceName : serviceNames) {
+ ModelService service = context.getModelService(serviceName);
+ if (service != null && service.isExport() && UtilValidate.isNotEmpty(service.getAction())) {
+ Map<String, Object> serviceMap = new LinkedHashMap<String, Object>();
+ serviceMap.put("name", service.getName());
+ serviceMap.put("description", service.getDescription());
+ Link selfLink = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder().path(service.getName()))
+ .type(service.getAction()).rel("self").build();
+ serviceMap.put("link", selfLink);
+ serviceList.add(serviceMap);
+ }
+ }
+ Success success = new Success(Response.Status.OK.getStatusCode(), Response.Status.OK.getReasonPhrase(),
+ Response.Status.OK.getReasonPhrase(), serviceList);
+ return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity(success).build();
+ }
+
+ /**
+ * Invokes an OFBiz service using HTTP GET semantics.
+ *
+ * <p>Request parameters are provided via query parameters and mapped to service input fields.</p>
+ *
+ * @param serviceRequest wrapper containing input parameters from query string
+ * @param serviceName the name of the OFBiz service to execute
+ * @return response containing the service execution result
+ * @throws IOException if request processing fails
+ * @throws GenericServiceException if service execution fails
+ */
+ @GET
+ @Path("/{serviceName}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @Secured
+ public Response doGet(@QueryParam(value = "inParams") ApiServiceRequest serviceRequest,
+ @PathParam(value = "serviceName") String serviceName) throws IOException, GenericServiceException {
+ ServiceRequestProcessor processor = new ServiceRequestProcessor();
+ return processor.process(UtilMisc.toMap("serviceName", serviceName, "httpVerb", HttpMethod.GET, "requestMap",
+ serviceRequest.getInParams(), "dispatcher", servletContext.getAttribute("dispatcher"), "request", httpRequest));
+ }
+
+ /**
+ * Invokes an OFBiz service using HTTP POST semantics.
+ *
+ * <p>The request body must contain a JSON object representing service input parameters.</p>
+ *
+ * @param serviceInParams JSON payload mapped to service input parameters
+ * @param serviceName the name of the OFBiz service to execute
+ * @return response containing the service execution result
+ * @throws IOException if request processing fails
+ * @throws GenericEntityException if entity processing fails
+ * @throws GenericServiceException if service execution fails
+ */
+ @POST
+ @Path("/{serviceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response doPost(HashMap<String, Object> serviceInParams,
+ @PathParam(value = "serviceName") String serviceName)
+ throws IOException, GenericEntityException, GenericServiceException {
+ return processBodyRequest(serviceName, HttpMethod.POST, serviceInParams);
+ }
+
+ /**
+ * Invokes an OFBiz service using HTTP PUT semantics.
+ *
+ * <p>The request body replaces the full input set for the service invocation.</p>
+ *
+ * @param serviceInParams JSON payload mapped to service input parameters
+ * @param serviceName the name of the OFBiz service to execute
+ * @return response containing the service execution result
+ * @throws IOException if request processing fails
+ * @throws GenericEntityException if entity processing fails
+ * @throws GenericServiceException if service execution fails
+ */
+ @PUT
+ @Path("/{serviceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response doPut(HashMap<String, Object> serviceInParams, @PathParam(value = "serviceName") String serviceName)
+ throws IOException, GenericEntityException, GenericServiceException {
+ return processBodyRequest(serviceName, HttpMethod.PUT, serviceInParams);
+ }
+
+ /**
+ * Invokes an OFBiz service using HTTP PATCH semantics.
+ *
+ * <p>The request body contains partial updates to be applied as service input parameters.</p>
+ *
+ * @param serviceInParams JSON payload containing partial service input parameters
+ * @param serviceName the name of the OFBiz service to execute
+ * @return response containing the service execution result
+ * @throws IOException if request processing fails
+ * @throws GenericEntityException if entity processing fails
+ * @throws GenericServiceException if service execution fails
+ */
+ @PATCH
+ @Path("/{serviceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response doPatch(HashMap<String, Object> serviceInParams,
+ @PathParam(value = "serviceName") String serviceName)
+ throws IOException, GenericEntityException, GenericServiceException {
+ return processBodyRequest(serviceName, HttpMethod.PATCH, serviceInParams);
+ }
+
+ /**
+ * Invokes an OFBiz service using HTTP DELETE semantics.
+ *
+ * <p>The request body contains parameters required to identify or remove the target resource.</p>
+ *
+ * @param serviceInParams JSON payload mapped to service input parameters
+ * @param serviceName the name of the OFBiz service to execute
+ * @return response containing the service execution result
+ * @throws IOException if request processing fails
+ * @throws GenericEntityException if entity processing fails
+ * @throws GenericServiceException if service execution fails
+ */
+ @DELETE
+ @Path("/{serviceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response doDelete(HashMap<String, Object> serviceInParams,
+ @PathParam(value = "serviceName") String serviceName)
+ throws IOException, GenericEntityException, GenericServiceException {
+ return processBodyRequest(serviceName, HttpMethod.DELETE, serviceInParams);
+ }
+
+ private Response processBodyRequest(String serviceName, String httpVerb, HashMap<String, Object> serviceInParams)
+ throws IOException, GenericEntityException, GenericServiceException {
+ if (UtilValidate.isEmpty(serviceInParams)) {
+ throw new BadRequestException("The request body is missing.");
+ }
+ ServiceRequestProcessor processor = new ServiceRequestProcessor();
+ return processor.process(UtilMisc.toMap(
+ "serviceName", serviceName,
+ "httpVerb", httpVerb,
+ "requestMap", serviceInParams,
+ "dispatcher", servletContext.getAttribute("dispatcher"),
+ "request", httpRequest));
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java
new file mode 100644
index 0000000000..408bcbcc31
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java
@@ -0,0 +1,160 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.resources;
+
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.ws.rs.openapi.OFBizOpenApiReader;
+import org.apache.ofbiz.ws.rs.openapi.OFBizResourceScanner;
+
+import io.swagger.v3.core.util.Json;
+import io.swagger.v3.core.util.Yaml;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.integration.GenericOpenApiContextBuilder;
+import io.swagger.v3.oas.integration.SwaggerConfiguration;
+import io.swagger.v3.oas.integration.api.OpenApiContext;
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.info.Contact;
+import io.swagger.v3.oas.models.info.Info;
+import io.swagger.v3.oas.models.info.License;
+import io.swagger.v3.oas.models.security.SecurityScheme;
+import io.swagger.v3.oas.models.servers.Server;
+import jakarta.servlet.ServletConfig;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+
+@Path("/openapi.{type:json|yaml}")
+public final class OpenApiResource {
+ @Context
+ private ServletConfig config;
+
+ @Context
+ private ServletContext context;
+
+ @Context
+ private HttpServletRequest request;
+
+ @Context
+ private Application app;
+
+ /**
+ * Generates the OpenAPI specification for OFBiz REST resources.
+ *
+ * <p>This endpoint dynamically builds the OpenAPI document by scanning all
+ * JAX-RS resources in the configured package and applying OFBiz-specific
+ * OpenAPI readers and scanners.</p>
+ *
+ * <p>The generated specification includes configured security schemes for:
+ * <ul>
+ * <li>JWT Bearer token authentication</li>
+ * <li>HTTP Basic authentication</li>
+ * </ul>
+ *
+ * <p>The response format can be returned as either JSON or YAML depending on
+ * the requested type.</p>
+ *
+ * <p>This endpoint is marked as hidden in OpenAPI documentation to avoid
+ * recursive self-inclusion in the generated spec.</p>
+ *
+ * @param headers HTTP headers of the request (currently unused but available for extensions)
+ * @param uriInfo URI context of the request
+ * @param type optional response format selector ("yaml" for YAML output, otherwise JSON)
+ * @return the generated OpenAPI specification in JSON or YAML format
+ * @throws Exception if OpenAPI generation or serialization fails
+ */
+ @GET
+ @Produces({MediaType.APPLICATION_JSON, "application/yaml"})
+ @Operation(hidden = true)
+ public Response getOpenApi(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type)
+ throws Exception {
+ OpenAPI openApi = new OpenAPI();
+ openApi.addServersItem(buildOpenApiServer());
+
+ SecurityScheme securitySchemeBearer = new SecurityScheme();
+ securitySchemeBearer.setName("jwtToken");
+ securitySchemeBearer.setType(SecurityScheme.Type.HTTP);
+ securitySchemeBearer.setScheme("bearer");
+ securitySchemeBearer.bearerFormat("JWT");
+ openApi.schemaRequirement(securitySchemeBearer.getName(), securitySchemeBearer);
+
+ SecurityScheme basicAuthScheme = new SecurityScheme();
+ basicAuthScheme.setName("basicAuth");
+ basicAuthScheme.setType(SecurityScheme.Type.HTTP);
+ basicAuthScheme.setScheme("basic");
+ openApi.schemaRequirement(basicAuthScheme.getName(), basicAuthScheme);
+
+
+ SwaggerConfiguration config = new SwaggerConfiguration().openAPI(openApi.info(buildOpenApiInfo()))
+ .readerClass(OFBizOpenApiReader.class.getName())
+ .resourcePackages(Stream.of("org.apache.ofbiz.ws.rs.resources").collect(Collectors.toSet()))
+ .scannerClass(OFBizResourceScanner.class.getName());
+
+
+ OpenApiContext ctx = new GenericOpenApiContextBuilder<>().openApiConfiguration(config)
+ .buildContext(true);
+
+ openApi = ctx.read();
+
+ if (UtilValidate.isNotEmpty(type) && type.trim().equalsIgnoreCase("yaml")) {
+ return Response.status(Response.Status.OK)
+ .entity(Yaml.mapper().writeValueAsString(openApi))
+ .type("application/yaml").build();
+ }
+ return Response.status(Response.Status.OK)
+ .entity(Json.mapper().writeValueAsString(openApi))
+ .type(MediaType.APPLICATION_JSON_TYPE).build();
+ }
+
+
+ private Info buildOpenApiInfo() {
+ Info info = new Info().version("1.0.0").title("OFBiz REST APIs")
+ .description("Open API specification for OFBiz RESTful APIs.").contact(buildOpenApiContact())
+ .termsOfService("http://www.apache.org/licenses/LICENSE-2.0.html")
+ .license(new License()
+ .name("Apache 2.0")
+ .url("http://www.apache.org/licenses/LICENSE-2.0.txt"));
+
+ return info;
+ }
+
+ private Contact buildOpenApiContact() {
+ Contact contact = new Contact().name("OFBiz DEV API Team").email("dev@ofbiz.apache.org")
+ .url("https://ofbiz.apache.org/");
+ return contact;
+ }
+
+ private Server buildOpenApiServer() {
+ Server serverItem =
+ new Server().url(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath())
+ .description("Server Hosting the REST API");
+ return serverItem;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java
new file mode 100644
index 0000000000..0f363d81fd
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java
@@ -0,0 +1,251 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.response;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.annotation.JsonRootName;
+
+@JsonRootName(value = "error")
+@JsonPropertyOrder({ "statusCode", "statusDescription", "errorType", "errorMessage", "errorDescription",
+ "additionalErrors" })
+public class Error {
+
+ private int statusCode;
+ private String statusDescription;
+ private String errorMessage;
+ @JsonProperty("errorType")
+ private String type;
+ @JsonProperty("errorDescription")
+ private String errorDesc;
+ private List<String> additionalErrors;
+
+ /**
+ * Creates an empty error response.
+ */
+ public Error() {
+ }
+
+ /**
+ * Creates an error response with basic status and message information.
+ *
+ * @param statusCode HTTP status code
+ * @param statusDescription HTTP status reason phrase or description
+ * @param errorMessage human-readable error message
+ */
+ public Error(int statusCode, String statusDescription, String errorMessage) {
+ this.statusCode = statusCode;
+ this.statusDescription = statusDescription;
+ this.errorMessage = errorMessage;
+ }
+
+ /**
+ * Creates an error response with additional error details.
+ *
+ * @param statusCode HTTP status code
+ * @param statusDescription HTTP status reason phrase or description
+ * @param errorMessage human-readable error message
+ * @param additionalErrors list of additional validation or processing errors
+ */
+ public Error(int statusCode, String statusDescription, String errorMessage, List<String> additionalErrors) {
+ this.statusCode = statusCode;
+ this.statusDescription = statusDescription;
+ this.errorMessage = errorMessage;
+ this.additionalErrors = additionalErrors;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error code(int statusCode) {
+ this.statusCode = statusCode;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error description(String statusDescription) {
+ this.statusDescription = statusDescription;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error message(String errorMessage) {
+ this.errorMessage = errorMessage;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error type(String type) {
+ this.type = type;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error statusCode(int statusCode) {
+ this.statusCode = statusCode;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error additionalErrors(List<String> additionalErrors) {
+ this.additionalErrors = additionalErrors;
+ return this;
+ }
+
+ /**
+ * Fluent builder methods for constructing an {@code Error} response.
+ *
+ * <p>These methods allow chaining to populate error metadata in a concise way.
+ * Each method sets a field and returns the same {@code Error} instance.</p>
+ */
+ public Error errorDesc(String errorDesc) {
+ this.setErrorDesc(errorDesc);
+ return this;
+ }
+
+ /**
+ * Returns the status code.
+ *
+ * @return the HTTP or application status code
+ */
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ /**
+ * Returns the type.
+ *
+ * @return the type value
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Sets the status code.
+ *
+ * @param statusCode the status code to set
+ */
+ public void setStatusCode(int statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ /**
+ * Returns the status description.
+ *
+ * @return the status description
+ */
+ public String getStatusDescription() {
+ return statusDescription;
+ }
+
+ /**
+ * Sets the status description.
+ *
+ * @param statusDescription the status description to set
+ */
+ public void setStatusDescription(String statusDescription) {
+ this.statusDescription = statusDescription;
+ }
+
+ /**
+ * Returns the error message.
+ *
+ * @return the error message
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ /**
+ * Sets the error message.
+ *
+ * @param errorMessage the error message to set
+ */
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ /**
+ * Returns the list of additional errors.
+ *
+ * @return list of additional error messages
+ */
+ public List<String> getAdditionalErrors() {
+ return additionalErrors;
+ }
+
+ /**
+ * Sets the list of additional errors.
+ *
+ * @param additionalErrors the additional errors to set
+ */
+ public void setAdditionalErrors(List<String> additionalErrors) {
+ this.additionalErrors = additionalErrors;
+ }
+
+ /**
+ * Returns the error description.
+ *
+ * @return the error description
+ */
+ public String getErrorDesc() {
+ return errorDesc;
+ }
+
+ /**
+ * Sets the error description.
+ *
+ * @param errorDesc the error description to set
+ */
+ public void setErrorDesc(String errorDesc) {
+ this.errorDesc = errorDesc;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Success.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Success.java
new file mode 100644
index 0000000000..f01b775c75
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/response/Success.java
@@ -0,0 +1,120 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.response;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import com.fasterxml.jackson.annotation.JsonRootName;
+
+@JsonRootName(value = "success")
+@JsonInclude(Include.NON_NULL)
+public class Success {
+ private int statusCode;
+ private String statusDescription;
+ private String successMessage;
+ private Object data;
+
+ /**
+ * Creates a success response with basic status and message information.
+ *
+ * @param statusCode HTTP status code
+ * @param statusDescription HTTP status reason phrase or description
+ * @param successMessage human-readable success message
+ * @param data
+ */
+ public Success(int statusCode, String statusDescription, String successMessage, Object data) {
+ this.statusCode = statusCode;
+ this.statusDescription = statusDescription;
+ this.successMessage = successMessage;
+ this.data = data;
+ }
+
+ /**
+ * Returns the status code.
+ *
+ * @return the status code representing the result
+ */
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ /**
+ * Sets the status code.
+ *
+ * @param statusCode the status code to set
+ */
+ public void setStatusCode(int statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ /**
+ * Returns the status description.
+ *
+ * @return the status description
+ */
+ public String getStatusDescription() {
+ return statusDescription;
+ }
+
+ /**
+ * Sets the status description.
+ *
+ * @param statusDescription the status description to set
+ */
+ public void setStatusDescription(String statusDescription) {
+ this.statusDescription = statusDescription;
+ }
+
+ /**
+ * Returns the success message.
+ *
+ * @return the success message
+ */
+ public String getSuccessMessage() {
+ return successMessage;
+ }
+
+ /**
+ * Sets the success message.
+ *
+ * @param successMessage the success message to set
+ */
+ public void setSuccessMessage(String successMessage) {
+ this.successMessage = successMessage;
+ }
+
+ /**
+ * Returns the response data.
+ *
+ * @return the data object
+ */
+ public Object getData() {
+ return data;
+ }
+
+ /**
+ * Sets the response data.
+ *
+ * @param data the data object to set
+ */
+ public void setData(Object data) {
+ this.data = data;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java
new file mode 100644
index 0000000000..b273a4c0fd
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java
@@ -0,0 +1,164 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.security.auth;
+
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.util.EntityQuery;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.webapp.control.JWTManager;
+import org.apache.ofbiz.ws.rs.annotation.Secured;
+import org.apache.ofbiz.ws.rs.common.AuthenticationScheme;
+import org.apache.ofbiz.ws.rs.resources.OFBizServiceResource;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+
+import jakarta.annotation.Priority;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.ResourceInfo;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+import jakarta.ws.rs.ext.Provider;
+
+/**
+ * JAX-RS container request filter that enforces JWT Bearer token authentication
+ * on all resources annotated with {@link Secured}.
+ *
+ * <p>For requests targeting {@link OFBizServiceResource}, authentication may be
+ * skipped if the underlying OFBiz service has {@code auth=false} in its service
+ * definition and no {@code Authorization} header is present. If a token is
+ * present regardless, it is always validated.</p>
+ *
+ * <p>On successful validation, the resolved {@link GenericValue} userLogin is
+ * stored as a request attribute under {@code "userLogin"} for use by downstream
+ * resource methods. On failure, the request is aborted with HTTP 401 Unauthorized.
+ * If no {@code Authorization} header was present, a
+ * {@code WWW-Authenticate: Bearer realm="OFBiz"} challenge header is included
+ * in the response.</p>
+ *
+ * @see Secured
+ * @see HttpBasicAuthFilter
+ */
+@Secured
+@Provider
+@Priority(Priorities.AUTHORIZATION)
+public class APIAuthFilter implements ContainerRequestFilter {
+
+ private static final String MODULE = APIAuthFilter.class.getName();
+
+ @Context
+ private UriInfo uriInfo;
+
+ @Context
+ private ResourceInfo resourceInfo;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ @Context
+ private ServletContext servletContext;
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
+ if (isServiceResource()) {
+ String service = (String) RestApiUtil.extractParams(uriInfo.getPathParameters()).get("serviceName");
+ if (UtilValidate.isNotEmpty(service)) {
+ ModelService mdService = null;
+ try {
+ mdService = ((LocalDispatcher) servletContext.getAttribute("dispatcher")).getDispatchContext().getModelService(service);
+ } catch (GenericServiceException e) {
+ Debug.logError(e.getMessage(), MODULE);
+ }
+ // Skip auth for services auth=false in service definition and if Authorization header is absent
+ // Still validate the token if it is present even if service being called is auth=false
+ if (mdService != null && !mdService.isAuth() && authorizationHeader == null) {
+ return;
+ }
+ }
+ }
+ Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
+ if (!isTokenBasedAuthentication(authorizationHeader)) {
+ abortWithUnauthorized(requestContext, false, "Unauthorized: Access is denied due to invalid or absent Authorization header.");
+ return;
+ }
+ String jwtToken = JWTManager.getHeaderAuthBearerToken(httpRequest);
+ Map<String, Object> claims = JWTManager.validateToken(delegator, jwtToken);
+ if (claims.containsKey(ModelService.ERROR_MESSAGE)) {
+ abortWithUnauthorized(requestContext, true, "Unauthorized: " + (String) claims.get(ModelService.ERROR_MESSAGE));
+ } else {
+ GenericValue userLogin = extractUserLoginFromJwtClaim(delegator, claims);
+ httpRequest.setAttribute("userLogin", userLogin);
+ }
+ }
+
+ private boolean isTokenBasedAuthentication(String authorizationHeader) {
+ return authorizationHeader != null
+ && authorizationHeader.toLowerCase().startsWith(AuthenticationScheme.BEARER.getScheme().toLowerCase() + " ");
+ }
+
+ private void abortWithUnauthorized(ContainerRequestContext requestContext, boolean isAuthHeaderPresent, String message) {
+ if (!isAuthHeaderPresent) {
+ requestContext.abortWith(
+ RestApiUtil.errorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), Response.Status.UNAUTHORIZED.getReasonPhrase(), message)
+ .header(HttpHeaders.WWW_AUTHENTICATE,
+ AuthenticationScheme.BEARER.getScheme() + " realm=\"" + AuthenticationScheme.REALM + "\"").build());
+ } else {
+ requestContext
+ .abortWith(RestApiUtil.error(Response.Status.UNAUTHORIZED.getStatusCode(), Response.Status.UNAUTHORIZED.getReasonPhrase(), message));
+ }
+
+ }
+
+ private GenericValue extractUserLoginFromJwtClaim(Delegator delegator, Map<String, Object> claims) {
+ String userLoginId = (String) claims.get("userLoginId");
+ if (UtilValidate.isEmpty(userLoginId)) {
+ Debug.logWarning("No userLoginId found in the JWT token.", MODULE);
+ return null;
+ }
+ GenericValue userLogin = null;
+ try {
+ userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
+ if (UtilValidate.isEmpty(userLogin)) {
+ Debug.logWarning("There was a problem with the JWT token. Could not find provided userLogin " + userLoginId, MODULE);
+ }
+ } catch (GenericEntityException e) {
+ Debug.logError(e, "Unable to get UserLogin information from JWT Token: " + e.getMessage(), MODULE);
+ }
+ return userLogin;
+ }
+
+ private boolean isServiceResource() {
+ return OFBizServiceResource.class.isAssignableFrom(resourceInfo.getResourceClass());
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APICorsFilter.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APICorsFilter.java
new file mode 100644
index 0000000000..96b510b8e1
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APICorsFilter.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.security.auth;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+
+import jakarta.annotation.Priority;
+import jakarta.ws.rs.HttpMethod;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.container.ContainerResponseFilter;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.Provider;
+
+import org.apache.catalina.filters.CorsFilter;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilValidate;
+
+/**
+ * Read https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more details
+ */
+
+@Provider
+@Priority(Priorities.HEADER_DECORATOR)
+public class APICorsFilter implements ContainerResponseFilter {
+
+ // check security.properties file for 'cors.origins.allowed'
+ private static final List<String> ALLOWED_CORS_ORIGINS = UtilMisc.getCorsOriginsAllowed();
+
+ @Override
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
+ throws IOException {
+ MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders();
+
+ if (UtilValidate.isNotEmpty(ALLOWED_CORS_ORIGINS)) {
+ String origin = requestContext.getHeaderString(CorsFilter.REQUEST_HEADER_ORIGIN);
+ if (UtilValidate.isNotEmpty(origin) && ALLOWED_CORS_ORIGINS.contains(origin)) {
+ responseHeaders.add(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin);
+ // Vary: Origin is required when the response varies by origin, so that
+ // caches do not serve a response for one origin to a different origin.
+ responseHeaders.add("Vary", "Origin");
+ }
+ // Requests from unlisted origins receive no Access-Control-Allow-Origin header,
+ // which causes the browser to block the response.
+ }
+
+ // credentials support is enabled per default
+ responseHeaders.add(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
+
+ // publish supported request header field names
+ responseHeaders.addAll(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS,
+ Arrays.asList(HttpHeaders.CONTENT_TYPE, HttpHeaders.AUTHORIZATION));
+
+ // inform about all the supported methods. Itemize these due to the lack of support for the wildcard (*)
+ // in few browsers, e.g. in 'Safari' resp. 'FF for Android'
+ responseHeaders.addAll(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS,
+ Arrays.asList(HttpMethod.GET, HttpMethod.PATCH,
+ HttpMethod.PUT, HttpMethod.POST,
+ HttpMethod.DELETE, HttpMethod.OPTIONS));
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java
new file mode 100644
index 0000000000..74585dff23
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java
@@ -0,0 +1,130 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.security.auth;
+
+import java.io.IOException;
+import java.util.Base64;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilHttp;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.LocalDispatcher;
+import org.apache.ofbiz.service.ServiceUtil;
+import org.apache.ofbiz.ws.rs.annotation.AuthToken;
+import org.apache.ofbiz.ws.rs.common.AuthenticationScheme;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.ForbiddenException;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.ResourceInfo;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.Provider;
+
+
+@AuthToken
+@Provider
+public class HttpBasicAuthFilter implements ContainerRequestFilter {
+
+ private static final String MODULE = HttpBasicAuthFilter.class.getName();
+
+ @Context
+ private ResourceInfo resourceInfo;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ @Context
+ private ServletContext servletContext;
+
+ private static final String REALM = "OFBiz";
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Validates the {@code Authorization} header as HTTP Basic Auth by
+ * decoding the Base64 credentials and authenticating the username and
+ * password against OFBiz user logins.</p>
+ *
+ * <p>Aborts with HTTP 401 Unauthorized if the header is absent or not
+ * Basic Auth. Aborts with HTTP 401 if authentication fails with a
+ * {@link ForbiddenException}. On success, the request proceeds to the
+ * token issuance endpoint.</p>
+ */
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
+ if (!isBasicAuth(authorizationHeader)) {
+ abortWithUnauthorized(requestContext, false, "Unauthorized: Access is denied due to invalid or absent Authorization header");
+ return;
+ }
+ String[] tokens = (new String(Base64.getDecoder().decode(authorizationHeader.split(" ")[1]), "UTF-8")).split(":");
+ final String username = tokens[0];
+ final String password = tokens[1];
+ try {
+ authenticate(username, password);
+ } catch (ForbiddenException fe) {
+ abortWithUnauthorized(requestContext, true, "Access Denied: " + fe.getMessage());
+ }
+
+ }
+
+ private boolean isBasicAuth(String authorizationHeader) {
+ return authorizationHeader != null
+ && authorizationHeader.toLowerCase().startsWith(AuthenticationScheme.BASIC.getScheme().toLowerCase() + " ");
+ }
+
+ private void abortWithUnauthorized(ContainerRequestContext requestContext, boolean isAuthHeaderPresent, String message) {
+ if (!isAuthHeaderPresent) {
+ requestContext.abortWith(
+ RestApiUtil.errorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), Response.Status.UNAUTHORIZED.getReasonPhrase(), message)
+ .header(HttpHeaders.WWW_AUTHENTICATE, AuthenticationScheme.BASIC.getScheme() + " realm=\"" + REALM + "\"").build());
+ } else {
+ requestContext
+ .abortWith(RestApiUtil.error(Response.Status.FORBIDDEN.getStatusCode(), Response.Status.FORBIDDEN.getReasonPhrase(), message));
+ }
+ }
+
+ private void authenticate(String userName, String password) throws ForbiddenException {
+ Map<String, Object> result = null;
+ LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher");
+ try {
+ result = dispatcher.runSync("userLogin",
+ UtilMisc.toMap("login.username", userName, "login.password", password, "locale", UtilHttp.getLocale(httpRequest)));
+ } catch (GenericServiceException e) {
+ Debug.logError(e, "Error calling userLogin service", MODULE);
+ throw new ForbiddenException(e.getMessage());
+ }
+ if (!ServiceUtil.isSuccess(result)) {
+ Debug.logError(ServiceUtil.getErrorMessage(result), MODULE);
+ throw new ForbiddenException(ServiceUtil.getErrorMessage(result));
+ }
+
+ GenericValue userLogin = (GenericValue) result.get("userLogin");
+ httpRequest.setAttribute("userLogin", userLogin);
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/services/RestServices.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/services/RestServices.java
new file mode 100644
index 0000000000..ec8f41f70c
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/services/RestServices.java
@@ -0,0 +1,72 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.services;
+
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.GenericValue;
+import org.apache.ofbiz.entity.util.EntityUtilProperties;
+import org.apache.ofbiz.service.DispatchContext;
+import org.apache.ofbiz.service.ServiceUtil;
+import org.apache.ofbiz.webapp.control.JWTManager;
+
+public final class RestServices {
+
+ private static final String MODULE = RestServices.class.getName();
+
+ private RestServices() { }
+
+ /**
+ * Generates a JWT authentication token for the currently logged-in user.
+ *
+ * <p>This service creates a signed JWT token based on the provided
+ * {@code userLoginId}. The token can be used for authenticated REST
+ * API access.</p>
+ *
+ * <p>The token expiration time is retrieved from the security properties
+ * configuration ({@code security.jwt.token.expireTime}).</p>
+ *
+ * @param ctx the service execution context providing access to Delegator and environment
+ * @param context input parameters map containing:
+ * <ul>
+ * <li>{@code userLogin} - the authenticated user login entity</li>
+ * </ul>
+ * @return a service success response map containing:
+ * <ul>
+ * <li>{@code access_token} - generated JWT token</li>
+ * <li>{@code expires_in} - token validity duration in seconds</li>
+ * <li>{@code token_type} - token type ("Bearer")</li>
+ * </ul>
+ */
+ public static Map<String, Object> generateAuthToken(DispatchContext ctx, Map<String, Object> context) {
+ Delegator delegator = ctx.getDelegator();
+ GenericValue userLogin = (GenericValue) context.get("userLogin");
+ String userLoginStr = userLogin.getString("userLoginId");
+ Debug.logInfo("Generating auth token for userLogin: " + userLoginStr, MODULE);
+ String jwtToken = JWTManager.createJwt(delegator, UtilMisc.toMap("userLoginId", userLoginStr));
+ Map<String, Object> success = ServiceUtil.returnSuccess();
+ success.put("access_token", jwtToken);
+ success.put("expires_in", EntityUtilProperties.getPropertyValue("security", "security.jwt.token.expireTime", "1800", delegator));
+ success.put("token_type", "Bearer");
+ return success;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GenericServiceExceptionMapper.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GenericServiceExceptionMapper.java
new file mode 100644
index 0000000000..5c2bfe154c
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GenericServiceExceptionMapper.java
@@ -0,0 +1,126 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.spi.impl;
+
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.entity.GenericEntityException;
+import org.apache.ofbiz.entity.GenericEntityNotFoundException;
+import org.apache.ofbiz.entity.GenericNoSuchEntityException;
+import org.apache.ofbiz.service.GenericServiceException;
+import org.apache.ofbiz.service.ServiceValidationException;
+import org.apache.ofbiz.ws.rs.ServiceNameContextHolder;
+import org.apache.ofbiz.ws.rs.core.ResponseStatus;
+import org.apache.ofbiz.ws.rs.response.Error;
+import org.apache.ofbiz.ws.rs.util.RestApiUtil;
+import org.codehaus.groovy.runtime.InvokerInvocationException;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.Provider;
+
+/**
+ *
+ * Exception Mapper for GenericServiceException. Catches GenericServiceException and handles it and prepares appropriate response.
+ *
+ */
+@Provider
+public class GenericServiceExceptionMapper implements jakarta.ws.rs.ext.ExceptionMapper<GenericServiceException> {
+
+ /**
+ * Module Name Used for debugging
+ */
+ private static final String MODULE = GenericServiceExceptionMapper.class.getName();
+
+ @Context
+ private HttpServletRequest request;
+
+ @Context
+ private ContainerRequestContext crc;
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Unwraps the root cause of the exception and maps it to an appropriate
+ * HTTP error response:</p>
+ * <ul>
+ * <li>{@link ServiceValidationException} → HTTP 400 Bad Request</li>
+ * <li>{@link GenericNoSuchEntityException} or {@link GenericEntityNotFoundException}
+ * → HTTP 500 Internal Server Error</li>
+ * <li>{@link GenericEntityException} → HTTP 422 Unprocessable Entity</li>
+ * <li>Any other cause → HTTP 500 Internal Server Error</li>
+ * </ul>
+ *
+ * <p>{@link InvokerInvocationException} is transparently unwrapped to
+ * expose the underlying cause before mapping.</p>
+ */
+ @Override
+ public Response toResponse(GenericServiceException gse) {
+ Debug.logError(gse.getMessage(), MODULE);
+ Response.ResponseBuilder builder = null;
+ Throwable actualCause = gse.getCause();
+ if (actualCause == null) {
+ actualCause = gse;
+ } else if (actualCause instanceof InvokerInvocationException) {
+ actualCause = actualCause.getCause();
+ }
+ String service = ServiceNameContextHolder.get();
+ if (actualCause instanceof ServiceValidationException) {
+ ServiceValidationException validationException = (ServiceValidationException) actualCause;
+ Error error = new Error().type(actualCause.getClass().getSimpleName())
+ .code(Response.Status.BAD_REQUEST.getStatusCode())
+ .description(Response.Status.BAD_REQUEST.getReasonPhrase())
+ .message(RestApiUtil.getErrorMessage(service, "GenericServiceValidationErrorMessage", request.getLocale()))
+ .errorDesc((validationException.getMessage()))
+ .additionalErrors(validationException.getMessageList());
+ builder = Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(error);
+ } else if (actualCause instanceof GenericNoSuchEntityException
+ || actualCause instanceof GenericEntityNotFoundException) {
+ Error error = new Error().type(actualCause.getClass().getSimpleName())
+ .code(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
+ .description(Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase())
+ .message(RestApiUtil.getErrorMessage(service, "NoSuchEntityDefaultMessage", request.getLocale()))
+ .errorDesc(ExceptionUtils.getRootCauseMessage(gse));
+ builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON)
+ .entity(error);
+ } else if (actualCause instanceof GenericEntityException) {
+ Error error = new Error().type(actualCause.getClass().getSimpleName())
+ .code(ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getStatusCode())
+ .description(ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getReasonPhrase())
+ .message(RestApiUtil.getErrorMessage(service, "GenericServiceExecutionGenericEntityOperationErrorMessage",
+ request.getLocale()))
+ .errorDesc(ExceptionUtils.getRootCauseMessage(gse));
+ builder = Response.status(ResponseStatus.Custom.UNPROCESSABLE_ENTITY).type(MediaType.APPLICATION_JSON)
+ .entity(error);
+ } else {
+ Error error = new Error().type(actualCause.getClass().getSimpleName())
+ .code(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
+ .description(Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase())
+ .message(RestApiUtil.getErrorMessage(service, "GenericServiceExecutionGenericExceptionErrorMessage",
+ request.getLocale()))
+ .errorDesc(ExceptionUtils.getRootCauseMessage(gse));
+ builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON)
+ .entity(error);
+ }
+ return builder.build();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java
new file mode 100644
index 0000000000..3423ae359a
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.spi.impl;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.ws.rs.response.Error;
+
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.Provider;
+
+@Provider
+public class GlobalExceptionMapper implements jakarta.ws.rs.ext.ExceptionMapper<Throwable> {
+
+ private static final String MODULE = GlobalExceptionMapper.class.getName();
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Maps the throwable to an HTTP error response. If the throwable is a
+ * {@link WebApplicationException}, its own HTTP status is used; all other
+ * throwables result in HTTP 500 Internal Server Error.</p>
+ */
+ @Override
+ public Response toResponse(Throwable throwable) {
+ Debug.logError(throwable.getMessage(), MODULE);
+ if (Debug.verboseOn()) {
+ throwable.printStackTrace();
+ }
+ Response.StatusType type = (throwable instanceof WebApplicationException
+ ? ((WebApplicationException) throwable).getResponse().getStatusInfo()
+ : Response.Status.INTERNAL_SERVER_ERROR);
+
+ Error error = new Error(type.getStatusCode(), type.getReasonPhrase(), throwable.getMessage());
+ return Response.status(type.getStatusCode()).entity(error).type(MediaType.APPLICATION_JSON).build();
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java
new file mode 100644
index 0000000000..4fdbba1f15
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.spi.impl;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+
+import jakarta.ws.rs.core.Link;
+import jakarta.ws.rs.ext.ContextResolver;
+import jakarta.ws.rs.ext.Provider;
+
+@Provider
+public class JacksonConfig implements ContextResolver<ObjectMapper> {
+
+ private final ObjectMapper objectMapper;
+
+ /**
+ * Configures the Jackson {@link ObjectMapper} used for JSON serialization
+ * and deserialization in REST responses.
+ *
+ * <p>This configuration applies consistent serialization rules across OFBiz REST APIs,
+ * including:
+ * <ul>
+ * <li>ISO-style date handling (no timestamp serialization)</li>
+ * <li>Ignoring unknown JSON properties during deserialization</li>
+ * <li>Excluding null values from output</li>
+ * <li>Full field visibility for serialization/deserialization</li>
+ * <li>Pretty-printed JSON output</li>
+ * </ul>
+ *
+ * <p>Additionally, custom serializers are registered for REST link representations</p>
+ */
+ public JacksonConfig() {
+ objectMapper = JsonMapper.builder()
+ .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .defaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL))
+ .visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
+ .enable(SerializationFeature.INDENT_OUTPUT)
+ .build();
+ SimpleModule simpleModule = new SimpleModule();
+ simpleModule.addSerializer(Link.class, new LinkSerializer());
+ objectMapper.registerModule(simpleModule);
+ }
+
+ @Override
+ public ObjectMapper getContext(Class<?> type) {
+ return objectMapper;
+ }
+
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java
new file mode 100644
index 0000000000..f32ba01170
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.spi.impl;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.ws.rs.ApiServiceRequest;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.ext.ParamConverter;
+import jakarta.ws.rs.ext.ParamConverterProvider;
+import jakarta.ws.rs.ext.Provider;
+
+@Provider
+public class JsonifiedParamConverterProvider implements ParamConverterProvider {
+
+ private static final String MODULE = JsonifiedParamConverterProvider.class.getName();
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ // TODO: check thread safety and performance
+ private static ObjectMapper getMapper() {
+ return MAPPER;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Returns a {@link ParamConverter} for {@link ApiServiceRequest} that
+ * deserializes a JSON string into an {@link ApiServiceRequest} wrapping
+ * a {@code Map<String, Object>}. Returns {@code null} for all other types,
+ * indicating this provider does not handle them.</p>
+ *
+ * <p>The converter's {@code fromString} method returns an empty
+ * {@link ApiServiceRequest} if the value is absent or empty, and throws
+ * {@link BadRequestException} if the JSON is malformed. The {@code toString}
+ * method delegates to {@link ApiServiceRequest#getInParams()}.</p>
+ */
+ @Override
+ public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
+ if (rawType.getName().equals(ApiServiceRequest.class.getName())) {
+ return new ParamConverter<T>() {
+ @SuppressWarnings("unchecked")
+ @Override
+ public T fromString(String value) {
+ if (UtilValidate.isEmpty(value)) {
+ return (T) new ApiServiceRequest(new HashMap<String, Object>());
+ }
+ Map<String, Object> map = null;
+ try {
+ map = getMapper().readValue(value, new TypeReference<Map<String, Object>>() {
+ });
+ } catch (JsonProcessingException e) {
+ Debug.logError(e.getMessage(), MODULE);
+ throw new BadRequestException("Error parsing JSON, malformed JSON.");
+ }
+ return (T) new ApiServiceRequest(map);
+ }
+
+ @Override
+ public String toString(T map) {
+ return ((ApiServiceRequest) map).getInParams().toString();
+ }
+ };
+ }
+ return null;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java
new file mode 100644
index 0000000000..a348e25f98
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.spi.impl;
+
+import java.io.IOException;
+import java.util.Map.Entry;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+
+import jakarta.ws.rs.core.Link;
+
+public class LinkSerializer extends JsonSerializer<jakarta.ws.rs.core.Link> {
+ static final String HREF_PROPERTY = "href";
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>Serializes the {@link Link} as a JSON object with the URI written
+ * as {@code "href"} and each link parameter written as an additional
+ * string field.</p>
+ */
+ @Override
+ public void serialize(Link link, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+ jsonGenerator.writeStartObject();
+ jsonGenerator.writeStringField(HREF_PROPERTY, link.getUri().toString());
+ for (Entry<String, String> entry : link.getParams().entrySet()) {
+ jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
+ }
+ jsonGenerator.writeEndObject();
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java
new file mode 100644
index 0000000000..588f46de7c
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java
@@ -0,0 +1,469 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.util;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.Debug;
+import org.apache.ofbiz.base.util.UtilMisc;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.entity.Delegator;
+import org.apache.ofbiz.entity.model.ModelEntity;
+import org.apache.ofbiz.entity.model.ModelField;
+import org.apache.ofbiz.service.ModelParam;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.webapp.WebAppUtil;
+import org.apache.ofbiz.ws.rs.common.AuthenticationScheme;
+import org.apache.ofbiz.ws.rs.core.ResponseStatus;
+import org.apache.ofbiz.ws.rs.listener.ApiContextListener;
+
+import io.swagger.v3.oas.models.headers.Header;
+import io.swagger.v3.oas.models.media.ArraySchema;
+import io.swagger.v3.oas.models.media.BooleanSchema;
+import io.swagger.v3.oas.models.media.Content;
+import io.swagger.v3.oas.models.media.DateSchema;
+import io.swagger.v3.oas.models.media.IntegerSchema;
+import io.swagger.v3.oas.models.media.MapSchema;
+import io.swagger.v3.oas.models.media.MediaType;
+import io.swagger.v3.oas.models.media.NumberSchema;
+import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.oas.models.media.StringSchema;
+import io.swagger.v3.oas.models.responses.ApiResponse;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
+
+public final class OpenApiUtil {
+
+ private static final String MODULE = OpenApiUtil.class.getName();
+
+ private OpenApiUtil() {
+
+ }
+
+ private static final Map<String, String> CLASS_ALIAS = new HashMap<>();
+ private static final Map<String, Class<?>> JAVA_OPEN_API_MAP = new HashMap<>();
+ private static final Map<String, String> FIELD_TYPE_MAP = new HashMap<String, String>();
+ private static final Map<String, ApiResponse> RESPONSES = new HashMap<>();
+ private static final Map<String, Schema<?>> SCHEMAS = new HashMap<>();
+
+ static {
+ CLASS_ALIAS.put("String", "String");
+ CLASS_ALIAS.put("java.lang.String", "String");
+ CLASS_ALIAS.put("CharSequence", "String");
+ CLASS_ALIAS.put("java.lang.CharSequence", "String");
+ CLASS_ALIAS.put("Date", "String");
+ CLASS_ALIAS.put("java.sql.Date", "String");
+ CLASS_ALIAS.put("Time", "String");
+ CLASS_ALIAS.put("java.sql.Time", "String");
+ CLASS_ALIAS.put("Timestamp", "Timestamp");
+ CLASS_ALIAS.put("java.sql.Timestamp", "Timestamp");
+ CLASS_ALIAS.put("Integer", "Integer");
+ CLASS_ALIAS.put("java.lang.Integer", "Integer");
+ CLASS_ALIAS.put("Long", "Long");
+ CLASS_ALIAS.put("java.lang.Long", "Long");
+ CLASS_ALIAS.put("BigInteger", "BigInteger");
+ CLASS_ALIAS.put("java.math.BigInteger", "BigInteger");
+ CLASS_ALIAS.put("Float", "Float");
+ CLASS_ALIAS.put("java.lang.Float", "Float");
+ CLASS_ALIAS.put("Double", "Float");
+ CLASS_ALIAS.put("java.lang.Double", "Float");
+ CLASS_ALIAS.put("BigDecimal", "BigDecimal");
+ CLASS_ALIAS.put("java.math.BigDecimal", "BigDecimal");
+ CLASS_ALIAS.put("Boolean", "Boolean");
+ CLASS_ALIAS.put("java.lang.Boolean", "Boolean");
+
+ CLASS_ALIAS.put("org.apache.ofbiz.entity.GenericValue", "GenericValue");
+ CLASS_ALIAS.put("GenericValue", "GenericValue");
+ CLASS_ALIAS.put("GenericPK", "GenericPK");
+ CLASS_ALIAS.put("org.apache.ofbiz.entity.GenericPK", "GenericPK");
+ CLASS_ALIAS.put("org.apache.ofbiz.entity.GenericEntity", "GenericEntity");
+ CLASS_ALIAS.put("GenericEntity", "GenericEntity");
+
+ CLASS_ALIAS.put("java.util.List", "List");
+ CLASS_ALIAS.put("List", "List");
+ CLASS_ALIAS.put("java.util.Set", "Set");
+ CLASS_ALIAS.put("Set", "Set");
+ CLASS_ALIAS.put("java.util.Map", "Map");
+ CLASS_ALIAS.put("Map", "Map");
+ CLASS_ALIAS.put("java.util.HashMap", "HashMap");
+ CLASS_ALIAS.put("HashMap", "HashMap");
+
+ JAVA_OPEN_API_MAP.put("String", StringSchema.class);
+ JAVA_OPEN_API_MAP.put("Integer", IntegerSchema.class);
+ JAVA_OPEN_API_MAP.put("Long", IntegerSchema.class);
+ JAVA_OPEN_API_MAP.put("Boolean", BooleanSchema.class);
+ JAVA_OPEN_API_MAP.put("Map", MapSchema.class);
+ JAVA_OPEN_API_MAP.put("GenericEntity", MapSchema.class);
+ JAVA_OPEN_API_MAP.put("GenericPK", MapSchema.class);
+ JAVA_OPEN_API_MAP.put("GenericValue", MapSchema.class);
+ JAVA_OPEN_API_MAP.put("HashMap", MapSchema.class);
+ JAVA_OPEN_API_MAP.put("List", ArraySchema.class);
+ JAVA_OPEN_API_MAP.put("Set", ArraySchema.class);
+ JAVA_OPEN_API_MAP.put("Collection", ArraySchema.class);
+ JAVA_OPEN_API_MAP.put("Float", NumberSchema.class);
+ JAVA_OPEN_API_MAP.put("Double", NumberSchema.class);
+ JAVA_OPEN_API_MAP.put("BigDecimal", NumberSchema.class);
+ JAVA_OPEN_API_MAP.put("BigInteger", IntegerSchema.class);
+ JAVA_OPEN_API_MAP.put("Timestamp", DateSchema.class);
+
+ FIELD_TYPE_MAP.put("id", "String");
+ FIELD_TYPE_MAP.put("indicator", "String");
+ FIELD_TYPE_MAP.put("date", "String");
+ FIELD_TYPE_MAP.put("id-vlong", "String");
+ FIELD_TYPE_MAP.put("description", "String");
+ FIELD_TYPE_MAP.put("numeric", "Int"); //
+ FIELD_TYPE_MAP.put("long-varchar", "String");
+ FIELD_TYPE_MAP.put("id-long", "String");
+ FIELD_TYPE_MAP.put("currency-amount", "BigDecimal");
+ FIELD_TYPE_MAP.put("value", "value");
+ FIELD_TYPE_MAP.put("email", "String");
+ FIELD_TYPE_MAP.put("currency-precise", "BigDecimal");
+ FIELD_TYPE_MAP.put("very-short", "String");
+ FIELD_TYPE_MAP.put("date-time", "Timestamp");
+ FIELD_TYPE_MAP.put("credit-card-date", "String");
+ FIELD_TYPE_MAP.put("url", "String");
+ FIELD_TYPE_MAP.put("credit-card-number", "String");
+ FIELD_TYPE_MAP.put("fixed-point", "BigDecimal");
+ FIELD_TYPE_MAP.put("name", "String");
+ FIELD_TYPE_MAP.put("short-varchar", "String");
+ FIELD_TYPE_MAP.put("comment", "String");
+ FIELD_TYPE_MAP.put("time", "String");
+ FIELD_TYPE_MAP.put("very-long", "String");
+ FIELD_TYPE_MAP.put("floating-point", "Float");
+ FIELD_TYPE_MAP.put("object", "Byte");
+ FIELD_TYPE_MAP.put("byte-array", "Byte");
+ FIELD_TYPE_MAP.put("blob", "Byte");
+
+ buildApiResponseSchemas();
+ buildApiResponses();
+ }
+
+ private static void buildApiResponseSchemas() {
+ Schema<?> genericErrorSchema = new MapSchema();
+ genericErrorSchema.addProperty("statusCode", new IntegerSchema().description("HTTP Status Code"));
+
+ genericErrorSchema.addProperty("statusDescription", new StringSchema().description("HTTP Status Code Description"));
+ genericErrorSchema.addProperty("errorType", new StringSchema().description("Error Type for the error"));
+ genericErrorSchema.addProperty("errorMessage", new StringSchema().description("Error Message"));
+ SCHEMAS.put("api.response.unauthorized.noheader", genericErrorSchema);
+ SCHEMAS.put("api.response.unauthorized.invalidtoken", genericErrorSchema);
+ SCHEMAS.put("api.response.forbidden", genericErrorSchema);
+ SCHEMAS.put("api.response.service.badrequest", genericErrorSchema);
+ SCHEMAS.put("api.response.service.unprocessableentity", genericErrorSchema);
+ SCHEMAS.put("api.response.service.methodnotallowed", genericErrorSchema);
+ }
+
+ /**
+ * Returns the standard API responses shared across all OFBiz REST operations.
+ *
+ * @return the map of standard {@link ApiResponse} instances keyed by HTTP status code
+ */
+ public static Map<String, ApiResponse> getStandardApiResponses() {
+ return RESPONSES;
+ }
+
+ /**
+ * Returns the standard API response schemas shared across all OFBiz REST operations.
+ *
+ * @return the map of standard {@link Schema} instances keyed by schema name
+ */
+ public static Map<String, Schema<?>> getStandardApiResponseSchemas() {
+ return SCHEMAS;
+ }
+
+ private static void buildApiResponses() {
+ Map<String, Object> unauthorizedNoHeaderExample = UtilMisc.toMap("statusCode", Response.Status.UNAUTHORIZED.getStatusCode(),
+ "statusDescription", Response.Status.UNAUTHORIZED.getReasonPhrase(),
+ "errorMessage", "Unauthorized: Access is denied due to invalid or absent Authorization header.");
+ Map<String, Object> unauthorizedInvalidTokenExample = UtilMisc.toMap("statusCode", Response.Status.UNAUTHORIZED.getStatusCode(),
+ "statusDescription", Response.Status.UNAUTHORIZED.getReasonPhrase(),
+ "errorMessage", "Unauthorized: Access is denied due to invalid or absent Authorization header.");
+ Map<String, Object> forbiddenExample = UtilMisc.toMap("statusCode", Response.Status.FORBIDDEN.getStatusCode(),
+ "statusDescription", Response.Status.FORBIDDEN.getReasonPhrase(),
+ "errorMessage", "Forbidden: Insufficient rights to perform this API call.");
+ Map<String, Object> badRequestExample = UtilMisc.toMap("statusCode", Response.Status.BAD_REQUEST.getStatusCode(),
+ "statusDescription", Response.Status.BAD_REQUEST.getReasonPhrase(),
+ "errorType", "ServiceValidationException",
+ "errorMessage", "createProduct validation failed. The request contained invalid information and could not be processed.",
+ "errorDescription", "The following required parameter is missing: [IN] [createProduct.internalName]");
+ Map<String, Object> unprocessableEntExample = UtilMisc.toMap("statusCode", ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getStatusCode(),
+ "statusDescription", ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getReasonPhrase(),
+ "errorType", "GenericEntityException",
+ "errorMessage", "createProduct execution failed. The request contained invalid information and could not be processed.",
+ "errorDescription", "StandardException: A truncation error was encountered trying to shrink CHAR 'string' to length 1.");
+ Map<String, Object> methodNotAllowedExample = UtilMisc.toMap("statusCode", Response.Status.METHOD_NOT_ALLOWED.getStatusCode(),
+ "statusDescription", Response.Status.METHOD_NOT_ALLOWED.getReasonPhrase(),
+ "errorMessage", "HTTP POST is not allowed on service 'demoDoGetService'.");
+
+ final ApiResponse unauthorizedNoHeader = new ApiResponse().addHeaderObject(HttpHeaders.WWW_AUTHENTICATE, new Header()
+ .schema(new Schema<>().type("string").format("string")).example(HttpHeaders.WWW_AUTHENTICATE + ": "
+ + AuthenticationScheme.BEARER.getScheme() + " realm=\"" + AuthenticationScheme.REALM + "\""))
+ .description("Unauthorized: Access is denied due to invalid or absent Authorization header.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>()
+ .$ref("#/components/schemas/" + "api.response.unauthorized.noheader"))
+ .example(unauthorizedNoHeaderExample)));
+
+ final ApiResponse unauthorizedInvalidToken = new ApiResponse()
+ .description("Unauthorized: Access is denied due to invalid or absent Authorization header.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>()
+ .$ref("#/components/schemas/" + "api.response.unauthorized.invalidtoken"))
+ .example(unauthorizedInvalidTokenExample)));
+
+ final ApiResponse forbidden = new ApiResponse().addHeaderObject(HttpHeaders.WWW_AUTHENTICATE, new Header()
+ .schema(new Schema<>().type("string"))
+ .example(HttpHeaders.WWW_AUTHENTICATE + ": "
+ + AuthenticationScheme.BEARER.getScheme() + " realm=\"" + AuthenticationScheme.REALM + "\""))
+ .description("Forbidden: Insufficient rights to perform this API call.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>().$ref("#/components/schemas/" + "api.response.forbidden"))
+ .example(forbiddenExample)));
+
+ final ApiResponse badRequest = new ApiResponse()
+ .description("Bad Request: Due to malformed request syntax or invalid request message framing or incorrect request parameters.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>()
+ .$ref("#/components/schemas/" + "api.response.service.badrequest"))
+ .example(badRequestExample)));
+
+ final ApiResponse unprocessableEntity = new ApiResponse()
+ .description("Unprocessable Entity: Error indicating semantical errors. Request is syntactically correct though.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>()
+ .$ref("#/components/schemas/" + "api.response.service.unprocessableentity"))
+ .example(unprocessableEntExample)));
+
+ final ApiResponse methodNotAllowed = new ApiResponse()
+ .description("Method Not Allowed: Service called with HTTP method other than the declared one.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>()
+ .$ref("#/components/schemas/" + "api.response.service.methodnotallowed"))
+ .example(methodNotAllowedExample)));
+
+ RESPONSES.put(String.valueOf(Response.Status.UNAUTHORIZED.getStatusCode()), unauthorizedNoHeader);
+ RESPONSES.put(String.valueOf(Response.Status.UNAUTHORIZED.getStatusCode()), unauthorizedInvalidToken);
+ RESPONSES.put(String.valueOf(Response.Status.FORBIDDEN.getStatusCode()), forbidden);
+ RESPONSES.put(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()), badRequest);
+ RESPONSES.put(String.valueOf(ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getStatusCode()), unprocessableEntity);
+ RESPONSES.put(String.valueOf(Response.Status.METHOD_NOT_ALLOWED.getStatusCode()), methodNotAllowed);
+ }
+
+ /**
+ * Returns the OpenAPI {@link Class} type mapped to the given OFBiz service
+ * attribute type.
+ *
+ * @param attributeType the OFBiz attribute type (e.g. {@code "String"}, {@code "Long"})
+ * @return the corresponding OpenAPI schema class, or {@code null} if no mapping exists
+ */
+ public static Class<?> getOpenApiTypeForAttributeType(String attributeType) {
+ return JAVA_OPEN_API_MAP.get(CLASS_ALIAS.get(attributeType));
+ }
+
+ /**
+ * Returns the OpenAPI {@link Class} type mapped to the given OFBiz entity
+ * field type.
+ *
+ * @param fieldType the OFBiz entity field type (e.g. {@code "date-time"}, {@code "numeric"})
+ * @return the corresponding OpenAPI schema class, or {@code null} if no mapping exists
+ */
+ public static Class<?> getOpenApiTypeForFieldType(String fieldType) {
+ return JAVA_OPEN_API_MAP.get(FIELD_TYPE_MAP.get(fieldType));
+ }
+
+ /**
+ * Builds the OpenAPI request body schema for the input parameters of the
+ * given OFBiz service.
+ *
+ * <p>Each input parameter is mapped to an OpenAPI property. Parameters
+ * that are not optional are added to the required list. Parameters without
+ * a known OpenAPI type mapping are silently skipped.</p>
+ *
+ * @param service the {@link ModelService} for which to build the input schema
+ * @return an OpenAPI {@link Schema} representing the service request body
+ */
+ public static Schema<Object> getInSchema(ModelService service) {
+ Schema<Object> parentSchema = new Schema<Object>();
+ parentSchema.setDescription("In Schema for service: " + service.getName() + " request");
+ parentSchema.setType("object");
+ List<String> required = UtilMisc.toList();
+ service.getInParamNamesMap().forEach((name, type) -> {
+ ModelParam param = service.getParam(name);
+ if (!param.isOptional()) {
+ required.add(name);
+ }
+ Schema<?> attrSchema = getAttributeSchema(service, param);
+ if (attrSchema != null) {
+ parentSchema.addProperty(name, getAttributeSchema(service, service.getParam(name)));
+ }
+ });
+ parentSchema.setRequired(required);
+ return parentSchema;
+ }
+
+ /**
+ * Builds the OpenAPI schema for a single OFBiz service parameter.
+ *
+ * <p>The schema type is determined by mapping the parameter's OFBiz type
+ * to an OpenAPI type. Returns {@code null} and logs a warning if no mapping
+ * is found, or if a {@code Map} type parameter has no entity name or child
+ * attributes defined.</p>
+ *
+ * @param service the {@link ModelService} owning the parameter
+ * @param param the {@link ModelParam} to build a schema for
+ * @return the OpenAPI {@link Schema} for the parameter, or {@code null} if
+ * the parameter cannot be mapped
+ */
+ public static Schema<?> getAttributeSchema(ModelService service, ModelParam param) {
+ Schema<?> schema = null;
+ Class<?> schemaClass = getOpenApiTypeForAttributeType(param.getType());
+ if (schemaClass == null) {
+ Debug.logWarning("Attribute '" + param.getName() + "' ignored as it is declared as '" + param.getType()
+ + "' and corresponding OpenApi Type Mapping not found.", MODULE);
+ return null;
+ }
+ try {
+ schema = (Schema<?>) schemaClass.getDeclaredConstructor().newInstance();
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
+ | SecurityException e) {
+ Debug.logError(e, MODULE);
+ }
+
+ List<ModelParam> children = param.getChildren();
+ Delegator delegator = WebAppUtil.getDelegator(ApiContextListener.getApplicationCntx());
+ if (schema instanceof ArraySchema) {
+ ArraySchema arrSch = (ArraySchema) schema;
+ arrSch.setItems(children.size() > 0 ? getAttributeSchema(service, children.get(0)) : new StringSchema());
+ } else if (schema instanceof MapSchema) {
+ if (isTypeGenericEntityOrGenericValue(param.getType())) {
+ if (UtilValidate.isEmpty(param.getEntityName())) {
+ Debug.logWarning(
+ "Attribute '" + param.getName() + "' ignored as it is declared as '" + param.getType() + "' but does not have "
+ + "entity-name defined.",
+ MODULE);
+ return null;
+ }
+ schema = getSchemaForEntity(delegator.getModelEntity(param.getEntityName()));
+ } else if (UtilValidate.isEmpty(param.getChildren())) {
+ Debug.logWarning(
+ "Attribute '" + param.getName() + "' ignored as it is declared as '" + param.getType() + "' but does not have "
+ + "any child attributes.",
+ MODULE);
+ return null;
+ } else {
+ List<String> required = UtilMisc.toList();
+ for (ModelParam childParam : children) {
+ if (!param.isOptional()) {
+ required.add(childParam.getName());
+ }
+ schema.addProperty(childParam.getName(), getAttributeSchema(service, childParam));
+ }
+ schema.setRequired(required);
+ }
+
+ }
+ return schema;
+ }
+
+ /**
+ * Builds the OpenAPI response body schema for the output parameters of the
+ * given OFBiz service.
+ *
+ * <p>The response schema always includes {@code statusCode},
+ * {@code statusDescription}, and {@code successMessage} properties.
+ * Service output parameters are nested under a {@code data} property.</p>
+ *
+ * @param service the {@link ModelService} for which to build the output schema
+ * @return an OpenAPI {@link Schema} representing the service response body
+ */
+ public static Schema<Object> getOutSchema(ModelService service) {
+ Schema<Object> parentSchema = new Schema<Object>();
+ parentSchema.setDescription("Out Schema for service: " + service.getName() + " response");
+ parentSchema.setType("object");
+ parentSchema.addProperty("statusCode", new IntegerSchema().description("HTTP Status Code"));
+ parentSchema.addProperty("statusDescription", new StringSchema().description("HTTP Status Code Description"));
+ parentSchema.addProperty("successMessage", new StringSchema().description("Success Message"));
+ Schema<Object> dataSchema = new Schema<Object>();
+ parentSchema.addProperty("data", dataSchema);
+ service.getOutParamNamesMap().forEach((name, type) -> {
+ Schema<?> attrSchema = getAttributeSchema(service, service.getParam(name));
+ if (attrSchema != null) {
+ dataSchema.addProperty(name, getAttributeSchema(service, service.getParam(name)));
+ }
+ });
+ return parentSchema;
+ }
+
+ private static boolean isTypeGenericEntityOrGenericValue(String type) {
+ if (type == null) {
+ return false;
+ }
+ return type.matches("org.apache.ofbiz.entity.GenericValue|GenericValue|org.apache.ofbiz.entity.GenericEntity|GenericEntity");
+ }
+
+ private static Schema<?> getSchemaForEntity(ModelEntity entity) {
+ Schema<?> dataSchema = new Schema<>();
+ dataSchema.setType("object");
+ List<String> fields = entity.getAllFieldNames();
+ for (String fieldNm : fields) {
+ ModelField field = entity.getField(fieldNm);
+ Schema<?> schema = null;
+ Class<?> schemaClass = getOpenApiTypeForFieldType(field.getType());
+ if (schemaClass == null) {
+ continue;
+ }
+ try {
+ schema = (Schema<?>) schemaClass.getDeclaredConstructor().newInstance();
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
+ | SecurityException e) {
+ Debug.logError(e, MODULE);
+ }
+ if (schemaClass != null) {
+ dataSchema.addProperty(fieldNm, schema.description(fieldNm));
+ }
+ }
+ return dataSchema;
+ }
+
+ /**
+ * Builds a standard HTTP 200 success {@link ApiResponse} referencing the
+ * OpenAPI response schema for the given service.
+ *
+ * @param service the {@link ModelService} for which to build the success response
+ * @return an {@link ApiResponse} with a JSON media type and a schema reference
+ * to {@code #/components/schemas/api.response.<serviceName>.success}
+ */
+ public static ApiResponse buildSuccessResponse(ModelService service) {
+ final ApiResponse success = new ApiResponse()
+ .description("Success response for the API call.")
+ .content(new Content()
+ .addMediaType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
+ .schema(new Schema<>().$ref("#/components/schemas/" + "api.response." + service.getName() + ".success"))));
+ return success;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java
new file mode 100644
index 0000000000..ef9637b68a
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java
@@ -0,0 +1,182 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.util;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.ofbiz.base.util.UtilProperties;
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.service.ModelService;
+import org.apache.ofbiz.ws.rs.core.ResponseStatus;
+import org.apache.ofbiz.ws.rs.response.Error;
+import org.apache.ofbiz.ws.rs.response.Success;
+
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response.ResponseBuilder;
+
+public final class RestApiUtil {
+
+ private static final String DEFAULT_MSG_UI_LABEL_RESOURCE = "ApiUiLabels";
+
+ private RestApiUtil() {
+
+ }
+
+ /**
+ * Builds a JSON success response with HTTP 200 and the given message and data.
+ *
+ * @param message a human-readable success message
+ * @param data the response payload
+ * @return a JAX-RS {@link Response} with status 200 and a JSON {@link Success} body
+ */
+ public static Response success(String message, Object data) {
+ Success success = new Success(Response.Status.OK.getStatusCode(), Response.Status.OK.getReasonPhrase(), message, data);
+ return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity(success).build();
+ }
+
+ /**
+ * Builds a JSON error response with the given status code, reason phrase,
+ * and message.
+ *
+ * @param statusCode the HTTP status code
+ * @param reasonPhrase the HTTP reason phrase (e.g. {@code "Bad Request"})
+ * @param message a human-readable error message
+ * @return a JAX-RS {@link Response} with a JSON {@link Error} body
+ */
+ public static Response error(int statusCode, String reasonPhrase, String message) {
+ Error error = new Error(statusCode, reasonPhrase, message);
+ return Response.status(statusCode).type(MediaType.APPLICATION_JSON).entity(error).build();
+ }
+
+ /**
+ * Builds a JSON error {@link ResponseBuilder} that can be further modified
+ * before building the final response.
+ *
+ * @param statusCode the HTTP status code
+ * @param reasonPhrase the HTTP reason phrase (e.g. {@code "Bad Request"})
+ * @param message a human-readable error message
+ * @return a JAX-RS {@link ResponseBuilder} with a JSON {@link Error} entity
+ */
+ public static ResponseBuilder errorBuilder(int statusCode, String reasonPhrase, String message) {
+ Error error = new Error(statusCode, reasonPhrase, message);
+ return Response.status(statusCode).type(MediaType.APPLICATION_JSON).entity(error);
+ }
+
+ /**
+ * Extracts query or form parameters from a {@link MultivaluedMap} into a
+ * flat map. Single-value entries are unwrapped to a plain {@link String};
+ * multi-value entries are kept as a {@link List}.
+ *
+ * @param multivaluedMap the JAX-RS parameter map to extract from
+ * @return a map of parameter names to either a {@link String} or {@link List} of strings
+ */
+ public static Map<String, Object> extractParams(MultivaluedMap<String, String> multivaluedMap) {
+ Map<String, Object> result = new HashMap<>();
+ multivaluedMap.forEach((name, values) -> {
+ if (UtilValidate.isNotEmpty(values)) {
+ result.put(name, (values.size() != 1) ? values : values.get(0));
+ }
+ });
+ return result;
+ }
+
+ /**
+ * Extracts path parameter names from a JAX-RS path template string.
+ * Template variables are identified by curly brace notation (e.g.
+ * {@code {id}}).
+ *
+ * @param pathInfo the path template string (e.g. {@code "/order/{orderId}/item/{itemId}"})
+ * @return a list of parameter names without braces; empty if {@code pathInfo}
+ * is {@code null} or contains no template variables
+ */
+ public static List<String> getPathParameters(String pathInfo) {
+ List<String> pathParams = new ArrayList<>();
+ if (pathInfo == null) {
+ return pathParams;
+ }
+ String[] pathParts = pathInfo.split("/");
+ for (String pathSegement : pathParts) {
+ if (pathSegement.startsWith("{") && pathSegement.endsWith("}")) {
+ pathParams.add(pathSegement.substring(1, pathSegement.length() - 1));
+ }
+ }
+ return pathParams;
+ }
+
+ /**
+ * Builds a JSON error response from an OFBiz service result map that
+ * indicates failure. Extracts the primary error message and any additional
+ * error messages from the result and returns an HTTP 422 Unprocessable Entity
+ * response.
+ *
+ * @param service the name of the OFBiz service that produced the error
+ * @param result the service result map containing error message entries
+ * @param locale the locale used to resolve the error message label
+ * @return a JAX-RS {@link Response} with status 422 and a JSON {@link Error} body
+ */
+ @SuppressWarnings("unchecked")
+ public static Response buildErrorFromServiceResult(String service, Map<String, Object> result, Locale locale) {
+ String errorMessage = null;
+ List<String> additionalErrorMessages = new LinkedList<>();
+ if (!UtilValidate.isEmpty(result.get(ModelService.ERROR_MESSAGE))) {
+ errorMessage = result.get(ModelService.ERROR_MESSAGE).toString();
+ }
+ if (!UtilValidate.isEmpty(result.get(ModelService.ERROR_MESSAGE_LIST))) {
+ List<String> errorMessageList = (List<String>) result.get(ModelService.ERROR_MESSAGE_LIST);
+ if (UtilValidate.isEmpty(errorMessage)) {
+ errorMessage = errorMessageList.get(0);
+ errorMessageList.remove(0);
+ }
+ for (int i = 0; i < errorMessageList.size(); i++) {
+ additionalErrorMessages.add(errorMessageList.get(i));
+ }
+ }
+ Error error = new Error().type("ServiceError").code(ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getStatusCode())
+ .description(ResponseStatus.Custom.UNPROCESSABLE_ENTITY.getReasonPhrase())
+ .message(getErrorMessage(service, "GenericServiceErrorMessage", locale)).errorDesc(errorMessage);
+ if (!additionalErrorMessages.isEmpty()) {
+ error.setAdditionalErrors(additionalErrorMessages);
+ }
+ return Response.status(ResponseStatus.Custom.UNPROCESSABLE_ENTITY).type(MediaType.APPLICATION_JSON)
+ .entity(error).build();
+ }
+
+ /**
+ * Resolves a localized error message from {@code ApiUiLabels} for the given
+ * service name and error key, substituting the service name into the message
+ * template.
+ *
+ * @param serviceName the OFBiz service name substituted into the message template
+ * @param errorKey the label key to look up in {@code ApiUiLabels}
+ * @param locale the locale used to resolve the label
+ * @return the resolved and substituted error message string
+ */
+ public static String getErrorMessage(String serviceName, String errorKey, Locale locale) {
+ String error = UtilProperties.getMessage(DEFAULT_MSG_UI_LABEL_RESOURCE, errorKey, locale);
+ error = error.replace("${service}", serviceName);
+ return error;
+ }
+}
diff --git a/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/ServiceRequestWorker.java b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/ServiceRequestWorker.java
new file mode 100644
index 0000000000..1b10ad3323
--- /dev/null
+++ b/framework/rest-api/src/main/java/org/apache/ofbiz/ws/rs/util/ServiceRequestWorker.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.ofbiz.ws.rs.util;
+
+import java.util.Map;
+import java.util.LinkedHashMap;
+
+import org.apache.ofbiz.base.util.UtilValidate;
+import org.apache.ofbiz.service.ModelParam;
+import org.apache.ofbiz.service.ModelService;
+
+public final class ServiceRequestWorker {
+ public static Map<String, Object> extractResponseData(ModelService service, Map<String, Object> result) {
+ Map<String, Object> responseData = new LinkedHashMap<>();
+ for (String outParamName : service.getOutParamNames()) {
+ ModelParam outParam = service.getParam(outParamName);
+ if (!outParam.isInternal()) {
+ Object value = result.get(outParamName);
+ if (UtilValidate.isNotEmpty(value)) {
+ responseData.put(outParamName, value);
+ }
+ }
+ }
+ return responseData;
+ }
+}
diff --git a/framework/rest-api/testdef/rest-apiTests.xml b/framework/rest-api/testdef/rest-apiTests.xml
new file mode 100644
index 0000000000..48e0630b15
--- /dev/null
+++ b/framework/rest-api/testdef/rest-apiTests.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<test-suite suite-name="rest-api-tests"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:noNamespaceSchemaLocation="https://ofbiz.apache.org/dtds/test-suite.xsd">
+
+
+</test-suite>
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/README.adoc b/framework/rest-api/webapp/docs/README.adoc
new file mode 100644
index 0000000000..f616ffb5c9
--- /dev/null
+++ b/framework/rest-api/webapp/docs/README.adoc
@@ -0,0 +1,15 @@
+= REST API documentation
+
+You can choose between Swagger UI and Redoc to publish documentation for the REST API.
+
+== Swagger
+
+Current version: swagger-ui-4.2.1
+
+Access: https://localhost:8443/docs/swagger-ui.html
+
+== Redoc
+
+Current version: redoc@2.0.0-rc.59
+
+Accesss: https://localhost:8443/docs/redoc.html
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/WEB-INF/web.xml b/framework/rest-api/webapp/docs/WEB-INF/web.xml
new file mode 100644
index 0000000000..d5a9404e62
--- /dev/null
+++ b/framework/rest-api/webapp/docs/WEB-INF/web.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
+ <display-name>Apache OFBiz - REST API Swagger Component</display-name>
+ <description>REST API Swagger Component of the Apache OFBiz Project</description>
+ <welcome-file-list>
+ <welcome-file>swagger-ui.html</welcome-file>
+ </welcome-file-list>
+</web-app>
diff --git a/framework/rest-api/webapp/docs/favicon-16x16.png b/framework/rest-api/webapp/docs/favicon-16x16.png
new file mode 100644
index 0000000000..8b194e617a
Binary files /dev/null and b/framework/rest-api/webapp/docs/favicon-16x16.png differ
diff --git a/framework/rest-api/webapp/docs/favicon-32x32.png b/framework/rest-api/webapp/docs/favicon-32x32.png
new file mode 100644
index 0000000000..249737fe44
Binary files /dev/null and b/framework/rest-api/webapp/docs/favicon-32x32.png differ
diff --git a/framework/rest-api/webapp/docs/oauth2-redirect.html b/framework/rest-api/webapp/docs/oauth2-redirect.html
new file mode 100644
index 0000000000..80168cc60a
--- /dev/null
+++ b/framework/rest-api/webapp/docs/oauth2-redirect.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="en-US">
+<head>
+ <title>Swagger UI: OAuth2 Redirect</title>
+</head>
+<body>
+</body>
+</html>
+<script>
+ 'use strict';
+ function run () {
+ var oauth2 = window.opener.swaggerUIRedirectOauth2;
+ var sentState = oauth2.state;
+ var redirectUrl = oauth2.redirectUrl;
+ var isValid, qp, arr;
+
+ if (/code|token|error/.test(window.location.hash)) {
+ qp = window.location.hash.substring(1);
+ } else {
+ qp = location.search.substring(1);
+ }
+
+ arr = qp.split("&")
+ arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
+ qp = qp ? JSON.parse('{' + arr.join() + '}',
+ function (key, value) {
+ return key === "" ? value : decodeURIComponent(value)
+ }
+ ) : {}
+
+ isValid = qp.state === sentState
+
+ if ((
+ oauth2.auth.schema.get("flow") === "accessCode"||
+ oauth2.auth.schema.get("flow") === "authorizationCode"
+ ) && !oauth2.auth.code) {
+ if (!isValid) {
+ oauth2.errCb({
+ authId: oauth2.auth.name,
+ source: "auth",
+ level: "warning",
+ message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
+ });
+ }
+
+ if (qp.code) {
+ delete oauth2.state;
+ oauth2.auth.code = qp.code;
+ oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
+ } else {
+ let oauthErrorMsg
+ if (qp.error) {
+ oauthErrorMsg = "["+qp.error+"]: " +
+ (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
+ (qp.error_uri ? "More info: "+qp.error_uri : "");
+ }
+
+ oauth2.errCb({
+ authId: oauth2.auth.name,
+ source: "auth",
+ level: "error",
+ message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
+ });
+ }
+ } else {
+ oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
+ }
+ window.close();
+ }
+
+ window.addEventListener('DOMContentLoaded', function () {
+ run();
+ });
+</script>
diff --git a/framework/rest-api/webapp/docs/redoc.html b/framework/rest-api/webapp/docs/redoc.html
new file mode 100644
index 0000000000..6fa1d23978
--- /dev/null
+++ b/framework/rest-api/webapp/docs/redoc.html
@@ -0,0 +1,47 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<!DOCTYPE html>
+<html lang="en-US">
+ <head>
+ <title>OFBiz REST API</title>
+ <!-- needed for adaptive design -->
+ <meta charset="utf-8"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
+ <!--
+ ReDoc doesn't change outer page styles
+ -->
+ <style>
+ body {
+ margin: 0;
+ padding: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <redoc></redoc>
+ <script src="redoc.standalone.js"> </script>
+ <script>
+ if (!window.location.origin) {
+ window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
+ }
+ Redoc.init(window.location.origin + '/rest/openapi.json');
+ </script>
+ </body>
+</html>
diff --git a/framework/rest-api/webapp/docs/redoc.standalone.js b/framework/rest-api/webapp/docs/redoc.standalone.js
new file mode 100644
index 0000000000..3c7725ab66
--- /dev/null
+++ b/framework/rest-api/webapp/docs/redoc.standalone.js
@@ -0,0 +1,3 @@
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):"function"==typeof define&&define.amd?define(["null"],t):"object"==typeof exports?exports.Redoc=t(require("null")):e.Redoc=t(e.null)}(this,(function(e){return function(){var t={7228:function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r},e.exports.default=e.exports,e.exports.__esModule=!0},2858:function(e){e.exports=func [...]
":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function w(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}for(var k=new Array(256),E=new Array(256),S=0;S<256;S++)k[S]=x(S)?1:0,E[S]=x(S);function _(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||s,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typ [...]
\u2028\u2029".indexOf(this.buffer.charAt(o-1));)if(o-=1,this.position-o>t/2-1){n=" ... ",o+=5;break}for(i="",a=this.position;a<this.buffer.length&&-1==="\0\r\n
\u2028\u2029".indexOf(this.buffer.charAt(a));)if((a+=1)-this.position>t/2-1){i=" ... ",a-=5;break}return s=this.buffer.slice(o,a),r.repeat(" ",e)+n+s+i+"\n"+r.repeat(" ",e+this.position-o+n.length)+"^"},o.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},e.exports=o},304:function(e,t,n){"use strict";n(4747),n(7327);var r=n(910),o=n(2188),i=n(889);function [...]
"!="
"[e]()||o[e].name!==e}))}},3111:function(e,t,n){var r=n(4488),o="["+n(1361)+"]",i=RegExp("^"+o+o+"*"),a=RegExp(o+o+"*$"),s=function(e){return function(t){var n=String(r(t));return 1&e&&(n=n.replace(i,"")),2&e&&(n=n.replace(a,"")),n}};e.exports={start:s(1),end:s(2),trim:s(3)}},261:function(e,t,n){var r,o,i,a=n(7854),s=n(7293),l=n(9974),c=n(490),u=n(317),p=n(6833),f=n(5268),d=a.location,h=a.setImmediate,m=a.clearImmediate,v=a.process,g=a.MessageChannel,y=a.Dispatch,b=0,x={},w=function(e){i [...]
"!="
"[e]()||i[e].name!==e}))}},3111:function(e,t,r){var n=r(4488),i="["+r(1361)+"]",o=RegExp("^"+i+i+"*"),s=RegExp(i+i+"*$"),a=function(e){return function(t){var r=String(n(t));return 1&e&&(r=r.replace(o,"")),2&e&&(r=r.replace(s,"")),r}};e.exports={start:a(1),end:a(2),trim:a(3)}},261:function(e,t,r){var n,i,o,s=r(7854),a=r(7293),u=r(9974),c=r(490),l=r(317),f=r(6833),h=r(5268),p=s.location,d=s.setImmediate,v=s.clearImmediate,y=s.process,g=s.MessageChannel,m=s.Dispatch,x=0,w={},b=function(e){i [...]
+//# sourceMappingURL=redoc.standalone.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-bundle.js b/framework/rest-api/webapp/docs/swagger-ui-bundle.js
new file mode 100644
index 0000000000..008952e051
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-bundle.js
@@ -0,0 +1,3 @@
+/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r [...]
":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function oe(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}for(var ae=new Array(256),ie=new Array(256),ue=0;ue<256;ue++)ae[ue]=re(ue)?1:0,ie[ue]=re(ue);function se(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||W,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledIm [...]
"!=="
"[e]()||r&&a[e].name!==e}))}},function(e,t,n){var r=n(100),o=n(255);e.exports=function(e){return o(r(e).toLowerCase())}},function(e,t,n){var r=n(132),o=n(390),a=n(51),i=n(191),u=r?r.prototype:void 0,s=u?u.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(a(t))return o(t,e)+"";if(i(t))return s?s.call(t):"";var n=t+"";return"0"==n&&1/t==-Infinity?"-0":n}},function(e,t,n){var r=n(673),o=n(392),a=n(674),i=n(100);e.exports=function(e){return function(t){t=i(t);var n=o( [...]
+//# sourceMappingURL=swagger-ui-bundle.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-bundle.js.map b/framework/rest-api/webapp/docs/swagger-ui-bundle.js.map
new file mode 100644
index 0000000000..2695fec9be
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-bundle.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://SwaggerUIBundle/webpack/universalModuleDefinition","webpack://SwaggerUIBundle/webpack/bootstrap","webpack://SwaggerUIBundle/./node_modules/react/index.js","webpack://SwaggerUIBundle/./node_modules/immutable/dist/immutable.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/concat.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/helpers/defineProperty.js","webpack://SwaggerUIBundle/./node_modul [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js b/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js
new file mode 100644
index 0000000000..fab30abb01
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js
@@ -0,0 +1,3 @@
+/*! For license information please see swagger-ui-es-bundle-core.js.LICENSE.txt */
+module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e; [...]
"!=="
"[e]()||r&&o[e].name!==e}))}},function(e,t,n){var r=n(96),a=n(232);e.exports=function(e){return a(r(e).toLowerCase())}},function(e,t,n){var r=n(122),a=n(362),o=n(51),i=n(178),s=r?r.prototype:void 0,c=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(o(t))return a(t,e)+"";if(i(t))return c?c.call(t):"";var n=t+"";return"0"==n&&1/t==-Infinity?"-0":n}},function(e,t,n){var r=n(622),a=n(364),o=n(623),i=n(96);e.exports=function(e){return function(t){t=i(t);var n=a(t) [...]
+//# sourceMappingURL=swagger-ui-es-bundle-core.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js.map b/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js.map
new file mode 100644
index 0000000000..25dee53f3b
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-es-bundle-core.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://SwaggerUIBundle/webpack/bootstrap","webpack://SwaggerUIBundle/external \"react\"","webpack://SwaggerUIBundle/external \"immutable\"","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/concat.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/helpers/defineProperty.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/map.js","webpack://SwaggerUIBundle/./src/co [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js b/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js
new file mode 100644
index 0000000000..6c86553f3a
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js
@@ -0,0 +1,3 @@
+/*! For license information please see swagger-ui-es-bundle.js.LICENSE.txt */
+module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e; [...]
":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function oe(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}for(var ae=new Array(256),ie=new Array(256),ue=0;ue<256;ue++)ae[ue]=re(ue)?1:0,ie[ue]=re(ue);function se(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||W,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledIm [...]
"!=="
"[e]()||r&&a[e].name!==e}))}},function(e,t,n){var r=n(100),o=n(255);e.exports=function(e){return o(r(e).toLowerCase())}},function(e,t,n){var r=n(132),o=n(390),a=n(51),i=n(191),u=r?r.prototype:void 0,s=u?u.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(a(t))return o(t,e)+"";if(i(t))return s?s.call(t):"";var n=t+"";return"0"==n&&1/t==-Infinity?"-0":n}},function(e,t,n){var r=n(673),o=n(392),a=n(674),i=n(100);e.exports=function(e){return function(t){t=i(t);var n=o( [...]
+//# sourceMappingURL=swagger-ui-es-bundle.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js.map b/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js.map
new file mode 100644
index 0000000000..accc676355
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-es-bundle.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://SwaggerUIBundle/webpack/bootstrap","webpack://SwaggerUIBundle/./node_modules/react/index.js","webpack://SwaggerUIBundle/./node_modules/immutable/dist/immutable.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/concat.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/helpers/defineProperty.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/map.js","web [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js b/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js
new file mode 100644
index 0000000000..71cffe0670
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js
@@ -0,0 +1,3 @@
+/*! For license information please see swagger-ui-standalone-preset.js.LICENSE.txt */
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SwaggerUIStandalonePreset=e():t.SwaggerUIStandalonePreset=e()}(this,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumer [...]
":95===t?" ":76===t?"\u2028":80===t?"\u2029":""}function it(t){return t<=65535?String.fromCharCode(t):String.fromCharCode(55296+(t-65536>>10),56320+(t-65536&1023))}for(var ot=new Array(256),ut=new Array(256),st=0;st<256;st++)ot[st]=rt(st)?1:0,ut[st]=rt(st);function at(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||G,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledIm [...]
"!=="
"[t]()||r&&o[t].name!==t}))}},function(t,e,n){var r=n(71),i=n(154);t.exports=function(t){return i(r(t).toLowerCase())}},function(t,e,n){var r=n(93),i=n(434),o=n(26),u=n(94),s=r?r.prototype:void 0,a=s?s.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(o(e))return i(e,t)+"";if(u(e))return a?a.call(e):"";var n=e+"";return"0"==n&&1/e==-Infinity?"-0":n}},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i [...]
+//# sourceMappingURL=swagger-ui-standalone-preset.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js.map b/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js.map
new file mode 100644
index 0000000000..966b78aea5
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui-standalone-preset.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://SwaggerUIStandalonePreset/webpack/universalModuleDefinition","webpack://SwaggerUIStandalonePreset/webpack/bootstrap","webpack://SwaggerUIStandalonePreset/./node_modules/core-js-pure/internals/global.js","webpack://SwaggerUIStandalonePreset/./node_modules/immutable/dist/immutable.js","webpack://SwaggerUIStandalonePreset/./node_modules/core-js-pure/internals/export.js","webpack://SwaggerUIStandalonePreset/./node_modules/react/index.js","webpack://SwaggerU [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui.css b/framework/rest-api/webapp/docs/swagger-ui.css
new file mode 100644
index 0000000000..e43a572a13
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui.css
@@ -0,0 +1,4 @@
+.swagger-ui{color:#3b4151;
+ /*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */font-family:sans-serif}.swagger-ui html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;line-height:1.15}.swagger-ui body{margin:0}.swagger-ui article,.swagger-ui aside,.swagger-ui footer,.swagger-ui header,.swagger-ui nav,.swagger-ui section{display:block}.swagger-ui h1{font-size:2em;margin:.67em 0}.swagger-ui figcaption,.swagger-ui figure,.swagger-ui main{display:block}.swagger-ui figure{margin:1em 40 [...]
+
+/*# sourceMappingURL=swagger-ui.css.map*/
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui.css.map b/framework/rest-api/webapp/docs/swagger-ui.css.map
new file mode 100644
index 0000000000..715873f110
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui.css.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///./src/style/main.scss","webpack:///./src/style/_type.scss","webpack:///./src/style/_variables.scss","webpack:///./node_modules/tachyons-sass/scss/_normalize.scss","webpack:///./node_modules/tachyons-sass/scss/_debug-children.scss","webpack:///./node_modules/tachyons-sass/scss/_debug-grid.scss","webpack:///./node_modules/tachyons-sass/scss/_box-sizing.scss","webpack:///./node_modules/tachyons-sass/scss/_aspect-ratios.scss","webpack:///./node_modules/tac [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui.html b/framework/rest-api/webapp/docs/swagger-ui.html
new file mode 100644
index 0000000000..53636b1cc0
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui.html
@@ -0,0 +1,63 @@
+<!-- HTML for static distribution bundle build -->
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <title>Swagger UI</title>
+ <link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
+ <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
+ <link rel="icon" type="image/png" href=".favicon-16x16.png" sizes="16x16" />
+ <style>
+ html
+ {
+ box-sizing: border-box;
+ overflow: -moz-scrollbars-vertical;
+ overflow-y: scroll;
+ }
+
+ *,
+ *:before,
+ *:after
+ {
+ box-sizing: inherit;
+ }
+
+ body
+ {
+ margin:0;
+ background: #fafafa;
+ }
+ </style>
+ </head>
+
+ <body>
+ <div id="swagger-ui"></div>
+
+ <script src="./swagger-ui-bundle.js"> </script>
+ <script src="./swagger-ui-standalone-preset.js"> </script>
+ <script>
+ window.onload = function() {
+ // Begin Swagger UI call region
+ if (!window.location.origin) {
+ window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
+ }
+ const ui = SwaggerUIBundle({
+ url: window.location.origin + "/rest/openapi.json",
+ dom_id: '#swagger-ui',
+ deepLinking: true,
+ presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIStandalonePreset
+ ],
+ plugins: [
+ SwaggerUIBundle.plugins.DownloadUrl
+ ],
+ layout: "StandaloneLayout"
+ })
+ // End Swagger UI call region
+
+ window.ui = ui
+ }
+ </script>
+ </body>
+</html>
diff --git a/framework/rest-api/webapp/docs/swagger-ui.js b/framework/rest-api/webapp/docs/swagger-ui.js
new file mode 100644
index 0000000000..1351a87f6c
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui.js
@@ -0,0 +1,3 @@
+/*! For license information please see swagger-ui.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUICore=t():e.SwaggerUICore=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=fun [...]
"!=="
"[e]()||r&&o[e].name!==e}))}},function(e,t,n){var r=n(96),a=n(232);e.exports=function(e){return a(r(e).toLowerCase())}},function(e,t,n){var r=n(122),a=n(362),o=n(51),i=n(178),s=r?r.prototype:void 0,c=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(o(t))return a(t,e)+"";if(i(t))return c?c.call(t):"";var n=t+"";return"0"==n&&1/t==-Infinity?"-0":n}},function(e,t,n){var r=n(622),a=n(364),o=n(623),i=n(96);e.exports=function(e){return function(t){t=i(t);var n=a(t) [...]
+//# sourceMappingURL=swagger-ui.js.map
\ No newline at end of file
diff --git a/framework/rest-api/webapp/docs/swagger-ui.js.map b/framework/rest-api/webapp/docs/swagger-ui.js.map
new file mode 100644
index 0000000000..9b906a024c
--- /dev/null
+++ b/framework/rest-api/webapp/docs/swagger-ui.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://SwaggerUICore/webpack/universalModuleDefinition","webpack://SwaggerUICore/webpack/bootstrap","webpack://SwaggerUICore/external \"react\"","webpack://SwaggerUICore/external \"immutable\"","webpack://SwaggerUICore/./node_modules/@babel/runtime-corejs3/core-js-stable/instance/concat.js","webpack://SwaggerUICore/./node_modules/@babel/runtime-corejs3/helpers/defineProperty.js","webpack://SwaggerUICore/./node_modules/@babel/runtime-corejs3/core-js-stable/inst [...]
\ No newline at end of file
diff --git a/framework/rest-api/webapp/rest-api/WEB-INF/web.xml b/framework/rest-api/webapp/rest-api/WEB-INF/web.xml
new file mode 100644
index 0000000000..28a09a2d14
--- /dev/null
+++ b/framework/rest-api/webapp/rest-api/WEB-INF/web.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
+ <display-name>Apache OFBiz - rest-api Component</display-name>
+ <description>rest-api Component of the Apache OFBiz Project</description>
+
+ <context-param>
+ <description>A unique name used to identify/recognize the local dispatcher for the Service Engine</description>
+ <param-name>localDispatcherName</param-name><param-value>rest-api</param-value>
+ </context-param>
+ <context-param>
+ <description>The Name of the Entity Delegator to use, defined in entityengine.xml</description>
+ <param-name>entityDelegatorName</param-name><param-value>default</param-value>
+ </context-param>
+ <filter>
+ <filter-name>Jersey REST Filter</filter-name>
+ <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
+ <init-param>
+ <param-name>jakarta.ws.rs.Application</param-name>
+ <param-value>org.apache.ofbiz.ws.rs.core.OFBizApiConfig</param-value>
+ </init-param>
+ <init-param>
+ <param-name>jersey.config.servlet.filter.staticContentRegex</param-name>
+ <param-value>/swagger/.*</param-value>
+ </init-param>
+ </filter>
+ <filter-mapping>
+ <filter-name>Jersey REST Filter</filter-name>
+ <url-pattern>/*</url-pattern>
+ </filter-mapping>
+ <listener>
+ <listener-class>
+ org.apache.ofbiz.ws.rs.listener.ApiContextListener
+ </listener-class>
+ </listener>
+</web-app>
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 46ca08d831..11ac720574 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
@@ -1675,7 +1675,7 @@ public class ModelService extends AbstractMap<String, Object> implements Seriali
} catch (GeneralException e) {
String errMsg = "Type conversion of field [" + paramName + "] to type [" + modelParam.getType() + "] failed for value \""
+ value + "\": " + e;
- Debug.logWarning("[ModelService.makeValid] : " + errMsg, MODULE);
+ Debug.logWarning("[ModelService.makeValid] : %s", MODULE, errMsg);
if (errorMessages != null) {
errorMessages.add(errMsg);
}