This is an automated email from the ASF dual-hosted git repository.
grv pushed a commit to branch trunk in repository https://gitbox.apache.org/repos/asf/ofbiz-plugins.git The following commit(s) were added to refs/heads/trunk by this push: new 13e4651 Implemented: (OFBIZ-11328) Added a new component to provide REST capabilities to OFBiz. (#35) 13e4651 is described below commit 13e465109bd0ab80b03910bc525fce5bc89ac6ba Author: girishvasmatkar <[hidden email]> AuthorDate: Fri Aug 14 21:38:23 2020 +0530 Implemented: (OFBIZ-11328) Added a new component to provide REST capabilities to OFBiz. (#35) * First commit with REST support for exportable services * Update README.adoc * Updated Terms of Service and Contact email address for OpenApi * Added a new BasicAuthFilter to generate JWT API token * Updated README * Removed README.md * Fixed checkstyle error --- ofbiz-rest-impl/HELP.adoc | 1 + ofbiz-rest-impl/LICENSE | 201 +++++++++++++++++ ofbiz-rest-impl/README.adoc | 157 +++++++++++++ ofbiz-rest-impl/build.gradle | 45 ++++ .../config/Ofbiz-rest-jerseyUiLabels.xml | 43 ++++ ofbiz-rest-impl/data/Ofbiz-rest-jerseyDemoData.xml | 23 ++ .../Ofbiz-rest-jerseySecurityGroupDemoData.xml | 36 +++ ...Ofbiz-rest-jerseySecurityPermissionSeedData.xml | 35 +++ ofbiz-rest-impl/data/Ofbiz-rest-jerseyTypeData.xml | 23 ++ .../data/helpdata/HELP_Ofbiz-rest-jersey.xml | 29 +++ ofbiz-rest-impl/documents/Ofbiz-rest-jersey.xml | 36 +++ ofbiz-rest-impl/entitydef/entitymodel.xml | 31 +++ ofbiz-rest-impl/ofbiz-component.xml | 61 ++++++ ofbiz-rest-impl/servicedef/services.xml | 33 +++ .../org/apache/ofbiz/ws/rs/ApiServiceRequest.java | 38 ++++ .../ofbiz/ws/rs/MethodNotAllowedException.java | 38 ++++ .../ofbiz/ws/rs/ServiceRequestProcessor.java | 85 ++++++++ .../apache/ofbiz/ws/rs/core/OFBizApiConfig.java | 43 ++++ .../ofbiz/ws/rs/listener/ApiContextListener.java | 63 ++++++ .../ofbiz/ws/rs/openapi/OFBizOpenApiReader.java | 242 +++++++++++++++++++++ .../ofbiz/ws/rs/openapi/OFBizResourceScanner.java | 65 ++++++ .../ws/rs/resources/AuthenticationResource.java | 76 +++++++ .../ofbiz/ws/rs/resources/IOFBizResource.java | 44 ++++ .../ofbiz/ws/rs/resources/OFBizResource.java | 41 ++++ .../ws/rs/resources/OFBizServiceResource.java | 133 +++++++++++ .../ofbiz/ws/rs/resources/OpenApiResource.java | 138 ++++++++++++ .../org/apache/ofbiz/ws/rs/response/Error.java | 102 +++++++++ .../org/apache/ofbiz/ws/rs/response/Success.java | 96 ++++++++ .../org/apache/ofbiz/ws/rs/security/AuthToken.java | 33 +++ .../org/apache/ofbiz/ws/rs/security/Secured.java | 33 +++ .../ofbiz/ws/rs/security/auth/APIAuthFilter.java | 133 +++++++++++ .../ws/rs/security/auth/HttpBasicAuthFilter.java | 128 +++++++++++ .../ofbiz/ws/rs/spi/AbstractExceptionMapper.java | 71 ++++++ .../ws/rs/spi/impl/GlobalExceptionMapper.java | 50 +++++ .../apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java | 58 +++++ .../spi/impl/JsonifiedParamConverterProvider.java | 71 ++++++ .../ofbiz/ws/rs/spi/impl/LinkSerializer.java | 44 ++++ .../org/apache/ofbiz/ws/rs/util/OpenApiUtil.java | 102 +++++++++ .../org/apache/ofbiz/ws/rs/util/RestApiUtil.java | 52 +++++ ofbiz-rest-impl/testdef/Ofbiz-rest-jerseyTests.xml | 26 +++ .../ofbiz-rest-jersey/WEB-INF/controller.xml | 47 ++++ .../webapp/ofbiz-rest-jersey/WEB-INF/web.xml | 61 ++++++ ofbiz-rest-impl/webapp/ofbiz-rest-jersey/index.jsp | 20 ++ ofbiz-rest-impl/webapp/swagger/WEB-INF/web.xml | 24 ++ ofbiz-rest-impl/webapp/swagger/favicon-16x16.png | Bin 0 -> 665 bytes ofbiz-rest-impl/webapp/swagger/favicon-32x32.png | Bin 0 -> 628 bytes .../webapp/swagger/oauth2-redirect.html | 68 ++++++ .../webapp/swagger/swagger-ui-bundle.js | 134 ++++++++++++ .../webapp/swagger/swagger-ui-bundle.js.map | 1 + .../webapp/swagger/swagger-ui-standalone-preset.js | 22 ++ .../swagger/swagger-ui-standalone-preset.js.map | 1 + ofbiz-rest-impl/webapp/swagger/swagger-ui.css | 4 + ofbiz-rest-impl/webapp/swagger/swagger-ui.css.map | 1 + ofbiz-rest-impl/webapp/swagger/swagger-ui.html | 63 ++++++ ofbiz-rest-impl/webapp/swagger/swagger-ui.js | 9 + ofbiz-rest-impl/webapp/swagger/swagger-ui.js.map | 1 + ofbiz-rest-impl/widget/CommonScreens.xml | 71 ++++++ ofbiz-rest-impl/widget/Ofbiz-rest-jerseyForms.xml | 26 +++ ofbiz-rest-impl/widget/Ofbiz-rest-jerseyMenus.xml | 29 +++ .../widget/Ofbiz-rest-jerseyScreens.xml | 40 ++++ 60 files changed, 3381 insertions(+) diff --git a/ofbiz-rest-impl/HELP.adoc b/ofbiz-rest-impl/HELP.adoc new file mode 100644 index 0000000..5bd7293 --- /dev/null +++ b/ofbiz-rest-impl/HELP.adoc @@ -0,0 +1 @@ +The Ofbiz-rest-jersey Help file template. \ No newline at end of file diff --git a/ofbiz-rest-impl/LICENSE b/ofbiz-rest-impl/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/ofbiz-rest-impl/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. diff --git a/ofbiz-rest-impl/README.adoc b/ofbiz-rest-impl/README.adoc new file mode 100644 index 0000000..e959aa7 --- /dev/null +++ b/ofbiz-rest-impl/README.adoc @@ -0,0 +1,157 @@ += 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" + } ] + } +} +---- + + + diff --git a/ofbiz-rest-impl/build.gradle b/ofbiz-rest-impl/build.gradle new file mode 100644 index 0000000..3123b2c --- /dev/null +++ b/ofbiz-rest-impl/build.gradle @@ -0,0 +1,45 @@ +/* + * 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. + */ + +project.rootProject.configurations.all { + exclude module: 'jsr311-api' + // exclude module: 'cxf-rt-frontend-jaxrs' +} + +dependencies { + pluginLibsCompile 'org.glassfish.jersey.containers:jersey-container-servlet:2.31' + pluginLibsCompile 'org.glassfish.jersey.media:jersey-media-multipart:2.31' + pluginLibsCompile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.31' + pluginLibsCompile 'org.glassfish.jersey.inject:jersey-hk2:2.31' + pluginLibsCompile 'io.swagger.core.v3:swagger-jaxrs2:2.1.2' + pluginLibsCompile 'io.swagger.core.v3:swagger-jaxrs2-servlet-initializer:2.1.2' + pluginLibsCompile 'io.swagger.core.v3:swagger-annotations:2.1.2' +} + +task install { + doLast { + // Install logic for this plugin + } +} + +task uninstall { + doLast { + // uninstall logic for this plugin + } +} diff --git a/ofbiz-rest-impl/config/Ofbiz-rest-jerseyUiLabels.xml b/ofbiz-rest-impl/config/Ofbiz-rest-jerseyUiLabels.xml new file mode 100644 index 0000000..2071e6e --- /dev/null +++ b/ofbiz-rest-impl/config/Ofbiz-rest-jerseyUiLabels.xml @@ -0,0 +1,43 @@ +<?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="http://ofbiz.apache.org/dtds/ofbiz-properties.xsd"> + <property key="Ofbiz-rest-jerseyApplication"> + <value xml:lang="en">Ofbiz-rest-jersey Application</value> + <value xml:lang="zh">Ofbiz-rest-jersey应用程序</value> + <value xml:lang="zh-TW">Ofbiz-rest-jersey應用程式</value> + </property> + <property key="Ofbiz-rest-jerseyCompanyName"> + <value xml:lang="en">OFBiz: Ofbiz-rest-jersey</value> + <value xml:lang="zh-TW">OFBiz: Ofbiz-rest-jersey</value> + </property> + <property key="Ofbiz-rest-jerseyCompanySubtitle"> + <value xml:lang="en">Part of the Apache OFBiz Family of Open Source Software</value> + <value xml:lang="it">Un modulo della famiglia di software open source Apache OFBiz</value> + <value xml:lang="zh">开源软件OFBiz的组成部分</value> + <value xml:lang="zh-TW">開源軟體OFBiz的組成部分</value> + </property> + <property key="Ofbiz-rest-jerseyViewPermissionError"> + <value xml:lang="en">You are not allowed to view this page.</value> + <value xml:lang="zh">不允许你浏览这个页面。</value> + <value xml:lang="zh-TW">不允許您檢視這個頁面.</value> + </property> +</resource> diff --git a/ofbiz-rest-impl/data/Ofbiz-rest-jerseyDemoData.xml b/ofbiz-rest-impl/data/Ofbiz-rest-jerseyDemoData.xml new file mode 100644 index 0000000..b76e67e --- /dev/null +++ b/ofbiz-rest-impl/data/Ofbiz-rest-jerseyDemoData.xml @@ -0,0 +1,23 @@ +<?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. +--> + +<entity-engine-xml> + +</entity-engine-xml> \ No newline at end of file diff --git a/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityGroupDemoData.xml b/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityGroupDemoData.xml new file mode 100644 index 0000000..cd952cd --- /dev/null +++ b/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityGroupDemoData.xml @@ -0,0 +1,36 @@ +<?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. +--> + +<entity-engine-xml> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="FULLADMIN" + permissionId="OFBIZ-REST-JERSEY_ADMIN"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="FLEXADMIN" + permissionId="OFBIZ-REST-JERSEY_CREATE"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="FLEXADMIN" + permissionId="OFBIZ-REST-JERSEY_DELETE"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="FLEXADMIN" + permissionId="OFBIZ-REST-JERSEY_UPDATE"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="FLEXADMIN" + permissionId="OFBIZ-REST-JERSEY_VIEW"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="VIEWADMIN" + permissionId="OFBIZ-REST-JERSEY_VIEW"/> + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="BIZADMIN" + permissionId="OFBIZ-REST-JERSEY_ADMIN"/> +</entity-engine-xml> diff --git a/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityPermissionSeedData.xml b/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityPermissionSeedData.xml new file mode 100644 index 0000000..8b4c4ed --- /dev/null +++ b/ofbiz-rest-impl/data/Ofbiz-rest-jerseySecurityPermissionSeedData.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. +--> + +<entity-engine-xml> + <SecurityPermission description="View operations in the Ofbiz-rest-jersey Component." + permissionId="OFBIZ-REST-JERSEY_VIEW"/> + <SecurityPermission description="Create operations in the Ofbiz-rest-jersey Component." + permissionId="OFBIZ-REST-JERSEY_CREATE"/> + <SecurityPermission description="Update operations in the Ofbiz-rest-jersey Component." + permissionId="OFBIZ-REST-JERSEY_UPDATE"/> + <SecurityPermission description="Delete operations in the Ofbiz-rest-jersey Component." + permissionId="OFBIZ-REST-JERSEY_DELETE"/> + <SecurityPermission description="ALL operations in the Ofbiz-rest-jersey Component." + permissionId="OFBIZ-REST-JERSEY_ADMIN"/> + + <SecurityGroupPermission fromDate="2001-05-13 12:00:00.0" groupId="SUPER" permissionId="OFBIZ-REST-JERSEY_ADMIN"/> + +</entity-engine-xml> diff --git a/ofbiz-rest-impl/data/Ofbiz-rest-jerseyTypeData.xml b/ofbiz-rest-impl/data/Ofbiz-rest-jerseyTypeData.xml new file mode 100644 index 0000000..b76e67e --- /dev/null +++ b/ofbiz-rest-impl/data/Ofbiz-rest-jerseyTypeData.xml @@ -0,0 +1,23 @@ +<?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. +--> + +<entity-engine-xml> + +</entity-engine-xml> \ No newline at end of file diff --git a/ofbiz-rest-impl/data/helpdata/HELP_Ofbiz-rest-jersey.xml b/ofbiz-rest-impl/data/helpdata/HELP_Ofbiz-rest-jersey.xml new file mode 100644 index 0000000..b9b7d08 --- /dev/null +++ b/ofbiz-rest-impl/data/helpdata/HELP_Ofbiz-rest-jersey.xml @@ -0,0 +1,29 @@ +<?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. +--> + +<section xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5.0" + xmlns:xl="http://www.w3.org/1999/xlink" + xmlns:xi="http://www.w3.org/2001/XInclude" + xsi:schemaLocation="http://docbook.org/ns/docbook ../../../content/dtd/docbook.xsd" + xmlns="http://docbook.org/ns/docbook"> + <title>Ofbiz-rest-jersey Overview</title> + <para>The Ofbiz-rest-jersey Help file template.</para> +</section> + diff --git a/ofbiz-rest-impl/documents/Ofbiz-rest-jersey.xml b/ofbiz-rest-impl/documents/Ofbiz-rest-jersey.xml new file mode 100644 index 0000000..0cf2419 --- /dev/null +++ b/ofbiz-rest-impl/documents/Ofbiz-rest-jersey.xml @@ -0,0 +1,36 @@ +<?xml version="1.0"?> +<!-- +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. +--> + +<chapter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5.0" + xmlns:xl="http://www.w3.org/1999/xlink" + xmlns:xi="http://www.w3.org/2001/XInclude" + xsi:schemaLocation="http://docbook.org/ns/docbook ../../../applications/content/dtd/docbook.xsd" + xmlns="http://docbook.org/ns/docbook"> + + <title><anchor xml:id="Ofbiz-rest-jersey"/>The Ofbiz-rest-jersey Component + </title> + <section> + <title>Introduction</title> + <para> + </para> + </section> + <xi:include href="../data/helpdata/HELP_Ofbiz-rest-jersey.xml"/> + +</chapter> diff --git a/ofbiz-rest-impl/entitydef/entitymodel.xml b/ofbiz-rest-impl/entitydef/entitymodel.xml new file mode 100644 index 0000000..c204cff --- /dev/null +++ b/ofbiz-rest-impl/entitydef/entitymodel.xml @@ -0,0 +1,31 @@ +<?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. +--> + +<entitymodel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/entitymodel.xsd"> + <!-- ========================================================= --> + <!-- ======================== Defaults ======================= --> + <!-- ========================================================= --> + <title>Entity of Ofbiz-rest-jersey Component</title> + <description>None</description> + <copyright></copyright> + <version></version> + +</entitymodel> \ No newline at end of file diff --git a/ofbiz-rest-impl/ofbiz-component.xml b/ofbiz-rest-impl/ofbiz-component.xml new file mode 100644 index 0000000..c1aa1da --- /dev/null +++ b/ofbiz-rest-impl/ofbiz-component.xml @@ -0,0 +1,61 @@ +<?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="ofbiz-rest-jersey" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="http://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"/> + <!-- entity resources: model(s), eca(s), group, and data definitions --> + <entity-resource type="model" reader-name="main" loader="main" location="entitydef/entitymodel.xml"/> + <!-- <entity-resource type="eca" reader-name="main" loader="main" location="entitydef/eecas.xml"/> --> + <entity-resource type="data" reader-name="seed" loader="main" location="data/Ofbiz-rest-jerseyTypeData.xml"/> + <entity-resource type="data" reader-name="seed" loader="main" + location="data/Ofbiz-rest-jerseySecurityPermissionSeedData.xml"/> + <entity-resource type="data" reader-name="demo" loader="main" + location="data/Ofbiz-rest-jerseySecurityGroupDemoData.xml"/> + <entity-resource type="data" reader-name="demo" loader="main" location="data/Ofbiz-rest-jerseyDemoData.xml"/> + + <!-- service resources: model(s), eca(s) and group definitions --> + <service-resource type="model" loader="main" location="servicedef/services.xml"/> + <!-- + <service-resource type="eca" loader="main" location="servicedef/secas.xml"/> + <service-resource type="group" loader="main" location="servicedef/groups.xml"/> + --> + + <test-suite loader="main" location="testdef/Ofbiz-rest-jerseyTests.xml"/> + + <!-- web applications; will be mounted when using the embedded container --> + <webapp name="ofbiz-rest-jersey" + title="Ofbiz-rest-jersey" + server="default-server" + location="webapp/ofbiz-rest-jersey" + base-permission="OFBTOOLS,OFBIZ-REST-JERSEY" + mount-point="/rest"/> + <webapp name="swagger" + title="Swagger Docs" + app-bar-display="false" + server="default-server" + location="webapp/swagger" + mount-point="/docs"/> +</ofbiz-component> diff --git a/ofbiz-rest-impl/servicedef/services.xml b/ofbiz-rest-impl/servicedef/services.xml new file mode 100644 index 0000000..3e5f419 --- /dev/null +++ b/ofbiz-rest-impl/servicedef/services.xml @@ -0,0 +1,33 @@ +<?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="http://ofbiz.apache.org/dtds/services.xsd"> + <description>Ofbiz-rest-jersey Services</description> + <vendor></vendor> + <version>1.0</version> + + <service name="noSyntaxError" engine="interface"> + <description> + Dummy service to prevent empty files and syntax error - Remove when the 1st real service will be added here + </description> + </service> + +</services> \ No newline at end of file diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/ApiServiceRequest.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/ApiServiceRequest.java new file mode 100644 index 0000000..d3541cf --- /dev/null +++ b/ofbiz-rest-impl/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/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.java new file mode 100644 index 0000000..9c10be0 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/MethodNotAllowedException.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 javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.Response; + +/** + * + */ +public class MethodNotAllowedException extends ClientErrorException { + + private static final long serialVersionUID = -3002310435429546325L; + + /** + * Construct a new Method Not Allowed exception. + */ + public MethodNotAllowedException(String message) { + super(message, Response.Status.METHOD_NOT_ALLOWED); + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java new file mode 100644 index 0000000..18ac305 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/ServiceRequestProcessor.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * 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.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; + +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.ModelParam; +import org.apache.ofbiz.service.ModelService; +import org.apache.ofbiz.service.ServiceUtil; +import org.apache.ofbiz.ws.rs.util.RestApiUtil; + +public class ServiceRequestProcessor { + + /** + * @param requestContext + * @return + * @throws GenericServiceException + */ + @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.action) && !service.action.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); + Map<String, Object> responseData = new LinkedHashMap<>(); + if (ServiceUtil.isSuccess(result)) { + Set<String> outParams = service.getOutParamNames(); + for (String outParamName : outParams) { + ModelParam outParam = service.getParam(outParamName); + if (!outParam.internal) { + Object value = result.get(outParamName); + if (UtilValidate.isNotEmpty(value)) { + responseData.put(outParamName, value); + } + } + } + return RestApiUtil.success((String) result.get(ModelService.SUCCESS_MESSAGE), responseData); + } else { + return RestApiUtil.error(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), + (String) result.get(ModelService.ERROR_MESSAGE)); + } + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java new file mode 100644 index 0000000..92648cd --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/core/OFBizApiConfig.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * 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.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.ofbiz.base.util.Debug; +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; + +public class OFBizApiConfig extends ResourceConfig { + 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(MultiPartFeature.class); + if (Debug.verboseOn()) { + register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO, + LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); + } + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java new file mode 100644 index 0000000..3517b6f --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/listener/ApiContextListener.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * 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 javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.apache.ofbiz.base.util.Debug; +import org.apache.ofbiz.entity.Delegator; +import org.apache.ofbiz.service.LocalDispatcher; +import org.apache.ofbiz.webapp.WebAppUtil; + +public class ApiContextListener implements ServletContextListener { + + public static final String MODULE = ApiContextListener.class.getName(); + private static ServletContext servletContext; + + /** + * + */ + public void contextInitialized(ServletContextEvent sce) { + servletContext = sce.getServletContext(); + Delegator delegator = WebAppUtil.getDelegator(servletContext); + LocalDispatcher dispatcher = WebAppUtil.getDispatcher(servletContext); + Debug.logInfo("Api Jersey Context initialized, delegator " + delegator + ", dispatcher", MODULE); + servletContext.setAttribute("delegator", delegator); + servletContext.setAttribute("dispatcher", dispatcher); + servletContext.setAttribute("security", WebAppUtil.getSecurity(servletContext)); + } + + /** + * + */ + 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.removeAttribute("security"); + context = null; + } + + public static ServletContext getApplicationCntx() { + return servletContext; + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java new file mode 100644 index 0000000..dcf8c19 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizOpenApiReader.java @@ -0,0 +1,242 @@ +/******************************************************************************* + * 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.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.ws.rs.HttpMethod; + +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.ModelService; +import org.apache.ofbiz.webapp.WebAppUtil; +import org.apache.ofbiz.ws.rs.listener.ApiContextListener; +import org.apache.ofbiz.ws.rs.util.OpenApiUtil; + +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.ArraySchema; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +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 Components components; + private Paths paths; + private Set<Tag> openApiTags; + @SuppressWarnings("rawtypes") + private Map<String, Schema> schemas; + private OpenAPI openApi; + + public OFBizOpenApiReader() { + openApiTags = new LinkedHashSet<>(); + } + + @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); + if (openApi.getTags() != null) { + openApiTags.addAll(openApi.getTags()); + } + + Tag serviceResourceTag = new Tag().name("Exported Services") + .description("OFBiz services that are exposed via REST interface with export attribute set to true"); + openApiTags.add(serviceResourceTag); + openApi.setTags(new ArrayList<Tag>(openApiTags)); + 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(); + } + + ServletContext servletContext = ApiContextListener.getApplicationCntx(); + LocalDispatcher dispatcher = WebAppUtil.getDispatcher(servletContext); + DispatchContext context = dispatcher.getDispatchContext(); + 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.export && UtilValidate.isNotEmpty(service.action)) { + SecurityRequirement security = new SecurityRequirement(); + security.addList("jwtToken"); + final Operation operation = new Operation().summary(service.description) + .description(service.description).addTagsItem("Exported Services").operationId(service.name) + .deprecated(false).addSecurityItem(security); + + PathItem pathItemObject = new PathItem(); + + if (service.action.equalsIgnoreCase(HttpMethod.GET)) { + final QueryParameter serviceInParam = (QueryParameter) new QueryParameter().required(true) + .description("Service In Parameters in JSON").name("inParams"); + Schema<?> refSchema = new Schema<>(); + refSchema.$ref(service.name + "Request"); + serviceInParam.schema(refSchema); + operation.addParametersItem(serviceInParam); + + } else if (service.action.equalsIgnoreCase(HttpMethod.POST)) { + RequestBody request = new RequestBody().description("Request Body for service " + service.name) + .content(new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, + new MediaType().schema(new Schema<>().$ref(service.name + "Request")))); + operation.setRequestBody(request); + } + + ApiResponses apiResponsesObject = new ApiResponses(); + ApiResponse successResponse = new ApiResponse().description("Success"); + Content content = new Content(); + MediaType jsonMediaType = new MediaType(); + Schema<?> refSchema = new Schema<>(); + refSchema.$ref(service.name + "Response"); + jsonMediaType.setSchema(refSchema); + setOutSchemaForService(service); + setInSchemaForService(service); + content.addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, jsonMediaType); + + apiResponsesObject.addApiResponse("200", successResponse.content(content)); + setPathItemOperation(pathItemObject, service.action.toUpperCase(), operation); + operation.setResponses(apiResponsesObject); + paths.addPathItem("/services/" + service.name, pathItemObject); + + } + } + + openApi.setPaths(paths); + openApi.setComponents(components); + + return openApi; + } + + 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 setOutSchemaForService(ModelService service) { + Schema<Object> parentSchema = new Schema<Object>(); + parentSchema.setDescription("Out Schema for service: " + service.name + " response"); + parentSchema.setType("object"); + parentSchema.addProperties("statusCode", new IntegerSchema().description("HTTP Status Code")); + parentSchema.addProperties("statusDescription", new StringSchema().description("HTTP Status Code Description")); + parentSchema.addProperties("successMessage", new StringSchema().description("Success Message")); + ObjectSchema dataSchema = new ObjectSchema(); + parentSchema.addProperties("data", dataSchema); + service.getOutParamNamesMap().forEach((name, type) -> { + Schema<?> schema = null; + Class<?> schemaClass = OpenApiUtil.getOpenApiSchema(type); + if (schemaClass == null) { + return; + } + try { + schema = (Schema<?>) schemaClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + } + if (schema instanceof ArraySchema) { + ArraySchema arraySchema = (ArraySchema) schema; + arraySchema.items(new StringSchema()); + } + dataSchema.addProperties(name, schema.description(name)); + }); + schemas.put(service.name + "Response", parentSchema); + } + + private void setInSchemaForService(ModelService service) { + Schema<Object> parentSchema = new Schema<Object>(); + parentSchema.setDescription("In Schema for service: " + service.name + " request"); + parentSchema.setType("object"); + service.getInParamNamesMap().forEach((name, type) -> { + Schema<?> schema = null; + Class<?> schemaClass = OpenApiUtil.getOpenApiSchema(type); + if (schemaClass == null) { + return; + } + try { + schema = (Schema<?>) schemaClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + } + parentSchema.addProperties(name, schema.description(name)); + }); + schemas.put(service.name + "Request", parentSchema); + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java new file mode 100644 index 0000000..0484224 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/openapi/OFBizResourceScanner.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * 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"); + } + + public OFBizResourceScanner() { + onlyConsiderResourcePackages = true; + } + + /** + * + */ + 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; + } + + /** + * + */ + protected boolean isIgnored(String classOrPackageName) { + if (UtilValidate.isEmpty(classOrPackageName)) { + return true; + } + boolean isIgnored = IGNORED.stream().anyMatch(classOrPackageName::startsWith); + return isIgnored; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java new file mode 100644 index 0000000..848c5ba --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/AuthenticationResource.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * 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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +import org.apache.ofbiz.base.util.UtilMisc; +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.security.AuthToken; +import org.apache.ofbiz.ws.rs.util.RestApiUtil; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; + + +@Path("/auth") +@Provider +@Tag(name = "Authentication Token Generating Resource", description = "Intended to provide generation of authentication tokens.") +public class AuthenticationResource extends OFBizResource { + + @Context + private HttpServletRequest httpRequest; + + @Context + private HttpServletResponse httpResponse; + + /** + * + */ + @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() { + httpRequest.setAttribute("delegator", getDelegator()); + httpRequest.setAttribute("dispatcher", getDispatcher()); + 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(getDelegator(), UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId"))); + Map<String, Object> tokenPayload = UtilMisc.toMap("access_token", jwtToken, "expires_in", + EntityUtilProperties.getPropertyValue("security", "security.jwt.token.expireTime", "1800", getDelegator()), "token_type", "Bearer"); + return RestApiUtil.success("Token granted.", tokenPayload); + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/IOFBizResource.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/IOFBizResource.java new file mode 100644 index 0000000..feff685 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/IOFBizResource.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * 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 javax.ws.rs.ext.Provider; + +import org.apache.ofbiz.entity.Delegator; +import org.apache.ofbiz.service.LocalDispatcher; +import org.apache.ofbiz.webapp.WebAppUtil; +import org.apache.ofbiz.ws.rs.listener.ApiContextListener; + +/** + * Resource Interface + */ +@Provider +public interface IOFBizResource { + + default Delegator getDelegator() { + Delegator delegator = WebAppUtil.getDelegator(ApiContextListener.getApplicationCntx()); + return delegator; + } + + default LocalDispatcher getDispatcher() { + LocalDispatcher dispatcher = WebAppUtil.getDispatcher(ApiContextListener.getApplicationCntx()); + return dispatcher; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizResource.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizResource.java new file mode 100644 index 0000000..53b2fef --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizResource.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.resources; + +import javax.servlet.ServletContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.ext.Provider; + +import org.apache.ofbiz.entity.Delegator; +import org.apache.ofbiz.service.LocalDispatcher; + +/** + * + */ +@Provider +public abstract class OFBizResource implements IOFBizResource { + + @Context + private ServletContext servletContext; + + private Delegator delegator = getDelegator(); + + private LocalDispatcher dispatcher = getDispatcher(); + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java new file mode 100644 index 0000000..d19c9f4 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OFBizServiceResource.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * 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 javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.ext.Provider; + +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.response.Success; +import org.apache.ofbiz.ws.rs.security.Secured; + +@Secured +@Path("/services") +@Provider +public class OFBizServiceResource extends OFBizResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpServletRequest httpRequest; + + /** + * @return + * @throws GenericServiceException + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response serviceList() throws GenericServiceException { + LocalDispatcher dispatcher = getDispatcher(); + 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.export && UtilValidate.isNotEmpty(service.action)) { + Map<String, Object> serviceMap = new LinkedHashMap<String, Object>(); + serviceMap.put("name", service.name); + serviceMap.put("description", service.description); + Link selfLink = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder().path(service.name)).type(service.action).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(); + } + + /** + * @param serviceRequest + * @param serviceName + * @return + * @throws IOException + * @throws GenericServiceException + */ + @GET + @Path("/{serviceName}") + @Produces(MediaType.APPLICATION_JSON) + @Secured + public Response invokeServiceByGet(@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", + getDispatcher(), "request", httpRequest)); + + } + + /** + * @param serviceInParams + * @param serviceName + * @return + * @throws IOException + * @throws GenericEntityException + * @throws GenericServiceException + */ + @POST + @Path("/{serviceName}") + @Produces(MediaType.APPLICATION_JSON) + public Response invokeServiceByPost(HashMap<String, Object> serviceInParams, @PathParam(value = "serviceName") String serviceName) + throws IOException, GenericEntityException, GenericServiceException { + ServiceRequestProcessor processor = new ServiceRequestProcessor(); + return processor.process( + UtilMisc.toMap("serviceName", serviceName, "httpVerb", HttpMethod.POST, "requestMap", serviceInParams, "dispatcher", getDispatcher(), + "request", httpRequest)); + + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java new file mode 100644 index 0000000..d2f3406 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/resources/OpenApiResource.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * 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 javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +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; + +@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; + + @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 { + boolean pretty = false; + 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(pretty ? Yaml.pretty(openApi) : Yaml.mapper().writeValueAsString(openApi)) + .type("application/yaml").build(); + } else { + return Response.status(Response.Status.OK) + .entity(pretty ? Json.pretty(openApi) : Json.mapper().writeValueAsString(openApi)) + .type(MediaType.APPLICATION_JSON_TYPE).build(); + } + } + + + private Info buildOpenApiInfo() { + Info info = new Info().version("1.0.0").title("OFBiz REST Store") + .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("[hidden email]") + .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/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java new file mode 100644 index 0000000..24c7732 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Error.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.JsonRootName; + +@JsonRootName(value = "error") +public class Error { + + private int statusCode; + private String statusDescription; + private String errorMessage; + private List<String> additionalErrors; + + public Error(int statusCode, String statusDescription, String errorMessage) { + this.statusCode = statusCode; + this.statusDescription = statusDescription; + this.errorMessage = errorMessage; + } + + public Error(int statusCode, String statusDescription, String errorMessage, List<String> additionalErrors) { + this.statusCode = statusCode; + this.statusDescription = statusDescription; + this.errorMessage = errorMessage; + this.additionalErrors = additionalErrors; + } + + /** + * @return the statusCode + */ + public int getStatusCode() { + return statusCode; + } + + /** + * @param statusCode the statusCode to set + */ + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + /** + * @return the statusDescription + */ + public String getStatusDescription() { + return statusDescription; + } + + /** + * @param statusDescription the statusDescription to set + */ + public void setStatusDescription(String statusDescription) { + this.statusDescription = statusDescription; + } + + /** + * @return the errorMessage + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * @param errorMessage the errorMessage to set + */ + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + /** + * @return the additionalErrors + */ + public List<String> getAdditionalErrors() { + return additionalErrors; + } + + /** + * @param additionalErrors the additionalErrors to set + */ + public void setAdditionalErrors(List<String> additionalErrors) { + this.additionalErrors = additionalErrors; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Success.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Success.java new file mode 100644 index 0000000..0a7eb75 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/response/Success.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.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; + + public Success(int statusCode, String statusDescription, String successMessage, Object data) { + this.statusCode = statusCode; + this.statusDescription = statusDescription; + this.successMessage = successMessage; + this.data = data; + } + + /** + * @return the statusCode + */ + public int getStatusCode() { + return statusCode; + } + + /** + * @param statusCode the statusCode to set + */ + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + /** + * @return the statusDescription + */ + public String getStatusDescription() { + return statusDescription; + } + + /** + * @param statusDescription the statusDescription to set + */ + public void setStatusDescription(String statusDescription) { + this.statusDescription = statusDescription; + } + + /** + * @return the successMessage + */ + public String getSuccessMessage() { + return successMessage; + } + + /** + * @param successMessage the successMessage to set + */ + public void setSuccessMessage(String successMessage) { + this.successMessage = successMessage; + } + + /** + * @return the data + */ + public Object getData() { + return data; + } + + /** + * @param data the data to set + */ + public void setData(Object data) { + this.data = data; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/AuthToken.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/AuthToken.java new file mode 100644 index 0000000..070d700 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/AuthToken.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * 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; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.ws.rs.NameBinding; + + +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface AuthToken { + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/Secured.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/Secured.java new file mode 100644 index 0000000..728d805 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/Secured.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * 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; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.ws.rs.NameBinding; + + +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Secured { + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java new file mode 100644 index 0000000..4709ed2 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/APIAuthFilter.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * 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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +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.ModelService; +import org.apache.ofbiz.webapp.control.JWTManager; +import org.apache.ofbiz.ws.rs.security.Secured; +import org.apache.ofbiz.ws.rs.util.RestApiUtil; + +/** + * Api Security + */ +@Secured +@Provider +public class APIAuthFilter implements ContainerRequestFilter { + + private static final String MODULE = APIAuthFilter.class.getName(); + + @Context + private ResourceInfo resourceInfo; + + @Context + private HttpServletRequest httpRequest; + + @Context + private ServletContext servletContext; + + private static final String AUTHENTICATION_SCHEME = "Bearer"; + private static final String REALM = "OFBiz"; + + /** + * + */ + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); + 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(jwtToken, JWTManager.getJWTKey(delegator)); + if (claims.containsKey(ModelService.ERROR_MESSAGE)) { + abortWithUnauthorized(requestContext, true, (String) claims.get(ModelService.ERROR_MESSAGE)); + } else { + GenericValue userLogin = extractUserLoginFromJwtClaim(delegator, claims); + if (UtilValidate.isEmpty(userLogin)) { + abortWithUnauthorized(requestContext, true, "Access Denied: User does not exist in the system"); + return; + } + httpRequest.setAttribute("userLogin", userLogin); + } + + } + + /** + * @param authorizationHeader + * @return + */ + private boolean isTokenBasedAuthentication(String authorizationHeader) { + return authorizationHeader != null && authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " "); + } + + /** + * @param requestContext + */ + 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, AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"").build()); + } else { + requestContext + .abortWith(RestApiUtil.error(Response.Status.FORBIDDEN.getStatusCode(), Response.Status.FORBIDDEN.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; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java new file mode 100644 index 0000000..15a268d --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/security/auth/HttpBasicAuthFilter.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * 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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.ForbiddenException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +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.security.AuthToken; +import org.apache.ofbiz.ws.rs.util.RestApiUtil; + + +@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 AUTHENTICATION_SCHEME = "Basic"; + private static final String REALM = "OFBiz"; + + /** + * @param requestContext + * @throws IOException + */ + @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()); + } + + } + + /** + * @param authorizationHeader + * @return + */ + private boolean isBasicAuth(String authorizationHeader) { + return authorizationHeader != null && authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " "); + } + + /** + * @param requestContext + */ + 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, AUTHENTICATION_SCHEME + " 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/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/AbstractExceptionMapper.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/AbstractExceptionMapper.java new file mode 100644 index 0000000..35daf4d --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/AbstractExceptionMapper.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * 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; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.ofbiz.ws.rs.response.Error; + +/* + * + */ +public class AbstractExceptionMapper { + /** + * @param status + * @param responseEntity + * @return + */ + protected Response errorResponse(int status, Error responseEntity) { + return customizeResponse(status, responseEntity); + } + + /** + * @param status + * @param responseEntity + * @param t + * @return + */ + protected Response errorResponse(int status, Error responseEntity, Throwable t) { + return customizeResponse(status, responseEntity); + } + + /** + * @param ex + * @return + */ + protected Response.StatusType getStatusType(Throwable ex) { + if (ex instanceof WebApplicationException) { + return ((WebApplicationException) ex).getResponse().getStatusInfo(); + } else { + return Response.Status.INTERNAL_SERVER_ERROR; + } + } + + /** + * @param status + * @param responseEntity + * @return + */ + private Response customizeResponse(int status, Error responseEntity) { + return Response.status(status).entity(responseEntity).type(MediaType.APPLICATION_JSON).build(); + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java new file mode 100644 index 0000000..af08942 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/GlobalExceptionMapper.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * 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 javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +import org.apache.ofbiz.base.util.Debug; +import org.apache.ofbiz.ws.rs.response.Error; +import org.apache.ofbiz.ws.rs.spi.AbstractExceptionMapper; + +@Provider +public class GlobalExceptionMapper extends AbstractExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Throwable> { + + /** + * Module Name Used for debugging + */ + private static final String MODULE = GlobalExceptionMapper.class.getName(); + + /** + * + */ + @Override + public Response toResponse(Throwable throwable) { + Debug.logError(throwable.getMessage(), MODULE); + if (Debug.verboseOn()) { + throwable.printStackTrace(); + } + Response.StatusType type = getStatusType(throwable); + Error error = new Error(type.getStatusCode(), type.getReasonPhrase(), throwable.getMessage()); + return errorResponse(type.getStatusCode(), error); + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java new file mode 100644 index 0000000..7b3f14c --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JacksonConfig.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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 javax.ws.rs.core.Link; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; + +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.module.SimpleModule; + +@Provider +public class JacksonConfig implements ContextResolver<ObjectMapper> { + + private final ObjectMapper objectMapper; + + public JacksonConfig() { + objectMapper = new ObjectMapper(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + SimpleModule simpleModule = new SimpleModule(); + simpleModule.addSerializer(Link.class, new LinkSerializer()); + objectMapper.registerModule(simpleModule); + } + + /** + * + */ + @Override + public ObjectMapper getContext(Class<?> type) { + return objectMapper; + } + +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java new file mode 100644 index 0000000..fff65ec --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/JsonifiedParamConverterProvider.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * 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.Map; + +import javax.ws.rs.ext.ParamConverter; +import javax.ws.rs.ext.ParamConverterProvider; +import javax.ws.rs.ext.Provider; + +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; + +@Provider +public class JsonifiedParamConverterProvider implements ParamConverterProvider { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static ObjectMapper getMapper() { + return MAPPER; + } + + /** + * + */ + @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) { + Map<String, Object> map = null; + try { + map = getMapper().readValue(value, new TypeReference<Map<String, Object>>() { + }); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + return (T) new ApiServiceRequest(map); + } + + @Override + public String toString(T map) { + return ((ApiServiceRequest) map).getInParams().toString(); + } + }; + } + return null; + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java new file mode 100644 index 0000000..e7eac98 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/spi/impl/LinkSerializer.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * 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 javax.ws.rs.core.Link; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +public class LinkSerializer extends JsonSerializer<javax.ws.rs.core.Link> { + static final String HREF_PROPERTY = "href"; + + /** + * + */ + 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/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java new file mode 100644 index 0000000..0920109 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/OpenApiUtil.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.HashMap; +import java.util.Map; + +import io.swagger.v3.oas.models.media.ArraySchema; +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.NumberSchema; +import io.swagger.v3.oas.models.media.StringSchema; + +public final class OpenApiUtil { + + private OpenApiUtil() { + + } + + private static final Map<String, String> CLASS_ALIAS = new HashMap<>(); + private static final Map<String, Class<?>> JAVA_OPEN_API_MAP = 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", "Int"); + CLASS_ALIAS.put("java.lang.Integer", "Int"); + 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("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("Float", NumberSchema.class); + JAVA_OPEN_API_MAP.put("Double", NumberSchema.class); + JAVA_OPEN_API_MAP.put("BigDecimal", NumberSchema.class); + JAVA_OPEN_API_MAP.put("Timestamp", DateSchema.class); + + } + + + public static Class<?> getOpenApiSchema(String type) { + return JAVA_OPEN_API_MAP.get(CLASS_ALIAS.get(type)); + } +} diff --git a/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java new file mode 100644 index 0000000..309ca53 --- /dev/null +++ b/ofbiz-rest-impl/src/main/java/org/apache/ofbiz/ws/rs/util/RestApiUtil.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * 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 javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; + +import org.apache.ofbiz.ws.rs.response.Error; +import org.apache.ofbiz.ws.rs.response.Success; + +public final class RestApiUtil { + + private RestApiUtil() { + + } + + 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.getStatusCode()).type(MediaType.APPLICATION_JSON).entity(success).build(); + } + + 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(); + } + + /** + * @param message + * @return + */ + 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); + } +} diff --git a/ofbiz-rest-impl/testdef/Ofbiz-rest-jerseyTests.xml b/ofbiz-rest-impl/testdef/Ofbiz-rest-jerseyTests.xml new file mode 100644 index 0000000..35e51bf --- /dev/null +++ b/ofbiz-rest-impl/testdef/Ofbiz-rest-jerseyTests.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="Ofbiz-rest-jerseytests" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/test-suite.xsd"> + + +</test-suite> \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/controller.xml b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/controller.xml new file mode 100644 index 0000000..e079106 --- /dev/null +++ b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/controller.xml @@ -0,0 +1,47 @@ +<?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. +--> + +<site-conf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://ofbiz.apache.org/Site-Conf" xsi:schemaLocation="http://ofbiz.apache.org/Site-Conf http://ofbiz.apache.org/dtds/site-conf.xsd"> + <!-- The controller elements that are common to all OFBiz components + can be found in the following xml file. A component can override the + elements found in the common-controller.xml file. --> + <include location="component://common/webcommon/WEB-INF/common-controller.xml"/> + + <description>Ofbiz-rest-jersey Component Site Configuration File</description> + + <!-- Events to run on every request before security (chains exempt) --> + <!-- + <preprocessor> + </preprocessor> + --> + <!-- Events to run on every request after all other processing (chains exempt) --> + <!-- + <postprocessor> + <event name="test" type="java" path="org.apache.ofbiz.webapp.event.TestEvent" invoke="test"/> + </postprocessor> + --> + + <!-- Request Mappings --> + <request-map uri="main"><security https="true" auth="true"/><response name="success" type="view" value="main"/></request-map> + + <!-- View Mappings --> + <view-map name="main" type="screen" page="component://ofbiz-rest-jersey/widget/Ofbiz-rest-jerseyScreens.xml#main"/> +</site-conf> \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/web.xml b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/web.xml new file mode 100644 index 0000000..8bc16ed --- /dev/null +++ b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/WEB-INF/web.xml @@ -0,0 +1,61 @@ +<?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 - Ofbiz-rest-jersey Component</display-name> + <description>Ofbiz-rest-jersey Component of the Apache OFBiz Project</description> + + <!-- context-param> + <param-name>webSiteId</param-name> + <param-value>ofbiz-rest-jerseySite</param-value> + <description>A unique ID used to look up the WebSite entity. Only for component using a WebSite entity, like ecommerce</description> + </context-param--> + <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>ofbiz-rest-jersey</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>javax.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/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/index.jsp b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/index.jsp new file mode 100644 index 0000000..4ea7d0c --- /dev/null +++ b/ofbiz-rest-impl/webapp/ofbiz-rest-jersey/index.jsp @@ -0,0 +1,20 @@ +<%-- +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. +--%> + +<%response.sendRedirect("control/main");%> \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/WEB-INF/web.xml b/ofbiz-rest-impl/webapp/swagger/WEB-INF/web.xml new file mode 100644 index 0000000..f87b1e2 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/WEB-INF/web.xml @@ -0,0 +1,24 @@ +<?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 - Tbc-api-swagger Component</display-name> + <description>Tbc-api-swagger Component of the Apache OFBiz Project</description> +</web-app> diff --git a/ofbiz-rest-impl/webapp/swagger/favicon-16x16.png b/ofbiz-rest-impl/webapp/swagger/favicon-16x16.png new file mode 100644 index 0000000..8b194e6 Binary files /dev/null and b/ofbiz-rest-impl/webapp/swagger/favicon-16x16.png differ diff --git a/ofbiz-rest-impl/webapp/swagger/favicon-32x32.png b/ofbiz-rest-impl/webapp/swagger/favicon-32x32.png new file mode 100644 index 0000000..249737f Binary files /dev/null and b/ofbiz-rest-impl/webapp/swagger/favicon-32x32.png differ diff --git a/ofbiz-rest-impl/webapp/swagger/oauth2-redirect.html b/ofbiz-rest-impl/webapp/swagger/oauth2-redirect.html new file mode 100644 index 0000000..a013fc8 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/oauth2-redirect.html @@ -0,0 +1,68 @@ +<!doctype html> +<html lang="en-US"> +<title>Swagger UI: OAuth2 Redirect</title> +<body onload="run()"> +</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(); + } +</script> diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js b/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js new file mode 100644 index 0000000..16e5652 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js @@ -0,0 +1,134 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(function(){try{return require("esprima")}catch(e){}}()):"function"==typeof define&&define.amd?define(["esprima"],t):"object"==typeof exports?exports.SwaggerUIBundle=t(function(){try{return require("esprima")}catch(e){}}()):e.SwaggerUIBundle=t(e.esprima)}(window,function(e){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.ex [...] +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){ret [...] +/*! + Copyright (c) 2017 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/ +/*! + Copyright (c) 2017 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/ +!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var i=typeof r;if("string"===i||"number"===i)e.push(r);else if(Array.isArray(r)&&r.length){var a=o.apply(null,r);a&&e.push(a)}else if("object"===i)for(var s in r)n.call(r,s)&&r[s]&&e.push(s)}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(r=function(){return o}.apply(t,[]))||(e.exports=r)}()},function(e,t,n){e.exports=n(765)},function(e,t,n){e. [...] +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <[hidden email]> <http://feross.org> + * @license MIT + */ +var r=n(569),o=n(570),i=n(355);function a(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(a()<t)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=u.prototype:(null===e&&(e=new u(t)),e.length=t),e}function u(e,t,n){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a stri [...] +/*! + * @description Recursive object extending + * @author Viacheslav Lotsmanov <[hidden email]> + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 Viacheslav Lotsmanov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +function n(e){return e instanceof t||e instanceof Date||e instanceof RegExp}function r(e){if(e instanceof t){var n=t.alloc?t.alloc(e.length):new t(e.length);return e.copy(n),n}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function o(e){var t=[];return e.forEach(function(e,i){"object"==typeof e&&null!==e?Array.isArray(e)?t[i]=o(e):n(e)?t[i]=r(e):t[i]=a({},e):t[i]=e}),t}function i(e,t){return"__proto__" [...] +/** + * Checks if an event is supported in the current execution environment. + * + * NOTE: This will not work correctly for non-generic events such as `change`, + * `reset`, `load`, `error`, and `select`. + * + * Borrows from Modernizr. + * + * @param {string} eventNameSuffix Event name, e.g. "click". + * @param {?boolean} capture Check if the capture phase is supported. + * @return {boolean} True if the event is supported. + * @internal + * @license Modernizr 3.0.0pre (Custom Build) | MIT + */,e.exports=function(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}},function(e,t,n){"use strict";var r={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function o(e){var t=this.nativeEvent;if(t.getModifierState)return t.getModifierState( [...] +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017 Joachim Wester + * MIT license + */ +var n=this&&this.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},r=Object.prototype.hasOwnProperty;function o(e,t){return r.call(e,t)}function i(e){if(Array.isArray(e)){for(var t=new Array(e.length),n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(e);t=[];for(var r in e)o(e,r)&&t.push(r);return t}function a(e){return-1===e.indexOf("/")&&-1 [...] +/** @license React v16.8.6 + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,o=r?Symbol.for("react.element"):60103,i=r?Symbol.for("react.portal"):60106,a=r?Symbol.for("react.fragment"):60107,s=r?Symbol.for("react.strict_mode"):60108,u=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,l=r?Symbol.for("react.context"):60110,p=r?Symbol.for("react.async_mode"):60111,f=r?Symbol.for("react.concurrent_mode"):60111,h=r?Symbol.for("react.forward_ref"):6 [...] +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017 Joachim Wester + * MIT license + */ +var r=n(267),o=n(456),i=n(456);t.applyOperation=i.applyOperation,t.applyPatch=i.applyPatch,t.applyReducer=i.applyReducer,t.getValueByPointer=i.getValueByPointer,t.validate=i.validate,t.validator=i.validator;var a=n(267);t.JsonPatchError=a.PatchError,t.deepClone=a._deepClone,t.escapePathComponent=a.escapePathComponent,t.unescapePathComponent=a.unescapePathComponent;var s=new WeakMap,u=function(e){this.observers=new Map,this.obj=e},c=function(e,t){this.callback=e,this.observer=t};function [...] +/*! + * @description Recursive object extending + * @author Viacheslav Lotsmanov <[hidden email]> + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 Viacheslav Lotsmanov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +function n(e){return e instanceof t||e instanceof Date||e instanceof RegExp}function r(e){if(e instanceof t){var n=t.alloc?t.alloc(e.length):new t(e.length);return e.copy(n),n}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function o(e){var t=[];return e.forEach(function(e,i){"object"==typeof e&&null!==e?Array.isArray(e)?t[i]=o(e):n(e)?t[i]=r(e):t[i]=a({},e):t[i]=e}),t}function i(e,t){return"__proto__" [...] +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */t.parse=function(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");for(var n={},o=t||{},a=e.split(i),u=o.decode||r,c=0;c<a.length;c++){var l=a[c],p=l.indexOf("=");if(!(p<0)){var f=l.substr(0,p).trim(),h=l.substr(++p,l.length).trim();'"'==h[0]&&(h=h.slice(1,-1)),null==n[f]&&(n[f]=s(h,u))}}return n},t.serialize=function(e,t,n){var r=n||{},i=r.encode||o;if("function"!=typeof i)throw new TypeError("option encode is invalid");if(!a.test(e))throw new TypeError( [...] +/*! + * repeat-string <https://github.com/jonschlinkert/repeat-string> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */var r,o="";e.exports=function(e,t){if("string"!=typeof e)throw new TypeError("expected a string");if(1===t)return e;if(2===t)return e+e;var n=e.length*t;if(r!==e||void 0===r)r=e,o="";else if(o.length>=n)return o.substr(0,n);for(;n>o.length&&t>1;)1&t&&(o+=e),t>>=1,e+=e;return o=(o+=e).substr(0,n)}},function(e,t,n){"use strict";var r=n(39).assign,o=n(981),i=n(983),a=n(994),s=n(1009),u=n(190),c={default:n(1028),full:n(1029),commonmark:n(1030)};function l(e,t,n){this.src=t,this.env=n,this [...] +/*! + * Autolinker.js + * 0.28.1 + * + * Copyright(c) 2016 Gregory Jacobs <[hidden email]> + * MIT License + * + * https://github.com/gregjacobs/Autolinker.js + */o=[],void 0===(i="function"==typeof(r=function(){var e,t,n,r,o,i,a,s=function(e){e=e||{},this.version=s.version,this.urls=this.normalizeUrlsCfg(e.urls),this.email="boolean"!=typeof e.email||e.email,this.twitter="boolean"!=typeof e.twitter||e.twitter,this.phone="boolean"!=typeof e.phone||e.phone,this.hashtag=e.hashtag||!1,this.newWindow="boolean"!=typeof e.newWindow||e.newWindow,this.stripPrefix="boolean"!=typeof e.stripPrefix||e.stripPrefix;var t=this.hashtag;if(!1!==t&&"twitter"!==t& [...] +//# sourceMappingURL=swagger-ui-bundle.js.map \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js.map b/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js.map new file mode 100644 index 0000000..ba3506a --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui-bundle.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://SwaggerUIBundle/webpack/universalModuleDefinition","webpack://SwaggerUIBundle/webpack/bootstrap","webpack://SwaggerUIBundle/./node_modules/react/react.js","webpack://SwaggerUIBundle/./node_modules/immutable/dist/immutable.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs2/helpers/defineProperty.js","webpack://SwaggerUIBundle/./src/core/utils.js","webpack://SwaggerUIBundle/./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js" [...] \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js b/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js new file mode 100644 index 0000000..66f7007 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js @@ -0,0 +1,22 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(function(){try{return require("esprima")}catch(t){}}()):"function"==typeof define&&define.amd?define(["esprima"],e):"object"==typeof exports?exports.SwaggerUIStandalonePreset=e(function(){try{return require("esprima")}catch(t){}}()):t.SwaggerUIStandalonePreset=e(t.esprima)}(window,function(t){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].c [...] +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;function u(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){ret [...] +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <[hidden email]> <http://feross.org> + * @license MIT + */ +var r=n(237),i=n(238),o=n(135);function u(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(t,e){if(u()<e)throw new RangeError("Invalid typed array length");return a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=a.prototype:(null===t&&(t=new a(e)),t.length=e),t}function a(t,e,n){if(!(a.TYPED_ARRAY_SUPPORT||this instanceof a))return new a(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a stri [...] +/** @license React v16.8.6 + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */Object.defineProperty(e,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,i=r?Symbol.for("react.element"):60103,o=r?Symbol.for("react.portal"):60106,u=r?Symbol.for("react.fragment"):60107,s=r?Symbol.for("react.strict_mode"):60108,a=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,f=r?Symbol.for("react.context"):60110,l=r?Symbol.for("react.async_mode"):60111,h=r?Symbol.for("react.concurrent_mode"):60111,p=r?Symbol.for("react.forward_ref"):6 [...] +//# sourceMappingURL=swagger-ui-standalone-preset.js.map \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js.map b/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js.map new file mode 100644 index 0000000..672eed8 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui-standalone-preset.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://SwaggerUIStandalonePreset/webpack/universalModuleDefinition","webpack://SwaggerUIStandalonePreset/webpack/bootstrap","webpack://SwaggerUIStandalonePreset/./node_modules/immutable/dist/immutable.js","webpack://SwaggerUIStandalonePreset/./node_modules/react/react.js","webpack://SwaggerUIStandalonePreset/./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js","webpack://SwaggerUIStandalonePreset/./node_modules/js-yaml/lib/js-yaml/type.js","webpack [...] \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui.css b/ofbiz-rest-impl/webapp/swagger/swagger-ui.css new file mode 100644 index 0000000..c61e5a8 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui.css @@ -0,0 +1,4 @@ +.swagger-ui{ + /*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */font-family:sans-serif;color:#3b4151}.swagger-ui html{line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}.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 [...] + +/*# sourceMappingURL=swagger-ui.css.map*/ \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui.css.map b/ofbiz-rest-impl/webapp/swagger/swagger-ui.css.map new file mode 100644 index 0000000..5f2d91e --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///./src/style/main.scss","webpack:///./node_modules/tachyons-sass/scss/_normalize.scss","webpack:///./src/style/_type.scss","webpack:///main.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/tachyons-sass/scss/_i [...] \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui.html b/ofbiz-rest-impl/webapp/swagger/swagger-ui.html new file mode 100644 index 0000000..53636b1 --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/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/ofbiz-rest-impl/webapp/swagger/swagger-ui.js b/ofbiz-rest-impl/webapp/swagger/swagger-ui.js new file mode 100644 index 0000000..3d5d2ac --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/swagger-ui.js @@ -0,0 +1,9 @@ +!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()}(window,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=fu [...] +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <[hidden email]> <http://feross.org> + * @license MIT + */ +var r=n(418),o=n(419),a=n(420);function i(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function u(e,t){if(i()<t)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=c.prototype:(null===e&&(e=new c(t)),e.length=t),e}function c(e,t,n){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a stri [...] +//# sourceMappingURL=swagger-ui.js.map \ No newline at end of file diff --git a/ofbiz-rest-impl/webapp/swagger/swagger-ui.js.map b/ofbiz-rest-impl/webapp/swagger/swagger-ui.js.map new file mode 100644 index 0000000..843b47c --- /dev/null +++ b/ofbiz-rest-impl/webapp/swagger/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-corejs2/helpers/defineProperty.js","webpack://SwaggerUICore/./src/core/utils.js","webpack://SwaggerUICore/./node_modules/@babel/runtime-corejs2/helpers/classCallCheck.js","webpack://SwaggerUICore/./node_modules/@bab [...] \ No newline at end of file diff --git a/ofbiz-rest-impl/widget/CommonScreens.xml b/ofbiz-rest-impl/widget/CommonScreens.xml new file mode 100644 index 0000000..b99f18b --- /dev/null +++ b/ofbiz-rest-impl/widget/CommonScreens.xml @@ -0,0 +1,71 @@ +<?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. +--> + +<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://ofbiz.apache.org/Widget-Screen" + xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd"> + + <screen name="main-decorator"> + <section> + <actions> + <property-map resource="Ofbiz-rest-jerseyUiLabels" map-name="uiLabelMap" global="true"/> + <property-map resource="CommonUiLabels" map-name="uiLabelMap" global="true"/> + + <set field="layoutSettings.companyName" from-field="uiLabelMap.Ofbiz-rest-jerseyCompanyName" + global="true"/> + <set field="layoutSettings.companySubtitle" from-field="uiLabelMap.Ofbiz-rest-jerseyCompanySubtitle" + global="true"/> + + <set field="activeApp" value="ofbiz-rest-jersey" global="true"/> + <set field="applicationMenuName" value="MainAppBar" global="true"/> + <set field="applicationMenuLocation" + value="component://ofbiz-rest-jersey/widget/Ofbiz-rest-jerseyMenus.xml" global="true"/> + <set field="applicationTitle" from-field="uiLabelMap.Ofbiz-rest-jerseyApplication" global="true"/> + </actions> + <widgets> + <include-screen name="GlobalDecorator" location="component://common/widget/CommonScreens.xml"/> + </widgets> + </section> + </screen> + + <screen name="Ofbiz-rest-jerseyCommonDecorator"> + <section> + <actions> + </actions> + <widgets> + <decorator-screen name="main-decorator" location="${parameters.mainDecoratorLocation}"> + <decorator-section name="body"> + <section> + <condition> + <if-has-permission permission="OFBIZ-REST-JERSEY" action="_VIEW"/> + </condition> + <widgets> + <decorator-section-include name="body"/> + </widgets> + <fail-widgets> + <label style="h3">${uiLabelMap.Ofbiz-rest-jerseyViewPermissionError}</label> + </fail-widgets> + </section> + </decorator-section> + </decorator-screen> + </widgets> + </section> + </screen> +</screens> \ No newline at end of file diff --git a/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyForms.xml b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyForms.xml new file mode 100644 index 0000000..0fcdc58 --- /dev/null +++ b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyForms.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. +--> + +<forms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://ofbiz.apache.org/Widget-Form" + xsi:schemaLocation="http://ofbiz.apache.org/Widget-Form http://ofbiz.apache.org/dtds/widget-form.xsd"> + + +</forms> \ No newline at end of file diff --git a/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyMenus.xml b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyMenus.xml new file mode 100644 index 0000000..bf7c73c --- /dev/null +++ b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyMenus.xml @@ -0,0 +1,29 @@ +<?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. +--> + +<menus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ofbiz.apache.org/Widget-Menu" + xsi:schemaLocation="http://ofbiz.apache.org/Widget-Menu http://ofbiz.apache.org/dtds/widget-menu.xsd"> + <menu name="MainAppBar" title="${uiLabelMap.Ofbiz-rest-jerseyApplication}" extends="CommonAppBarMenu" + extends-resource="component://common/widget/CommonMenus.xml"> + <menu-item name="main" title="${uiLabelMap.CommonMain}"> + <link target="main"/> + </menu-item> + </menu> +</menus> \ No newline at end of file diff --git a/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyScreens.xml b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyScreens.xml new file mode 100644 index 0000000..05944e3 --- /dev/null +++ b/ofbiz-rest-impl/widget/Ofbiz-rest-jerseyScreens.xml @@ -0,0 +1,40 @@ +<?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. +--> + +<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://ofbiz.apache.org/Widget-Screen" + xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd"> + + <screen name="main"> + <section> + <actions> + <set field="headerItem" value="main"/><!-- this highlights the selected menu-item with name "main" --> + </actions> + <widgets> + <decorator-screen name="Ofbiz-rest-jerseyCommonDecorator" + location="${parameters.mainDecoratorLocation}"> + <decorator-section name="body"> + </decorator-section> + </decorator-screen> + </widgets> + </section> + </screen> + +</screens> \ No newline at end of file |
Free forum by Nabble | Edit this page |