diff --git a/.apt_generated/org/etsi/osl/.gitignore b/.apt_generated/org/etsi/osl/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..028eea2244813b1babae1f1e0b94b60cca2b7e0f
--- /dev/null
+++ b/.apt_generated/org/etsi/osl/.gitignore
@@ -0,0 +1 @@
+/controllers/
diff --git a/.classpath b/.classpath
new file mode 100644
index 0000000000000000000000000000000000000000..073b7891c9fd0f922d674989cff20817006d786b
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.factorypath b/.factorypath
new file mode 100644
index 0000000000000000000000000000000000000000..f4c37c192867923a8c960c0625494ec0db7a553b
--- /dev/null
+++ b/.factorypath
@@ -0,0 +1,3 @@
+
+
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..b83d22266ac8aa2f8df2edef68082c789727841d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644
index 0000000000000000000000000000000000000000..58d9323be7e1f162cc288c9ad3a3240c7b7aaceb
--- /dev/null
+++ b/.gitlab-ci.yml
@@ -0,0 +1,23 @@
+include:
+ - ci-templates/default.yml
+ - ci-templates/build.yml
+
+ - local: ci-templates/build.yml
+ rules:
+ - if: '$CI_COMMIT_REF_NAME == "main" || $CI_COMMIT_REF_NAME == "develop" || $CI_COMMIT_REF_PROTECTED'
+
+ - local: ci-templates/build_unprotected.yml
+ rules:
+ - if: '$CI_COMMIT_REF_NAME != "main" && $CI_COMMIT_REF_NAME != "develop" && !$CI_COMMIT_REF_PROTECTED'
+
+
+
+
+maven_build:
+ extends: .maven_build
+
+docker_build:
+ extends: .docker_build
+ needs:
+ - maven_build
+
diff --git a/.project b/.project
new file mode 100644
index 0000000000000000000000000000000000000000..b6d8eb89f538e97e0cc9f4ec73f5756edcf6d924
--- /dev/null
+++ b/.project
@@ -0,0 +1,23 @@
+
+
+ org.etsi.osl.controllers.capif.invoker
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+ org.eclipse.m2e.core.maven2Builder
+
+
+
+
+
+ org.eclipse.jdt.core.javanature
+ org.eclipse.m2e.core.maven2Nature
+
+
diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 0000000000000000000000000000000000000000..29abf999564110a0d6aca109f55f439c72b7031c
--- /dev/null
+++ b/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,6 @@
+eclipse.preferences.version=1
+encoding//src/main/java=UTF-8
+encoding//src/main/resources=UTF-8
+encoding//src/test/java=UTF-8
+encoding//src/test/resources=UTF-8
+encoding/=UTF-8
diff --git a/.settings/org.eclipse.jdt.apt.core.prefs b/.settings/org.eclipse.jdt.apt.core.prefs
new file mode 100644
index 0000000000000000000000000000000000000000..fa6bcfb3fdb3a5ff5ccf658c79e656a02d8dbf61
--- /dev/null
+++ b/.settings/org.eclipse.jdt.apt.core.prefs
@@ -0,0 +1,5 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.apt.aptEnabled=true
+org.eclipse.jdt.apt.genSrcDir=.apt_generated
+org.eclipse.jdt.apt.genTestSrcDir=.apt_generated_tests
+org.eclipse.jdt.apt.reconcileEnabled=true
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000000000000000000000000000000000000..1f24da180636d5ccebadb72119e9495de5d6e0d4
--- /dev/null
+++ b/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,10 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.methodParameters=generate
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=17
+org.eclipse.jdt.core.compiler.compliance=17
+org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
+org.eclipse.jdt.core.compiler.processAnnotations=enabled
+org.eclipse.jdt.core.compiler.release=disabled
+org.eclipse.jdt.core.compiler.source=17
diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs
new file mode 100644
index 0000000000000000000000000000000000000000..f897a7f1cb2389f85fe6381425d29f0a9866fb65
--- /dev/null
+++ b/.settings/org.eclipse.m2e.core.prefs
@@ -0,0 +1,4 @@
+activeProfiles=
+eclipse.preferences.version=1
+resolveWorkspaceProjects=true
+version=1
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..3ea563c993f0ede78f7973fc32ad8fcbf0aa52ed
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,7 @@
+FROM ibm-semeru-runtimes:open-17.0.7_7-jdk
+MAINTAINER osl.etsi.org
+
+RUN mkdir /opt/osl
+
+COPY target/org.etsi.osl.capif.invoker-0.0.1-SNAPSHOT-exec.jar /opt/osl
+CMD ["java", "-jar", "/opt/osl/org.etsi.osl.capif.invoker-0.0.1-SNAPSHOT-exec.jar"]
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/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/README.md b/README.md
index 40640a929e1080bc798dc7d1bdbddfe8fe37a290..f4736add87aa63083b3e6bf6e804a62fafb00a39 100644
--- a/README.md
+++ b/README.md
@@ -1,93 +1,245 @@
-# org.etsi.osl.controllers.capif.invoker
+# OSL CAPIF Invoker management service
+This service is an **OSL controller** which acts as a **CAPIF 3GPP API Invoker Management layer**. In a nutshell it:
-## Getting started
+- Registers and manages multiple CAPIF invokers each one registered as Resource Specification in OSL Resource Specification catalog under category invoker.capif.osl.etsi.org.
+- Talks to a CAPIF Core component (e.g. https://capifcore.org:443)
+- Uses ActiveMQ for internal messaging (e.g., TMF catalog operations, orchestration invocations, etc)
+- Can automatically onboard Invokers, and manage certificates (via public/private keys)
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
+When a request of a new Invoker resource is performed (via a Service Order from OpenSlice), an Invoker is automatically registered to CAPIF core services and provides back a Bearer AUTH TOKEN as well as all the discovered API services as Service characteristics, so they can be used subsequently by further invocation to the registered service.
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
+For example, it is possible during an orchestration to onboard automatically an Invoker and perform an API call to a CAPIF registered service provider.
+Moreover, OSL invokers, once onboarded perform periodic token refreshes.
-## Add your files
+The service performs the following:
+
+----------
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
+### π **1. Invoker Configuration from YAML**
-```
-cd existing_repo
-git remote add origin https://labs.etsi.org/rep/osl/code/addons/org.etsi.osl.controllers.capif.invoker.git
-git branch -M main
-git push -uf origin main
-```
+ Before launching the service, invokers need to be configured via Springboot environment variables, overriding the default application.yaml behavior.
+
+- Loads invoker definitions (name, keys, description, APIs) from `application.yml` into the `SpringCapifInvokersConfig` bean using Springβs `@ConfigurationProperties`.
+
+- This allows external configuration of multiple API Invokers.
-## Integrate with your tools
+Currently application.yaml onboards two example invokers with self-signed certificates. In general the
-- [ ] [Set up project integrations](https://labs.etsi.org/rep/osl/code/addons/org.etsi.osl.controllers.capif.invoker/-/settings/integrations)
+ capif:
-## Collaborate with your team
+ section in `application.yaml` configures the Spring Boot application to:
+- Register as an API Invoker with a CAPIF Core
+- Use secure credentials (optional keys)
+- Periodically refresh tokens
+- Discover available APIs
+- Define which invokers to onboard
+
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
+----------
-## Test and Deploy
+### βοΈ **2. On Startup (`BootstrapService`)**
-Use the built-in continuous integration in GitLab.
+- Authenticates with the CAPIF Core (`/getauth`) and if successful then
+
+- Creates a *TMF ResourceSpecification* **per Invoker** (via `CapifInvokerResource`), storing bearer tokens, API names, status, etc.
+
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
+----------
-***
+### π€ **3. Invoker Lifecycle Management (`InvokerManagement`)**
-# Editing this README
+For each configured Invoker the service:
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
+- Creates self-signed or PEM-based keys if needed.
+
+- Generates CSR and onboards the Invoker to CAPIF.
+
+- Discovers available APIs and matches them with the configured ones.
+
+- Sets up OAuth2 security context and bearer token.
+
+- Stores onboarded state internally and updates the corresponding TMF Resource.
+
-## Suggestions for a good README
+----------
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
+### π‘ **4. Communication with CAPIF Core (`CapifService`)**
-## Name
-Choose a self-explaining name for your project.
+- Handles:
+
+ - Auth and token exchange
+
+ - Invoker onboarding (`/api-invoker-management/...`)
+
+ - API discovery (`/service-apis/...`)
+
+ - Bearer token retrieval (`/capif-security/...`)
+
+- Supports TLS and optional mTLS using truststore or inline PEM certs.
+
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
+----------
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
+### π€ **5. TMF Resource Integration**
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
+- All invoker state is reflected into TMF Logical Resources using the `CatalogClient`.
+
+- Uses ActiveMQ/JMS to integrate with the rest of the OSL system (create/update/delete resource specs).
+
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
+----------
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
+### π°οΈ **6. Token Refreshing via Apache Camel**
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
+- Periodically refreshes:
+
+ - Auth tokens (`authorizeToCapifService`)
+
+ - Bearer tokens per invoker (`processBearerRefreshTokens`)
+
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
+## β
Configuration
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
+Let's analyze the `capif:` section in application.yaml :
+
+**CAPIF Registration Endpoint**
+
+Used to authorize the app to the Capif Service, get an auth access_token and a certificate (ca_root)
+
+ REGISTER_HOSTNAME: localhost
+ REGISTER_PORT: 8084
+ USER_NAME: custom_user
+ USER_PASSWORD: user_pass
+
+**CAPIF Core Connection Details**
+
+ Where the CAPIF Core (the registry/service broker) lives. Our app will send API calls like onboarding and discovery here.
+
+ CAPIF_HOSTNAME: capifcore
+ CAPIF_PORT: 443
+
+**CAPIF API Paths**
+
+ ONBOARDING_URL: api-provider-management/v1/registrations
+ ONBOARDING_URL_INVOKER: api-invoker-management/v1/onboardedInvokers
+ DISCOVER_URL: service-apis/v1/allServiceAPIs
+
+These are the REST endpoints for:
+- Registering our own invokers
+- Discovering available service APIs
+
+> The app authorizes to the CAPI core service with the accessToken got
+> by the previous endpoint This follows the CAPIF spec for common API
+> exposure (3GPP TS 29.222 / 33.122).
+
+**Security Settings**
+
+ ALLOW_INSECURE: true
+ TRUSTSTORE_PATH: none
+ TRUSTSTORE_PASSWORD: none
+
+ALLOW_INSECURE: true disables strict TLS cert validation (dev/testing mode).
+
+If you want mutual TLS (mTLS), you'd set:
+- A real TRUSTSTORE_PATH
+- A truststore password
+- Turn ALLOW_INSECURE to false
+
+**Token Refresh Intervals**
+
+ authRefreshTokensPeriod: 36000
+ processBearerRefreshTokenPeriod: 180000
+
+- authRefreshTokensPeriod: how often (ms) to refresh CAPIF access tokens.
+- processBearerRefreshTokenPeriod: how often bearer tokens are refreshed and checked.
+
+This ensures long-running services donβt expire.
+
+
+ Configured Invokers
+
+ invokers:
+ - name: exampleInvoker
+ description: an example invoker
+ privatekey: selfsign
+ publickey: selfsign
+ apinames:
+ - api: hello_api_demo
+
+
+Each `invoker` block represents an **API Invoker you want to onboard** to CAPIF.
+
+There are two types shown:
+There are two types shown:
+
+#### π§ͺ Simple test entries
+
+ privatekey: selfsign
+ publickey: selfsign
+
+Used when your app will auto-generate keys or use placeholders.
+
+#### π PEM Key-based Invoker
+
+ privatekey: |
+ -----BEGIN PRIVATE KEY-----
+ ...
+ publickey: "-----BEGIN PUBLIC KEY-----..."
+This allows using **real asymmetric keys**, which CAPIF uses for identity and authentication.
+
+Each invoker:
+
+- Has a `name`, `description`, and optional `invokerversion`
+
+- Registers for specific APIs like `hello_api_demo`
+
+
+here is a simple diagram of performed actions:
+
+
+
+
+
+
+## π€ **Using the OSL CAPIF invoker service**
+
+From the above example configuration, we will get registered in our OSL Resource Specification catalog two invokers: exampleInvoker and exampleInvoker2.
+
+Use them as Resource Specification(s) assigned in a Resource Facing Service.
+
+
+### π¦ **Resource Specification Characteristics**
+
+| Name | Value Source | Description |
+|--|--|--|
+|`bearerAccessToken` | Token from CAPIF | OAuth bearer token assigned to Invoker |
+| `reqApiNames_0`, `reqApiNames_1`, ... | From `invoker.apinames` list | Requested CAPIF APIs |
+| `status.discoveredServiceAPIs` | CAPIF API discovery result (JSON) | APIs discovered from CAPIF Core |
+| `status.state` | Invoker state enum (e.g., CONFIGURED) | Current CAPIF onboarding status |
+| `status.infoMessage` | String (e.g., error or health status) | Any message for the user/operator |
+
+----------
+
+### β¨ Notes
+- These characteristics follow the TMF Open API model (e.g. `ResourceSpecificationCharacteristic` and `ResourceSpecificationCharacteristicValue`).
+- All characteristics are set as **non-configurable** (`configurable: false`).
+- Value types are all **TEXT**.
+
+
+The above Resource Specification Characteristics will be also exposed as Service Specification Characteristics.
+
+Then you can insert this Resource Facing Service Specification as a related Service Specification in a Customer Facing Service Specification.
+
+Here is an example rule that will get the latest Bearer and perform an API invocation (POST in this example) to an API provider register in the CAPIF server.
+
+
+
+
+The result will be stored in another characteristic called `myresponse`
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-## License
-For open source projects, say how it is licensed.
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
diff --git a/ci-templates/build.yml b/ci-templates/build.yml
new file mode 100644
index 0000000000000000000000000000000000000000..c0ff25498f2df442bc6fe61079f7088417f50804
--- /dev/null
+++ b/ci-templates/build.yml
@@ -0,0 +1,24 @@
+.maven_build:
+ extends: .default
+ stage: build
+ image: maven:3.9.5-ibm-semeru-17-focal
+ script:
+ - mvn deploy -s ci_settings.xml -Dversion=$APP_VERSION
+ artifacts:
+ paths:
+ - target/
+
+.docker_build:
+ extends: .default
+ stage: build
+ image:
+ name: gcr.io/kaniko-project/executor:debug
+ entrypoint: [""]
+ script:
+ - export DOCKER_TAG=$APP_VERSION
+ - |
+ if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
+ echo "Pushing Docker image with tag 'latest'"
+ export DOCKER_TAG=latest
+ fi
+ - /kaniko/executor --context "${CI_PROJECT_DIR}" --dockerfile "${CI_PROJECT_DIR}/Dockerfile" --destination "${CI_REGISTRY_IMAGE}:$DOCKER_TAG"
diff --git a/ci-templates/default.yml b/ci-templates/default.yml
new file mode 100644
index 0000000000000000000000000000000000000000..e49b634243ca7c5870671034b0027e80ea233d53
--- /dev/null
+++ b/ci-templates/default.yml
@@ -0,0 +1,17 @@
+stages:
+ - .pre
+ - build
+ - test
+ - post
+ - security
+
+.default:
+ before_script:
+ - |
+ if [ "$CI_COMMIT_REF_PROTECTED" = true ] && [ -n "$CI_COMMIT_TAG" ]; then
+ export APP_VERSION=$CI_COMMIT_TAG
+ elif [ "$CI_COMMIT_REF_NAME" = "develop" ]; then
+ export APP_VERSION="develop"
+ else
+ export APP_VERSION=$CI_COMMIT_REF_NAME
+ fi
diff --git a/ci_settings.xml b/ci_settings.xml
new file mode 100644
index 0000000000000000000000000000000000000000..69ad06ed6c63795d191555afde6ea2d1da4e133d
--- /dev/null
+++ b/ci_settings.xml
@@ -0,0 +1,16 @@
+
+
+
+ gitlab-maven
+
+
+
+ Job-Token
+ ${CI_JOB_TOKEN}
+
+
+
+
+
+
diff --git a/helm/.helmignore b/helm/.helmignore
new file mode 100644
index 0000000000000000000000000000000000000000..0e8a0eb36f4ca2c939201c0d54b5d82a1ea34778
--- /dev/null
+++ b/helm/.helmignore
@@ -0,0 +1,23 @@
+# Patterns to ignore when building packages.
+# This supports shell glob matching, relative path matching, and
+# negation (prefixed with !). Only one pattern per line.
+.DS_Store
+# Common VCS dirs
+.git/
+.gitignore
+.bzr/
+.bzrignore
+.hg/
+.hgignore
+.svn/
+# Common backup files
+*.swp
+*.bak
+*.tmp
+*.orig
+*~
+# Various IDEs
+.project
+.idea/
+*.tmproj
+.vscode/
diff --git a/helm/Chart.yaml b/helm/Chart.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e8f838977672cafa966f3cfabf6692f5ec1b8248
--- /dev/null
+++ b/helm/Chart.yaml
@@ -0,0 +1,23 @@
+apiVersion: v2
+name: oslcapif
+description: OSL CAPIF invoker management controller
+
+# A chart can be either an 'application' or a 'library' chart.
+#
+# Application charts are a collection of templates that can be packaged into versioned archives
+# to be deployed.
+#
+# Library charts provide useful utilities or functions for the chart developer. They're included as
+# a dependency of application charts to inject those utilities and functions into the rendering
+# pipeline. Library charts do not define any templates and therefore cannot be deployed.
+type: application
+
+# This is the chart version. This version number should be incremented each time you make changes
+# to the chart and its templates, including the app version.
+# Versions are expected to follow Semantic Versioning (https://semver.org/)
+version: 0.0.1
+
+# This is the version number of the application being deployed. This version number should be
+# incremented each time you make changes to the application. Versions are not expected to
+# follow Semantic Versioning. They should reflect the version the application is using.
+appVersion: 0.0.1
diff --git a/helm/templates/_helpers.tpl b/helm/templates/_helpers.tpl
new file mode 100644
index 0000000000000000000000000000000000000000..89f9f71fba483f569751099ef78cdfb1da8a3f4c
--- /dev/null
+++ b/helm/templates/_helpers.tpl
@@ -0,0 +1,62 @@
+{{/*
+Expand the name of the chart.
+*/}}
+{{- define "openslice.name" -}}
+{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
+{{- end }}
+
+{{/*
+Create a default fully qualified app name.
+We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
+If release name contains chart name it will be used as a full name.
+*/}}
+{{- define "openslice.fullname" -}}
+{{- if .Values.fullnameOverride }}
+{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
+{{- else }}
+{{- $name := default .Chart.Name .Values.nameOverride }}
+{{- if contains $name .Release.Name }}
+{{- .Release.Name | trunc 63 | trimSuffix "-" }}
+{{- else }}
+{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
+{{- end }}
+{{- end }}
+{{- end }}
+
+{{/*
+Create chart name and version as used by the chart label.
+*/}}
+{{- define "openslice.chart" -}}
+{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
+{{- end }}
+
+{{/*
+Common labels
+*/}}
+{{- define "openslice.labels" -}}
+helm.sh/chart: {{ include "openslice.chart" . }}
+{{ include "openslice.selectorLabels" . }}
+{{- if .Chart.AppVersion }}
+app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
+{{- end }}
+app.kubernetes.io/managed-by: {{ .Release.Service }}
+{{- end }}
+
+{{/*
+Selector labels
+*/}}
+{{- define "openslice.selectorLabels" -}}
+app.kubernetes.io/name: {{ include "openslice.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+{{- end }}
+
+{{/*
+Create the name of the service account to use
+*/}}
+{{- define "openslice.serviceAccountName" -}}
+{{- if .Values.serviceAccount.create }}
+{{- default (include "openslice.fullname" .) .Values.serviceAccount.name }}
+{{- else }}
+{{- default "default" .Values.serviceAccount.name }}
+{{- end }}
+{{- end }}
diff --git a/helm/templates/deployment.yaml b/helm/templates/deployment.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2d0a64a50e0df9de24961e8f73899cad07ba1ede
--- /dev/null
+++ b/helm/templates/deployment.yaml
@@ -0,0 +1,42 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ namespace: {{ .Release.Namespace }}
+ labels:
+ app: {{ include "openslice.fullname" . }}
+ org.etsi.osl.service: oslcapif
+ chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}"
+ {{- include "openslice.labels" . | nindent 4 }}
+ name: {{ include "openslice.fullname" . }}-oslcapif
+spec:
+ {{- if not .Values.autoscaling.enabled }}
+ replicas: {{ .Values.replicaCount }}
+ {{- end }}
+ selector:
+ matchLabels:
+ app: {{ include "openslice.fullname" . }}
+ org.etsi.osl.service: oslcapif
+ {{- include "openslice.selectorLabels" . | nindent 6 }}
+ template:
+ metadata:
+ labels:
+ app: {{ include "openslice.fullname" . }}
+ org.etsi.osl.service: oslcapif
+ {{- include "openslice.selectorLabels" . | nindent 8 }}
+ spec:
+ containers:
+ - image: "{{ .Values.image.oslcapif.repository }}:{{ .Values.image.oslcapif.tag | default .Chart.AppVersion }}"
+ imagePullPolicy: {{ .Values.image.oslcapif.pullPolicy | default "Always" }}
+ name: {{ include "openslice.fullname" . }}-oslcapif
+ env:
+ - name: SPRING_APPLICATION_JSON
+ value: >-
+ {
+ "logging.level.org.springframework" : "{{ .Values.spring.logLevel | default "INFO" }}",
+ "logging.level.org.etsi.osl.controllers.oslcapif" : "{{ .Values.logLevel | default "INFO" }}"
+ }
+ resources:
+ {{- toYaml .Values.resources | nindent 12 }}
+ restartPolicy: Always
+
+
\ No newline at end of file
diff --git a/helm/values.yaml b/helm/values.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0f72b3f8e9f38b34f08539ba2c1b2dc6d8f4b3d4
--- /dev/null
+++ b/helm/values.yaml
@@ -0,0 +1,30 @@
+# Default values for osl capif invoker controller.
+
+replicaCount: 1
+
+image:
+ oslcapif:
+ repository: labs.etsi.org:5050/osl/code/addons/org.etsi.osl.controllers.capif.invoker
+ pullPolicy: Always
+ # Overrides the image tag whose default is the chart appVersion.
+ tag: "latest"
+
+logLevel: INFO
+spring:
+ loglevel: INFO
+
+autoscaling:
+ enabled: false
+ minReplicas: 1
+ maxReplicas: 100
+ targetCPUUtilizationPercentage: 80
+ targetMemoryUtilizationPercentage: 80
+
+serviceAccount:
+ # Specifies whether a service account should be created
+ create: true
+ # Annotations to add to the service account
+ annotations: {}
+ # The name of the service account to use.
+ # If not set and create is true, a name is generated using the fullname template
+ name: ""
diff --git a/lcm_rule.jpg b/lcm_rule.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..77a7ecd3754d9a1fdb87aa585b6bd37b8cdf8785
Binary files /dev/null and b/lcm_rule.jpg differ
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000000000000000000000000000000000000..95af1338549c6fd63cb8c9b1cf66084fd2e0b4fd
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,327 @@
+
+ 4.0.0
+ org.etsi.osl
+ org.etsi.osl.controllers.capif.invoker
+ 0.0.1-SNAPSHOT
+ org.etsi.osl.controllers.capif.invoker
+ a capif invoker controller
+
+
+
+ UTF-8
+ UTF-8
+ 3.2.2
+ 1.18.28
+ 2.1.0
+ 1.5.3.Final
+ 17
+ 4.0.0-RC2
+ 2.8.11
+ 2.0.0
+ apache_v2
+ 1.7.0
+ 1.7.0
+ 22.0.1
+ 1.1.0-SNAPSHOT
+
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-dependencies
+ ${spring.boot-version}
+ pom
+ import
+
+
+
+ org.apache.camel.springboot
+ camel-spring-boot-dependencies
+ ${camel.version}
+ pom
+ import
+
+
+
+ com.google.guava
+ guava
+ 32.0.0-jre
+
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-resource-server
+
+
+
+ com.jayway.jsonpath
+ json-path
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webflux
+
+
+ org.springframework.security
+ spring-security-oauth2-client
+
+
+ org.springframework.security
+ spring-security-core
+
+
+ org.springframework.security
+ spring-security-web
+
+
+ org.springframework.security
+ spring-security-config
+
+
+
+
+ org.projectlombok
+ lombok
+ provided
+ ${lombok-version}
+
+
+ org.openapitools
+ jackson-databind-nullable
+ 0.2.6
+
+
+
+ org.bouncycastle
+ bcpkix-jdk18on
+ 1.78
+
+
+
+ org.etsi.osl
+ org.etsi.osl.model.tmf
+ ${org.etsi.osl.model.tmf.version}
+
+
+
+
+ org.springdoc
+ springdoc-openapi-starter-webmvc-ui
+ ${springdoc.version}
+
+
+ org.springdoc
+ springdoc-openapi-ui
+ ${springdoc.openapiui.version}
+
+
+ org.springdoc
+ springdoc-openapi-security
+ ${springdoc.security.version}
+
+
+
+ org.mapstruct
+ mapstruct
+ ${mapstruct.version}
+
+
+ org.mapstruct
+ mapstruct-processor
+ ${mapstruct.version}
+
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+ compile
+
+
+ jakarta.validation
+ jakarta.validation-api
+ 3.0.2
+
+
+ org.jetbrains
+ annotations
+ 13.0
+ compile
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-activemq
+
+
+ org.apache.activemq
+ activemq-amqp
+ test
+
+
+ org.apache.qpid
+ proton-j
+
+
+
+
+ org.messaginghub
+ pooled-jms
+
+
+
+
+ org.apache.camel.springboot
+ camel-spring-boot-starter
+
+
+ org.apache.activemq
+ activemq-pool
+
+
+ org.apache.camel
+ camel-activemq
+
+
+ org.apache.activemq
+ activemq-broker
+
+
+
+
+ org.apache.camel.springboot
+ camel-service-starter
+
+
+
+ org.apache.camel.springboot
+ camel-http-starter
+
+
+ org.apache.camel
+ camel-jackson
+
+
+ org.apache.camel
+ camel-stream
+
+
+
+ dk.brics.automaton
+ automaton
+ 1.11-8
+
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ ${java.version}
+ ${java.version}
+
+ -parameters
+
+
+
+ org.mapstruct
+ mapstruct-processor
+ ${mapstruct.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok-version}
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ license-maven-plugin
+ ${maven-license-plugin.version}
+
+ false
+ ========================LICENSE_START=================================
+ =========================LICENSE_END==================================
+ *.json
+
+
+
+ generate-license-headers
+
+ update-file-header
+
+ process-sources
+
+ ${license.licenseName}
+
+
+
+
+ download-licenses
+
+ download-licenses
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ ${spring.boot-version}
+
+
+
+ repackage
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ ${spring.boot-version}
+
+ exec
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/ActiveMQComponentConfig.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/ActiveMQComponentConfig.java
new file mode 100644
index 0000000000000000000000000000000000000000..97197e6f93eed1d37f5f750c858690a67c1891bc
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/ActiveMQComponentConfig.java
@@ -0,0 +1,41 @@
+/*-
+ * ========================LICENSE_START=================================
+ * org.etsi.osl.bugzilla
+ * %%
+ * Copyright (C) 2019 openslice.io
+ * %%
+ * 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.
+ * =========================LICENSE_END==================================
+ */
+package org.etsi.osl.controllers.capif.invoker;
+
+import org.apache.camel.component.activemq.ActiveMQComponent;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import jakarta.jms.ConnectionFactory;
+
+/**
+ * @author ctranoris
+ *
+ */
+@Configuration
+public class ActiveMQComponentConfig {
+
+ @Bean(name = "activemq")
+ public ActiveMQComponent createComponent(ConnectionFactory factory) {
+ ActiveMQComponent activeMQComponent = new ActiveMQComponent();
+ activeMQComponent.setConnectionFactory(factory);
+ return activeMQComponent;
+ }
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/ApiResponse.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/ApiResponse.java
new file mode 100644
index 0000000000000000000000000000000000000000..aa7919445b03ad992ef63440bd6ead0fbb2432da
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/ApiResponse.java
@@ -0,0 +1,133 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.util.ArrayList;
+import java.util.List;
+import lombok.Data;
+
+@Data
+public class ApiResponse {
+
+
+ private List serviceAPIDescriptions;
+
+ public List getServiceAPIDescriptions() {
+ return serviceAPIDescriptions;
+ }
+
+ public void setServiceAPIDescriptions(List serviceAPIDescriptions) {
+ this.serviceAPIDescriptions = serviceAPIDescriptions;
+ }
+
+
+ @Data
+ public static class ServiceAPIDescription {
+ private String apiName;
+ private String apiId;
+ private ApiStatus apiStatus;
+ private List aefProfiles;
+ private String description;
+ private String supportedFeatures;
+ private ShareableInfo shareableInfo;
+ private String serviceAPICategory;
+ private String apiSuppFeats;
+ private PubApiPath pubApiPath;
+ private String ccfId;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class ApiStatus {
+ private List aefIds;
+
+ public List getAefIds() {
+ return aefIds;
+ }
+
+ public void setAefIds(List aefIds) {
+ this.aefIds = aefIds;
+ }
+ }
+
+
+ @Data
+ public static class AefProfile {
+ private String aefId;
+ private List versions;
+ private String protocol;
+ private String dataFormat;
+ private List securityMethods;
+ private List interfaceDescriptions;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class Version {
+ private String apiVersion;
+ private String expiry;
+ private List resources;
+ private List custOperations;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class Resource {
+ private String resourceName;
+ private String commType;
+ private String uri;
+ private String custOpName;
+ private List operations;
+ private String description;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class CustOperation {
+ private String commType;
+ private String custOpName;
+ private List operations;
+ private String description;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class InterfaceDescription {
+ private String ipv4Addr;
+ private int port;
+ private List securityMethods;
+
+ // Getters and setters ...
+ }
+
+ @Data
+ public static class ShareableInfo {
+ private boolean isShareable;
+ private List capifProvDoms;
+ public boolean isIsShareable() {
+ return isShareable;
+ }
+
+ public void setIsShareable(boolean isShareable) {
+ this.isShareable = isShareable;
+ }
+ }
+
+ public static class PubApiPath {
+ private List ccfIds;
+
+ public List getCcfIds() {
+ return ccfIds;
+ }
+
+ public void setCcfIds(List ccfIds) {
+ this.ccfIds = ccfIds;
+ }
+ }
+
+}
+
+
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/BootstrapService.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/BootstrapService.java
new file mode 100644
index 0000000000000000000000000000000000000000..472c8ab8a5ab3b74dc09608e47273944a8649a6b
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/BootstrapService.java
@@ -0,0 +1,109 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.net.URL;
+import java.util.List;
+import java.util.Map;
+import org.etsi.osl.tmf.common.model.Any;
+import org.etsi.osl.tmf.pm632.model.Characteristic;
+import org.etsi.osl.tmf.pm632.model.Organization;
+import org.etsi.osl.tmf.pm632.model.OrganizationAttributeValueChangeEvent;
+import org.etsi.osl.tmf.rcm634.model.LogicalResourceSpecification;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecification;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationRef;
+import org.etsi.osl.tmf.ri639.model.Resource;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.context.event.ApplicationStartedEvent;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.event.EventListener;
+import org.springframework.stereotype.Service;
+import jakarta.annotation.PreDestroy;
+import lombok.Data;
+
+/**
+ * @author ctranoris
+ */
+@Service
+public class BootstrapService {
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+
+
+ @Autowired
+ CatalogClient catalogClient;
+
+
+ @Autowired
+ InvokerManagement invokerManagement;
+
+
+ @Autowired
+ CapifService aCapifService;
+
+ @Value("${osl-controller.category}")
+ private String compcategory;
+
+ @Value("${osl-controller.version}")
+ private String compversion;
+
+ @Autowired
+ private ApplicationContext context;
+
+ /**
+ * This one is executed when the cridge service application starts
+ *
+ * It creates here a default model in OSL TMF
+ * Create any related Logical resource specifications
+ *
+ *
+ * @param event
+ * @throws Exception
+ */
+ @EventListener(ApplicationStartedEvent.class)
+ public void onApplicationEvent() {
+
+
+ //Register first to CAPIF service
+ try {
+ aCapifService.authorizeToCapifService();
+ } catch (Exception e) {
+ e.printStackTrace();
+ logger.error( "Cannot connect and authorize to CAPIF Server" );
+ int exitCode = SpringApplication.exit(context, () -> 1);
+ System.exit(exitCode);
+
+ }
+
+ //after a successful authorization we need to register a Resource Specification per Invoker name
+
+ Map availableInvokers = invokerManagement.loadInvokers();
+ for (CapifInvoker capifInvoker : availableInvokers.values() ) {
+ CapifInvokerResource rspec = new CapifInvokerResource( capifInvoker.getName(), compversion ,
+ capifInvoker.getDescription() , compcategory, capifInvoker);
+ LogicalResourceSpecification lrs = catalogClient.createOrUpdateResourceSpecByNameCategoryVersion( rspec.toRSpecCreate_InitRepo() );
+
+ logger.info( "Registered LogicalResourceSpecification to repository: " + lrs.getId() );
+ }
+
+
+ logger.info( "Bootstrap process finished. Waiting for Invoker requests." );
+
+ }
+
+
+
+
+
+
+ @PreDestroy
+ private void stop() {
+ logger.info("Closing due to ContextStoppedEvent ");
+ }
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CISpringBoot.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CISpringBoot.java
new file mode 100644
index 0000000000000000000000000000000000000000..b96f982d4d111bd2e305d27d553563d6c63c31bb
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CISpringBoot.java
@@ -0,0 +1,66 @@
+/*-
+ * ========================LICENSE_START=================================
+ * org.etsi.osl.tmf.api
+ * %%
+ * Copyright (C) 2019 openslice.io
+ * %%
+ * 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.
+ * =========================LICENSE_END==================================
+ */
+package org.etsi.osl.controllers.capif.invoker;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.ExitCodeGenerator;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+import org.springframework.context.ApplicationContext;
+
+
+@SpringBootApplication
+@EntityScan(basePackages = {"org.etsi.osl.controllers.capif.invoker","org.etsi.osl.example.capif.invoker.api"})
+
+public class CISpringBoot implements CommandLineRunner {
+
+ private static ApplicationContext applicationContext;
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+
+ @Override
+ public void run(String... arg0) throws Exception {
+ if (arg0.length > 0 && arg0[0].equals("exitcode")) {
+ throw new ExitException();
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ logger.info("=========== STARTING org.etsi.osl.controllers.capif.invoker ==============================");
+ applicationContext = new SpringApplication(CISpringBoot.class).run(args);
+
+ }
+
+ class ExitException extends RuntimeException implements ExitCodeGenerator {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public int getExitCode() {
+ return 10;
+ }
+
+ }
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CSRGenerator.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CSRGenerator.java
new file mode 100644
index 0000000000000000000000000000000000000000..184ff83bbd089ae456b19cf97dbb210784e0b1af
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CSRGenerator.java
@@ -0,0 +1,112 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.io.StringWriter;
+import java.security.*;
+import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.RSAPublicKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+
+public class CSRGenerator {
+
+ static {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+
+ // Generate CSR using derived Public Key and provided Private Key
+ public static PKCS10CertificationRequest generateCSR(PrivateKey privateKey, PublicKey publicKey, String subjectDN) throws Exception {
+ X500Name subject = new X500Name(subjectDN);
+
+ JcaPKCS10CertificationRequestBuilder csrBuilder =
+ new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
+
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
+ .setProvider("BC")
+ .build(privateKey);
+
+ return csrBuilder.build(signer);
+ }
+
+ // Helper to load a private key from PEM-formatted string
+ public static PrivateKey loadPrivateKeyFromPEM(String pemKey) throws Exception {
+ String privKeyPEM = pemKey.replace("-----BEGIN PRIVATE KEY-----", "")
+ .replace("-----END PRIVATE KEY-----", "")
+ .replaceAll("\\s+", "");
+
+ byte[] decoded = Base64.getDecoder().decode(privKeyPEM);
+ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
+ return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
+ }
+
+ // Helper to load a public key from PEM-formatted string
+ public static PublicKey loadPublicKeyFromPEM(String pemKey) throws Exception {
+ String publicKeyPEM = pemKey
+ .replace("-----BEGIN PUBLIC KEY-----", "")
+ .replace("-----END PUBLIC KEY-----", "")
+ .replaceAll("\\s", "");
+
+ byte[] decoded = Base64.getDecoder().decode(publicKeyPEM);
+
+ X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // or EC if using EC keys
+ return keyFactory.generatePublic(keySpec);
+ }
+
+ // Derive Public Key from Private Key (RSA only)
+ public static PublicKey derivePublicKey(PrivateKey privateKey) throws Exception {
+ RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) privateKey;
+ RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(
+ rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+ return keyFactory.generatePublic(publicKeySpec);
+ }
+
+ public static String convertToPem(PublicKey publicKey) {
+ String encodedKey = Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(publicKey.getEncoded());
+ return "-----BEGIN PUBLIC KEY-----\n" + encodedKey + "\n-----END PUBLIC KEY-----";
+ }
+
+
+ public static String getCSR( String privateKeyPem, String publicKeyPem, String subjectDN ) {
+
+
+ try {
+
+ PrivateKey privateKey = loadPrivateKeyFromPEM(privateKeyPem);
+ PublicKey publicKey = loadPublicKeyFromPEM(publicKeyPem);
+
+
+
+ //String subjectDN = "CN=myapp.example.com,O=MyCompany,L=Athens,C=GR";
+
+ PKCS10CertificationRequest csr = generateCSR( privateKey, publicKey , subjectDN);
+
+ StringWriter csrPem = new StringWriter();
+ try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrPem)) {
+ pemWriter.writeObject(csr);
+ }
+
+ return csrPem.toString();
+
+
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+
+ return null;
+
+
+ }
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvoker.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvoker.java
new file mode 100644
index 0000000000000000000000000000000000000000..92fd608108357ec63b30835bb514a3920d786833
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvoker.java
@@ -0,0 +1,310 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.RSAPublicKeySpec;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import lombok.Builder;
+
+public class CapifInvoker {
+
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+
+ // this is used only on slef sign tests
+ @Builder.Default
+ private KeyPair akeyPair = generateRSAKeyPair();
+ private String name;
+ private String description;
+ private String privateKey;
+ private String publicKey;
+ private String apiInvokerPublicKeyCSR;
+ private String certificate;
+ String bearerAccessToken;
+ private int bearerExpiresIn;
+ private String discoveredServiceAPIs;
+
+ private CapifInvokerState capifInvokerState = CapifInvokerState.UNKNOWN;
+
+ @Builder.Default
+ List reqApiNames = new ArrayList<>();
+
+ @Builder.Default
+ Map serviceApis = new ConcurrentHashMap<>();
+ String invokerid;
+
+ /**
+ * @param name the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * @param aprivateKey the privateKey to set
+ */
+ public void setPrivateKey(String aprivateKey) {
+ if (aprivateKey.equalsIgnoreCase("selfsign")) {
+ aprivateKey = "-----BEGIN PRIVATE KEY-----\n"
+ + Base64.getMimeEncoder().encodeToString(akeyPair.getPrivate().getEncoded())
+ + "\n-----END PRIVATE KEY-----";
+ }
+ this.privateKey = aprivateKey;
+
+
+ }
+
+ /**
+ * @return the discoveredServiceAPIs
+ */
+ public String getDiscoveredServiceAPIs() {
+ return discoveredServiceAPIs;
+ }
+
+ /**
+ * @param discoveredServiceAPIs the discoveredServiceAPIs to set
+ */
+ public void setDiscoveredServiceAPIs(String discoveredServiceAPIs) {
+ this.discoveredServiceAPIs = discoveredServiceAPIs;
+ }
+
+ public String getPrivateKey() {
+ if (this.privateKey.equalsIgnoreCase("selfsign")) {
+ setPrivateKey(this.privateKey);
+ }
+
+ return this.privateKey;
+ }
+
+ /**
+ * @param apublicKey the publicKey to set
+ */
+ public void setPublicKey(String apublicKey) {
+ if (apublicKey.equalsIgnoreCase("selfsign")) {
+ apublicKey = "-----BEGIN PUBLIC KEY-----\n"
+ + Base64.getMimeEncoder().encodeToString(akeyPair.getPublic().getEncoded())
+ + "\n-----END PUBLIC KEY-----";
+ this.publicKey = apublicKey;
+
+ } else {
+ try {
+
+ PrivateKey privateKey = CSRGenerator.loadPrivateKeyFromPEM(this.privateKey);
+ PublicKey pKey = CSRGenerator.derivePublicKey(privateKey);
+ String pemString = CSRGenerator.convertToPem(pKey);
+
+ this.publicKey = pemString;
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+
+ logger.info("INVOKER: {} PrivateKEY {}", this.name, this.privateKey);
+
+ logger.info("INVOKER: {} PublicKEY {}", this.name, this.publicKey);
+ }
+
+ public String getPublicKey() {
+
+
+ return this.publicKey;
+ }
+
+ /**
+ * @param certificate the certificate to set
+ */
+ public void setCertificate(String certificate) {
+ this.certificate = certificate;
+ }
+
+
+ private static KeyPair generateRSAKeyPair() {
+ KeyPairGenerator keyGen;
+ try {
+ keyGen = KeyPairGenerator.getInstance("RSA");
+ keyGen.initialize(2048); // key size 2048 bits
+ KeyPair pair = keyGen.generateKeyPair();
+ return pair;
+ } catch (NoSuchAlgorithmException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+
+
+ public String getCSR() {
+ return CSRGenerator.getCSR(getPrivateKey(), getPublicKey(), "CN=InternalOSL");
+ }
+
+
+ public ObjectNode createPayload() {
+
+ apiInvokerPublicKeyCSR = getCSR();
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ ObjectNode payload = mapper.createObjectNode();
+ payload.put("notificationDestination", "http://host.docker.internal:8086/netapp_callback");
+ payload.put("supportedFeatures", "fffffff");
+ payload.put("apiInvokerInformation", "dummy");
+
+ ObjectNode websockNotifConfig = payload.putObject("websockNotifConfig");
+ websockNotifConfig.put("requestWebsocketUri", true);
+ websockNotifConfig.put("websocketUri", "websocketUri");
+
+ ObjectNode onboardingInformation = payload.putObject("onboardingInformation");
+ onboardingInformation.put("apiInvokerPublicKey", apiInvokerPublicKeyCSR); // dynamic value here
+
+ payload.put("requestTestNotification", true);
+
+ return payload;
+ }
+
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @return the certificate
+ */
+ public String getCertificate() {
+ return certificate;
+ }
+
+
+ /**
+ * @return the invokerid
+ */
+ public String getInvokerid() {
+ return invokerid;
+ }
+
+ /**
+ * @return the serviceApis
+ */
+ public Map getServiceApis() {
+ return serviceApis;
+ }
+
+ /**
+ * @return the reqApiNames
+ */
+ public List getReqApiNames() {
+ return reqApiNames;
+ }
+
+ /**
+ * @return the bearerAccessToken
+ */
+ public String getBearerAccessToken() {
+ return bearerAccessToken;
+ }
+
+ /**
+ * @param bearerAccessToken the bearerAccessToken to set
+ */
+ public void setBearerAccessToken(String bearerAccessToken) {
+ this.bearerAccessToken = bearerAccessToken;
+ }
+
+ /**
+ * @return the bearerExpiresIn
+ */
+ public int getBearerExpiresIn() {
+ return bearerExpiresIn;
+ }
+
+ /**
+ * @param bearerExpiresIn the bearerExpiresIn to set
+ */
+ public void setBearerExpiresIn(int bearerExpiresIn) {
+ this.bearerExpiresIn = bearerExpiresIn;
+ }
+
+ /**
+ * @param apiInvokerPublicKeyCSR the apiInvokerPublicKeyCSR to set
+ */
+ public void setApiInvokerPublicKeyCSR(String apiInvokerPublicKeyCSR) {
+ this.apiInvokerPublicKeyCSR = apiInvokerPublicKeyCSR;
+ }
+
+
+ private String genPulicKey(String privateKeyPem) throws Exception {
+
+
+ byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPem);
+
+ // Generate PrivateKey object
+ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+ PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
+
+ // Derive public key from private key
+ RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(privateKey, RSAPublicKeySpec.class);
+ PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
+
+ // Encode public key in PEM format
+ byte[] publicKeyEncoded = publicKey.getEncoded();
+ String publicKeyPem = "-----BEGIN PUBLIC KEY-----\n"
+ + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(publicKeyEncoded)
+ + "\n-----END PUBLIC KEY-----";
+
+ // Print it
+ // System.out.println(publicKeyPem);
+ return publicKeyPem;
+ }
+
+
+
+ /**
+ * @return the description
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * @param description the description to set
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * @return the capifInvokerState
+ */
+ public CapifInvokerState getCapifInvokerState() {
+ return capifInvokerState;
+ }
+
+ /**
+ * @param capifInvokerState the capifInvokerState to set
+ */
+ public void setCapifInvokerState(CapifInvokerState capifInvokerState) {
+ this.capifInvokerState = capifInvokerState;
+ }
+
+
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerResource.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerResource.java
new file mode 100644
index 0000000000000000000000000000000000000000..4c5a531cf57ec85a0e14d2b41e70f73462d326f3
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerResource.java
@@ -0,0 +1,179 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.RSAPublicKeySpec;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.etsi.osl.domain.model.DomainModelDefinition;
+import org.etsi.osl.domain.model.ITMFRCM634_ModelTransformer;
+import org.etsi.osl.domain.model.ITMFRI639_ModelTransformer;
+import org.etsi.osl.tmf.common.model.Any;
+import org.etsi.osl.tmf.common.model.ELifecycle;
+import org.etsi.osl.tmf.common.model.EValueType;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecification;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCharacteristic;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCharacteristicValue;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate;
+import org.etsi.osl.tmf.ri639.model.Characteristic;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.etsi.osl.tmf.ri639.model.ResourceStatusType;
+import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import lombok.Builder;
+import lombok.Data;
+import lombok.Getter;
+
+/**
+ * This wraps a CAPIF Invoker as a Resource.
+ * We have a new Resource reflecting an existing CAPIFInvoker.
+ * In current design a CAPIFInvoker might be reused by many resources.
+ * In future approaches and for use cases supporting different authentication means, we might need a one-to-one mapping
+ *
+ */
+
+
+public class CapifInvokerResource extends DomainModelDefinition
+implements ITMFRCM634_ModelTransformer, ITMFRI639_ModelTransformer {
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+ public static final String OSL_RSPEC_TYPE = "LogicalResourceSpecification";
+
+ private String healthStatus="NA";
+
+ @Autowired
+ static CatalogClient aCatalogClient;
+
+ CapifInvoker refCapifInvoker;
+
+ public CapifInvokerResource( String invokerName, String version, String description,
+ String category, CapifInvoker refCapifInvoker) {
+ super("", invokerName, version, description, category);
+ this.refCapifInvoker = refCapifInvoker;
+ }
+
+
+
+ @Override
+ public ResourceSpecificationCreate toRSpecCreate_InitRepo() {
+
+ ResourceSpecificationCreate rsc = new ResourceSpecificationCreate();
+
+ rsc.setName( this.name );
+ rsc.setVersion( this.version );
+ rsc.setDescription( this.description );
+ rsc.setType( OSL_RSPEC_TYPE );
+ rsc.setCategory( this.category);
+
+ rsc.setLifecycleStatus( ELifecycle.ACTIVE.getValue() );
+
+
+
+ ResourceSpecificationCharacteristic ci = addResourceSpecificationCharacteristicItemShort("bearerAccessToken", refCapifInvoker.getBearerAccessToken() , EValueType.TEXT.getValue(), description , "", false);
+ rsc.addResourceSpecificationCharacteristicItem(ci);
+
+
+ int i=0;
+ for (String reqApiName : refCapifInvoker.getReqApiNames()) {
+ ci = addResourceSpecificationCharacteristicItemShort("reqApiNames_" +i , reqApiName, EValueType.TEXT.getValue(), description , "", false);
+ rsc.addResourceSpecificationCharacteristicItem(ci);
+ i++;
+
+ }
+
+ ci = addResourceSpecificationCharacteristicItemShort("status.discoveredServiceAPIs", refCapifInvoker.getDiscoveredServiceAPIs() , EValueType.TEXT.getValue(), description , "", false);
+ rsc.addResourceSpecificationCharacteristicItem(ci);
+
+
+
+ ci = addResourceSpecificationCharacteristicItemShort("status.state", refCapifInvoker.getCapifInvokerState().name() , EValueType.TEXT.getValue(), description , "", false);
+ rsc.addResourceSpecificationCharacteristicItem(ci);
+ ci = addResourceSpecificationCharacteristicItemShort("status.infoMessage", healthStatus, EValueType.TEXT.getValue(), description , "", false);
+ rsc.addResourceSpecificationCharacteristicItem(ci);
+
+
+ return rsc;
+ }
+
+
+ /**
+ * @param name
+ * @param defaultValue
+ * @param valueType
+ * @param description
+ * @param isConfigurable
+ * @return
+ */
+ public ResourceSpecificationCharacteristic addResourceSpecificationCharacteristicItemShort(
+ String name,
+ String defaultValue,
+ String valueType,
+ String description,
+ String regex,
+ Boolean isConfigurable) {
+
+
+ ResourceSpecificationCharacteristic ci = new ResourceSpecificationCharacteristic();
+ ci
+ .name( name )
+ .description(description)
+ .valueType(valueType);
+ if (defaultValue!=null) {
+ ResourceSpecificationCharacteristicValue val = new ResourceSpecificationCharacteristicValue();
+ val.setValue( new Any( defaultValue, null) );
+ val.isDefault(true);
+ ci.getResourceSpecCharacteristicValue().add( val );
+ }
+ ci.configurable( isConfigurable );
+ ci.regex(regex);
+ return ci;
+ }
+
+
+
+ @Override
+ public DomainModelDefinition fromRSpec(ResourceSpecification rSpec) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+
+
+
+ /**
+ * @return the refCapifInvoker
+ */
+ public CapifInvoker getRefCapifInvoker() {
+ return refCapifInvoker;
+ }
+
+
+ /**
+ * @param refCapifInvoker the refCapifInvoker to set
+ */
+ public void setRefCapifInvoker(CapifInvoker refCapifInvoker) {
+ this.refCapifInvoker = refCapifInvoker;
+ }
+
+
+
+
+
+
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerState.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerState.java
new file mode 100644
index 0000000000000000000000000000000000000000..55d3ccda1a99d8fc59019604d37556cfd117f0de
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifInvokerState.java
@@ -0,0 +1,10 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+public enum CapifInvokerState {
+ UNKNOWN,
+ CONFIGURED,
+ ONBOARDED,
+ ERROR,
+ MISSING
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifService.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifService.java
new file mode 100644
index 0000000000000000000000000000000000000000..49224773e471728e5d43e36e398067a104ea6ea4
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CapifService.java
@@ -0,0 +1,556 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.Base64;
+import java.util.Map.Entry;
+import javax.net.ssl.TrustManagerFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.etsi.osl.controllers.capif.invoker.ApiResponse.AefProfile;
+import org.etsi.osl.controllers.capif.invoker.ApiResponse.ServiceAPIDescription;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.client.reactive.ClientHttpConnector;
+import org.springframework.http.client.reactive.ReactorClientHttpConnector;
+import org.springframework.stereotype.Service;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.reactive.function.client.ExchangeStrategies;
+import org.springframework.web.reactive.function.client.WebClient;
+import io.netty.channel.ChannelOption;
+import io.netty.handler.ssl.SslContext;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+import io.netty.handler.timeout.ReadTimeoutHandler;
+import io.netty.handler.timeout.WriteTimeoutHandler;
+import lombok.Data;
+import reactor.netty.http.client.HttpClient;
+import reactor.netty.tcp.TcpClient;
+
+@Data
+@Service
+public class CapifService {
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+ @Value("${capif.REGISTER_HOSTNAME}")
+ String REGISTER_HOSTNAME;
+
+ @Value("${capif.REGISTER_PORT}")
+ String REGISTER_PORT;
+
+ @Value("${capif.USER_NAME}")
+ String USER_NAME;
+
+ @Value("${capif.USER_PASSWORD}")
+ String USER_PASSWORD;
+
+ @Value("${capif.CAPIF_HOSTNAME}")
+ String CAPIF_HOSTNAME;
+
+ @Value("${capif.CAPIF_PORT}")
+ String CAPIF_PORT;
+
+ @Value("${capif.ONBOARDING_URL}")
+ String ONBOARDING_URL;
+
+ @Value("${capif.ONBOARDING_URL_INVOKER}")
+ String ONBOARDING_URL_INVOKER;
+
+ @Value("${capif.DISCOVER_URL}")
+ String DISCOVER_URL;
+
+ @Value("${capif.ALLOW_INSECURE}")
+ boolean ALLOW_INSECURE;
+
+ @Value("${capif.TRUSTSTORE_PATH}")
+ String TRUSTSTORE_PATH;
+
+ @Value("${capif.TRUSTSTORE_PASSWORD}")
+ String TRUSTSTORE_PASSWORD;
+
+ /**
+ * this is given after getAuth
+ */
+ String accessToken = null;
+
+ String ca_root = null;
+
+ public void authorizeToCapifService() throws Exception {
+
+ logger.info("=== authorizeToCapifService ===");
+
+ WebClient client = WebClient.builder().exchangeStrategies(getExchangeStrategies())
+ .baseUrl("https://" + REGISTER_HOSTNAME + ":" + REGISTER_PORT)
+ .clientConnector(clientHttpConnector())
+ .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .defaultHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader( USER_NAME, USER_PASSWORD))
+ .build();
+
+ String jsonResponse = client.get()
+ .uri("/getauth")
+ .retrieve()
+ .onStatus(
+ status -> status.is4xxClientError() || status.is5xxServerError(),
+ clientResponse -> clientResponse.bodyToMono(String.class)
+ .map(errorBody -> new RuntimeException("API error: " + errorBody) )
+ )
+ .bodyToMono(String.class).block();
+
+ logger.debug(jsonResponse);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode rootNode = objectMapper.readTree(jsonResponse);
+
+ accessToken = rootNode.path("access_token").asText();
+ ca_root = rootNode.path("ca_root").asText();
+
+
+
+ }
+
+ public SslContext createSslContext(boolean useTrustStore, String trustStorePath,
+ String trustStorePassword, boolean allowInsecure) throws Exception {
+
+ if (useTrustStore && trustStorePath != null && !trustStorePath.isEmpty()) {
+ KeyStore trustStore = KeyStore.getInstance("JKS");
+ try (FileInputStream fis = new FileInputStream(new File(trustStorePath))) {
+ trustStore.load(fis, trustStorePassword.toCharArray());
+ }
+
+ TrustManagerFactory trustManagerFactory =
+ TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ trustManagerFactory.init(trustStore);
+
+ return SslContextBuilder.forClient().trustManager(trustManagerFactory).build();
+
+ } else if (allowInsecure) {
+ // Insecure approach, for development only
+ return SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
+ .build();
+ }
+
+ // Default SSL context (standard validation)
+ return SslContextBuilder.forClient().build();
+ }
+
+
+ private ClientHttpConnector clientHttpConnector() throws Exception {
+
+ // default SSL
+ // createSslContext(false, null, null, false);
+
+ SslContext sslContext;
+ if (ALLOW_INSECURE) {
+ sslContext = createSslContext(false, null, null, true);
+ } else {
+ sslContext = createSslContext(true, TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD, false);
+ }
+
+
+ TcpClient tcpClient = TcpClient.create()
+ // .wiretap(true) //logging on reactor.netty.tcp.TcpClient level to DEBUG
+ .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
+ .doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(30))
+ .addHandlerLast(new WriteTimeoutHandler(30)));
+
+ return new ReactorClientHttpConnector(HttpClient.from(tcpClient).wiretap(true)// To enable it,
+ // you must set
+ // the logger
+ // reactor.netty.http.client.HttpClient
+ // level to DEBUG
+ .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)));
+ }
+
+ private ExchangeStrategies getExchangeStrategies() {
+
+ ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
+ .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)).build(); // spring.codec.max-in-memory-size=-1
+ // ?? if use
+ // autoconfiguration
+ return exchangeStrategies;
+ }
+
+ private static String basicAuthHeader(String username, String password) {
+ String credentials = username + ":" + password;
+ return "Basic "
+ + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
+ }
+
+ public CapifInvoker onboardInvoker(final CapifInvoker cif) throws Exception {
+
+
+ logger.info("================== onboardInvoker {} =========================", cif.getName());
+
+ CapifInvoker resultInv = cif;
+
+ WebClient webClient;
+
+ webClient = WebClient.builder()
+ .exchangeStrategies(getExchangeStrategies())
+ .baseUrl("https://" + CAPIF_HOSTNAME + ":" + CAPIF_PORT)
+ .clientConnector(clientHttpConnector())
+ .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken).build();
+
+ ObjectNode objnode = resultInv.createPayload();;
+
+
+ logger.info("================== onboardInvoker objnode {} =========================", objnode );
+
+ String response = webClient.post()
+ .uri(ONBOARDING_URL_INVOKER)
+ .bodyValue( objnode )
+ .retrieve()
+ .onStatus(
+ status -> status.is4xxClientError() || status.is5xxServerError(),
+ clientResponse -> clientResponse.bodyToMono(String.class)
+ .map(errorBody -> new RuntimeException("API error: " + errorBody) )
+ )
+ .bodyToMono(String.class).block();
+
+ logger.info("POST Response from server: " + response);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode rootNode = objectMapper.readTree(response);
+ resultInv.invokerid = rootNode.path("apiInvokerId").asText();
+ resultInv.setApiInvokerPublicKeyCSR(
+ rootNode.path("onboardingInformation").path("apiInvokerPublicKey").asText());
+ resultInv.setCertificate(
+ rootNode.path("onboardingInformation").path("apiInvokerCertificate").asText());
+
+ return resultInv;
+ }
+
+ public CapifInvoker putSecurityContext(CapifInvoker cif) throws Exception {
+
+ logger.info("================== putSecurityContext {} =========================",
+ cif.getName());
+
+ WebClient webClient = WebClient.builder()
+ .exchangeStrategies(getExchangeStrategies())
+ .baseUrl("https://" + CAPIF_HOSTNAME + ":" + CAPIF_PORT)
+ .clientConnector(clientHttpConnector(ca_root, cif))
+ .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();
+
+
+ for (Entry entry : cif.getServiceApis().entrySet()) {
+
+
+ ServiceAPIDescription serviceApi = entry.getValue().getServiceAPIDescriptions().get(0) ;
+ AefProfile defaultProfile = serviceApi.getAefProfiles().get(0);
+
+
+
+ String jsonPayload = """
+ {
+ "securityInfo": [
+ {
+ "prefSecurityMethods": [
+ "OAUTH"
+ ],
+ "authenticationInfo": "string",
+ "authorizationInfo": "string",
+ "aefId": "%s",
+ "apiId": "%s"
+ }
+ ],
+ "notificationDestination": "https://mynotificationdest.com",
+ "requestTestNotification": true,
+ "websockNotifConfig": {
+ "websocketUri": "string",
+ "requestWebsocketUri": true
+ },
+ "supportedFeatures": "fff"
+ }
+ """.formatted(defaultProfile.getAefId() , serviceApi.getApiId() ) ;
+
+
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode payloadNode = (ObjectNode) mapper.readTree(jsonPayload);
+
+
+ String response = webClient.put()
+ .uri("capif-security/v1/trustedInvokers/" + cif.invokerid)
+ .bodyValue(payloadNode)
+ .retrieve()
+ .onStatus(
+ status -> status.is4xxClientError() || status.is5xxServerError(),
+ clientResponse -> clientResponse.bodyToMono(String.class)
+ .map(errorBody -> new RuntimeException("API error: " + errorBody) )
+ ).bodyToMono(String.class).block();
+
+ logger.info("Response from server: " + response);
+ }
+
+ return cif;
+
+ }
+
+ public CapifInvoker getServiceBearer(CapifInvoker cif) throws Exception {
+
+
+ for (Entry entry : cif.getServiceApis().entrySet()) {
+
+
+ ServiceAPIDescription serviceApi = entry.getValue().getServiceAPIDescriptions().get(0) ;
+ AefProfile defaultProfile = serviceApi.getAefProfiles().get(0);
+
+ logger.info("========= GetOAuTh Bearer apiid: {}, aefid: {} ==========", defaultProfile.getAefId(), serviceApi.getApiId() );
+
+ WebClient webClient = WebClient.builder()
+ .exchangeStrategies(getExchangeStrategies())
+ .baseUrl("https://" + CAPIF_HOSTNAME + ":" + CAPIF_PORT)
+ .clientConnector(clientHttpConnector(ca_root, cif))
+ .defaultHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE).build();
+
+ MultiValueMap formData = new LinkedMultiValueMap<>();
+ formData.add("client_id", cif.invokerid);
+ formData.add("grant_type", "client_credentials");
+ formData.add("client_secret", "string");
+ formData.add("scope", "3gpp#" + defaultProfile.getAefId() + ":" + serviceApi.getApiName() );
+
+ String response = webClient.post().uri("/capif-security/v1/securities/" + cif.invokerid + "/token")
+ .bodyValue(formData)
+ .retrieve()
+ .onStatus(
+ status -> status.is4xxClientError() || status.is5xxServerError(),
+ clientResponse -> clientResponse.bodyToMono(String.class)
+ .map(errorBody -> new RuntimeException("API error: " + errorBody) )
+ ).bodyToMono(String.class).block();
+
+ logger.info("Response: " + response);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode rootNode = objectMapper.readTree(response);
+
+ String accessToken = rootNode.path("access_token").asText();
+ int expire = rootNode.path("_in").asInt();
+
+
+ cif.setBearerAccessToken( accessToken );
+ cif.setBearerExpiresIn(expire);
+
+ logger.info("OAUTH token: " + accessToken);
+ return cif;
+
+ }
+ return cif;
+
+ }
+
+
+ public void fetchURL(CapifInvoker cif) {
+
+ //we must refresh the token.
+
+ logger.info("==================Good luck invoker {}=======================", cif.getName());
+
+
+ ServiceAPIDescription serviceApi = cif.getServiceApis()
+ .entrySet().stream().findFirst().get()
+ .getValue().getServiceAPIDescriptions().get(0) ;
+ AefProfile defaultProfile = serviceApi.getAefProfiles().get(0);
+
+ String IPV4ADDR = defaultProfile.getInterfaceDescriptions().get(0).getIpv4Addr() ;
+ String SERVICE_PORT = defaultProfile.getInterfaceDescriptions().get(0).getPort() + "" ;
+ String SERVICE_URI = defaultProfile.getVersions().get(0).getResources().get(0).getUri();
+
+ logger.info("IPV4ADDR {}", IPV4ADDR);
+ logger.info("SERVICE_PORT {}", SERVICE_PORT);
+ logger.info("SERVICE_URI {}", SERVICE_URI);
+ new Thread(() -> {
+
+ while (true) {
+
+ // pm.environment.set('IPV4ADDR', api.aefProfiles[0].interfaceDescriptions[0].ipv4Addr);
+ // pm.environment.set('PORT', api.aefProfiles[0].interfaceDescriptions[0].port);
+ // pm.environment.set('URI', api.aefProfiles[0].versions[0].resources[0].uri);
+
+ WebClient webClientx;
+ try {
+ webClientx = WebClient.builder().exchangeStrategies(getExchangeStrategies())
+ .baseUrl("http://" +IPV4ADDR+ ":" + SERVICE_PORT)
+ .clientConnector(clientHttpConnector(ca_root, cif))
+ .defaultHeader("Authorization", "Bearer " + accessToken)
+ .defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE).build();
+ MultiValueMap formData2 = new LinkedMultiValueMap<>();
+ formData2.add("name", "ExamplePPayload from " + cif.getName());
+
+ String responsex = webClientx.post().uri( SERVICE_URI ).bodyValue( formData2 ).retrieve()
+ .bodyToMono(String.class).block();
+
+ logger.info("Response: " + responsex);
+
+
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ try {
+ Thread.sleep (1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+ }).start();
+
+
+ }
+
+
+
+
+ public CapifInvoker discoverallServiceAPIs(final CapifInvoker cif) throws Exception {
+
+ logger.info("================== discoverallServiceAPIs {}=========================",
+ cif.getName());
+ // needs ca_root
+ // needs client certificates and private key
+ CapifInvoker resultCif = cif;
+
+ WebClient webClient = WebClient.builder().exchangeStrategies(getExchangeStrategies())
+ .baseUrl("https://" + CAPIF_HOSTNAME + ":" + CAPIF_PORT)
+ .clientConnector(clientHttpConnector(ca_root, cif))
+ .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();
+
+ String response = webClient.get().uri(DISCOVER_URL + "?api-invoker-id=" + cif.getInvokerid())
+ .retrieve().bodyToMono(String.class).block();
+
+ System.out.println("Response from server Discover: " + response);
+
+ resultCif.setDiscoveredServiceAPIs(response);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ ApiResponse apiResponse = objectMapper.readValue( response, ApiResponse.class);
+
+ //the response can be a characteristic
+
+ for (ServiceAPIDescription serviceApiDesc : apiResponse.getServiceAPIDescriptions()) {
+
+
+ String apiName = serviceApiDesc.getApiName();
+ logger.info("API Name: " + apiName);
+
+ for (String reqApiName : resultCif.reqApiNames) {
+
+ if (apiName.equals(reqApiName)) {
+
+ logger.info("API Name found and added: " + apiName);
+
+ String apiId = serviceApiDesc.getApiId();
+ logger.info(" apiId: " + apiId);
+ String aefId = serviceApiDesc.getAefProfiles().get(0).getAefId();
+ logger.info(" AEF Profile ID: " + aefId);
+
+ resultCif.getServiceApis().put(apiId, apiResponse);
+
+ }
+
+ }
+
+
+ }
+
+
+
+
+
+
+
+
+
+ return resultCif;
+
+ }
+
+ public static ClientHttpConnector clientHttpConnector(String ca_root, CapifInvoker cif)
+ throws Exception {
+
+ // default SSL
+ // createSslContext(false, null, null, false);
+
+
+
+ SslContext sslContext = createSslContextFile(true, ca_root, true, cif);
+
+ TcpClient tcpClient = TcpClient.create()
+ // .wiretap(true) //logging on reactor.netty.tcp.TcpClient level to DEBUG
+ .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
+ .doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(30))
+ .addHandlerLast(new WriteTimeoutHandler(30)));
+
+ return new ReactorClientHttpConnector(HttpClient.from(tcpClient).wiretap(true)// To enable it,
+ // you must set
+ // the logger
+ // reactor.netty.http.client.HttpClient
+ // level to DEBUG
+ .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)));
+ }
+
+ public static SslContext createSslContextFile(boolean useTrustStore, String caCertPem,
+ boolean allowInsecure, CapifInvoker cif) throws Exception {
+
+ // CSR
+ // String ourCSRKey= CSRGenerator.getCSR( privateKeyPem, publicKeyPem, "CN=" + invokerId );
+
+ // crt file
+ // String clientCertPem= SelfSignedCertFromCSR.getCertPem(privateKeyPem, ourCSRKey) ;
+
+
+ // Load CA Certificate
+ CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
+ Certificate caCert = certFactory
+ .generateCertificate(new ByteArrayInputStream(caCertPem.getBytes(StandardCharsets.UTF_8)));
+
+ // Load Client Certificate
+ Certificate clientCert = certFactory.generateCertificate(
+ new ByteArrayInputStream(cif.getCertificate().getBytes(StandardCharsets.UTF_8)));
+
+ // Load Client Private Key
+ String privateKeyContent =
+ cif.getPrivateKey().replaceAll("-----\\w+ PRIVATE KEY-----", "").replaceAll("\\s+", "");
+ byte[] decodedKey = Base64.getDecoder().decode(privateKeyContent);
+ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
+ KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" depending on your key type
+ PrivateKey privateKey = kf.generatePrivate(keySpec);
+
+
+ // Create KeyStore with client cert and private key
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(null);
+ keyStore.setKeyEntry("client-key", privateKey, new char[0], new Certificate[] {clientCert});
+
+ // TrustStore with CA Certificate
+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ trustStore.load(null);
+ trustStore.setCertificateEntry("ca-cert", caCert);
+
+ // TrustManager setup
+ TrustManagerFactory trustManagerFactory =
+ TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ trustManagerFactory.init(trustStore);
+
+ // Build SSL context
+ return SslContextBuilder.forClient()
+ .keyManager(privateKey, (java.security.cert.X509Certificate) clientCert)
+ .trustManager(trustManagerFactory).build();
+ }
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/CatalogClient.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/CatalogClient.java
new file mode 100644
index 0000000000000000000000000000000000000000..dc8ecd379f6f4b1317b6ce07dce1c3d09cf679a3
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/CatalogClient.java
@@ -0,0 +1,282 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.camel.LoggingLevel;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.etsi.osl.tmf.rcm634.model.LogicalResourceSpecification;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecification;
+import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate;
+import org.etsi.osl.tmf.ri639.model.LogicalResource;
+import org.etsi.osl.tmf.ri639.model.Resource;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+/**
+ * Class to exchange information with TMF API services
+ *
+ */
+@Service
+public class CatalogClient extends RouteBuilder{
+
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.example.gc");
+
+ @Autowired
+ private ProducerTemplate template;
+
+
+ @Value("${CATALOG_GET_RESOURCESPEC_BY_ID}")
+ private String CATALOG_GET_RESOURCESPEC_BY_ID = "";
+
+ @Value("${CATALOG_GET_RESOURCESPEC_BY_NAME_CATEGORY}")
+ private String CATALOG_GET_RESOURCESPEC_BY_NAME_CATEGORY = "";
+
+
+ @Value("${CATALOG_UPDADD_RESOURCESPEC}")
+ private String CATALOG_UPDADD_RESOURCESPEC = "";
+
+
+ @Value("${CATALOG_UPDADD_RESOURCE}")
+ private String CATALOG_UPDADD_RESOURCE = "";
+
+
+ @Value("${CATALOG_UPD_RESOURCE}")
+ private String CATALOG_UPD_RESOURCE = "";
+
+ @Value("${CATALOG_GET_RESOURCE_BY_ID}")
+ private String CATALOG_GET_RESOURCE_BY_ID = "";
+
+
+ //private ConcurrentHashMap resourcesToBeUpdated = new ConcurrentHashMap<>();
+
+
+ @Override
+ public void configure() throws Exception {
+
+
+
+ }
+
+
+
+ /**
+ * get service spec by id from model via bus
+ * @param id
+ * @return
+ * @throws IOException
+ */
+ public ResourceSpecification retrieveResourceSpecByNameCategoryVersion(String aName, String aCategory, String aVersion) {
+ logger.debug("will retrieve Resource Specification aName=" + aName );
+
+ try {
+ Map map = new HashMap<>();
+ map.put( "aname", aName);
+ map.put( "acategory", aCategory);
+ map.put( "aversion", aVersion);
+ Object response =
+ template.requestBodyAndHeaders( CATALOG_GET_RESOURCESPEC_BY_NAME_CATEGORY, null, map);
+
+ if ( !(response instanceof String)) {
+ logger.error("Resource Specification object is wrong.");
+ return null;
+ }
+ LogicalResourceSpecification sor = toJsonObj( (String)response, LogicalResourceSpecification.class);
+ //logger.debug("retrieveSpec response is: " + response);
+ return sor;
+
+ }catch (Exception e) {
+ logger.error("Cannot retrieve Resource Specification details from catalog. " + e.toString());
+ }
+ return null;
+ }
+
+ /**
+ * get service spec by id from model via bus
+ * @param id
+ * @return
+ * @throws IOException
+ */
+ public ResourceSpecification retrieveResourceSpec(String specid) {
+ logger.debug("will retrieve Resource Specification id=" + specid );
+
+ try {
+ Object response = template.
+ requestBody( CATALOG_GET_RESOURCESPEC_BY_ID, specid);
+
+ if ( !(response instanceof String)) {
+ logger.error("Resource Specification object is wrong.");
+ return null;
+ }
+ LogicalResourceSpecification sor = toJsonObj( (String)response, LogicalResourceSpecification.class);
+ //logger.debug("retrieveSpec response is: " + response);
+ return sor;
+
+ }catch (Exception e) {
+ logger.error("Cannot retrieve Resource Specification details from catalog. " + e.toString());
+ }
+ return null;
+ }
+
+
+ public LogicalResourceSpecification createOrUpdateResourceSpecByNameCategoryVersion( ResourceSpecificationCreate s) {
+ logger.debug("will createOrUpdateResourceSpecByNameCategoryVersion " );
+ logger.debug("s= " + s );
+ try {
+ Map map = new HashMap<>();
+ map.put("aname", s.getName());
+ map.put("aversion", s.getVersion());
+ map.put("acategory", s.getCategory());
+
+ Object response = template.requestBodyAndHeaders( CATALOG_UPDADD_RESOURCESPEC, toJsonString(s), map);
+
+ if ( !(response instanceof String)) {
+ logger.error("ResourceSpecification object is wrong.");
+ }
+
+ LogicalResourceSpecification rs = toJsonObj( (String)response, LogicalResourceSpecification.class);
+ return rs;
+
+
+ }catch (Exception e) {
+ logger.error("Cannot create ResourceSpecification");
+ e.printStackTrace();
+ }
+ return null;
+
+ }
+
+ public Resource createOrUpdateResourceByNameCategoryVersion( ResourceCreate s) {
+ logger.debug("will createOrUpdateResourceByNameVersion a Resource " );
+ try {
+ Map map = new HashMap<>();
+ map.put("aname", s.getName());
+ map.put("aversion", s.getResourceVersion());
+ map.put("acategory", s.getCategory());
+
+ Object response = template.requestBodyAndHeaders( CATALOG_UPDADD_RESOURCE, toJsonString(s), map);
+
+ if ( !(response instanceof String)) {
+ logger.error("Resource object is wrong.");
+ }
+
+ logger.debug( response.toString() );
+ try {
+ LogicalResource rs = toJsonObj( (String)response, LogicalResource.class);
+ return rs;
+ }catch (Exception e) {
+ logger.error("Cannot create LogicalResource");
+ e.printStackTrace();
+ }
+
+ try {
+ Resource rs = toJsonObj( (String)response, Resource.class);
+ return rs;
+ }catch (Exception e) {
+ logger.error("Cannot create as Resource");
+ e.printStackTrace();
+ }
+
+
+ }catch (Exception e) {
+ logger.error("Cannot create Resource");
+ e.printStackTrace();
+ }
+ return null;
+
+ }
+
+
+
+ private T toJsonObj(String content, Class valueType) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ return mapper.readValue( content, valueType);
+ }
+
+ private String toJsonString(Object object) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ return mapper.writeValueAsString(object);
+ }
+
+
+
+ public Resource updateResourceById(String oslResourceId, ResourceUpdate rs) {
+
+
+ logger.debug("will update Resource : " + oslResourceId );
+ try {
+ Map map = new HashMap<>();
+ map.put("resourceId", oslResourceId );
+ map.put("triggerServiceActionQueue", false );
+
+ Object response = template.requestBodyAndHeaders( CATALOG_UPD_RESOURCE, toJsonString(rs), map);
+
+ if ( !(response instanceof String)) {
+ logger.error("Service Instance object is wrong.");
+ }
+
+ LogicalResource resourceInstance = toJsonObj( (String)response, LogicalResource.class);
+ //logger.debug("createService response is: " + response);
+ return resourceInstance;
+
+
+ }catch (Exception e) {
+ e.printStackTrace();
+ logger.error("Cannot update Service: " + oslResourceId + ": " + e.toString());
+ }
+ return null;
+ }
+
+// public void updateResourceById(String oslResourceId, ResourceUpdate rs) {
+//
+// resourcesToBeUpdated.put(oslResourceId, rs);
+//
+//
+// }
+
+// public void processUpdateResources() {
+//
+// resourcesToBeUpdated.forEach( (oslResourceId, rs) -> {
+//
+// logger.info("will update Resource : " + oslResourceId );
+// try {
+// Map map = new HashMap<>();
+// map.put("resourceId", oslResourceId );
+// map.put("triggerServiceActionQueue", false );
+// String json = toJsonString(rs);
+// Object response = template.requestBodyAndHeaders( CATALOG_UPD_RESOURCE, json, map);
+//
+// if ( !(response instanceof String)) {
+// logger.error("Service Instance object is wrong.");
+// }
+//
+// //LogicalResource resourceInstance = toJsonObj( (String)response, LogicalResource.class);
+// //logger.debug("createService response is: " + response);
+// //return resourceInstance;
+//
+// resourcesToBeUpdated.remove(oslResourceId);
+//
+//
+// logger.info("Updated successfully Resource : " + oslResourceId );
+// }catch (Exception e) {
+// e.printStackTrace();
+// logger.error("Cannot update Resource: " + oslResourceId + ": " + e.toString());
+// }
+//
+//
+//
+// });
+// }
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/InvokerManagement.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/InvokerManagement.java
new file mode 100644
index 0000000000000000000000000000000000000000..59465a02188670e7ee72701071fba02799b9b7c6
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/InvokerManagement.java
@@ -0,0 +1,130 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.etsi.osl.controllers.capif.invoker.SpringCapifInvokersConfig.Invoker;
+import org.etsi.osl.controllers.capif.invoker.SpringCapifInvokersConfig.Invoker.ApiName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.stereotype.Service;
+
+
+@Service
+@Configuration
+public class InvokerManagement {
+
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+// Map concurrentHashMap = new ConcurrentHashMap<>();
+
+ private final SpringCapifInvokersConfig config;
+
+ /**
+ * this list contains all the configured invokers (from application.yaml externally)
+ */
+ Map availableInvokers = new ConcurrentHashMap<>();
+
+
+ /**
+ * This map contains all the onboarded Invokers to the CAPIF service
+ * Key is the invoker name
+ */
+ Map onboardedInvokers = new ConcurrentHashMap<>();
+
+
+ @Autowired
+ CapifService aCapifService;
+
+ @Autowired
+ public InvokerManagement(SpringCapifInvokersConfig config) {
+ this.config = config;
+ }
+
+
+ public Map loadInvokers() {
+ logger.info("=== loadInvokers ===");
+ availableInvokers.clear();
+
+ for ( Invoker inv : config.getInvokers() ) {
+
+ CapifInvoker ci = new CapifInvoker();
+ ci.setName( inv.getName());
+ ci.setPrivateKey(inv.getPrivatekey());
+ ci.setPublicKey(inv.getPublickey());
+ ci.setDescription( inv.getDescription() );
+
+ for ( ApiName apiname : inv.getApinames()) {
+ ci.getReqApiNames().add( apiname.getApi() );
+ }
+
+ ci.setCapifInvokerState( CapifInvokerState.CONFIGURED );
+ availableInvokers.put( ci.getName(), ci);
+
+ }
+ return availableInvokers;
+
+ }
+
+
+ public CapifInvoker onboardInvokerByName(String invokerName) throws Exception {
+
+ CapifInvoker cif = availableInvokers.get(invokerName);
+ if ( cif!=null) {
+ logger.info("=== onboardInvokerByName {} ===", cif.getName());
+
+ CapifInvoker resultInv = onboardedInvokers.get(cif.getName());
+ if ( resultInv == null ) { //onboard it
+ resultInv = aCapifService.onboardInvoker( cif );
+ aCapifService.discoverallServiceAPIs( resultInv );
+ cif = aCapifService.putSecurityContext( resultInv );
+ }
+
+ cif = aCapifService.getServiceBearer( resultInv );
+ //aCapifService.fetchURL(cif);
+
+ onboardedInvokers.put(cif.getName() , cif);
+
+ return cif;
+ }
+
+
+ return null;
+ }
+
+ public CapifInvoker refreshBearer(CapifInvoker cif) {
+
+ CapifInvoker resultInv = onboardedInvokers.get(cif.getName());
+ try {
+ logger.info("Previous bearer: " + cif.getBearerAccessToken());
+ cif = aCapifService.getServiceBearer( resultInv );
+ logger.info("new bearer: " + cif.getBearerAccessToken());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return cif;
+
+ }
+
+
+
+
+ public CapifInvoker updateInvoker(CapifInvoker cif) {
+ return cif;
+
+ }
+
+
+ public Boolean deleteInvoker(CapifInvoker cif) {
+
+ return false;
+
+ }
+
+
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/OrchestrationRouteBuillder.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/OrchestrationRouteBuillder.java
new file mode 100644
index 0000000000000000000000000000000000000000..7bd3d8ea4122691512a3db9906ed61cd6dabc228
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/OrchestrationRouteBuillder.java
@@ -0,0 +1,115 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.io.IOException;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.camel.LoggingLevel;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.model.dataformat.JsonLibrary;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.stereotype.Component;
+
+
+@Configuration
+@Component
+public class OrchestrationRouteBuillder extends RouteBuilder {
+
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+ @Value("${spring.application.name}")
+ private String compname;
+
+ @Value("${osl-controller.category}")
+ private String compcategory;
+
+ @Value("${osl-controller.version}")
+ private String compversion;
+
+ @Value("${capif.authRefreshTokensPeriod}")
+ private String authRefreshTokensPeriod;
+
+
+ @Value("${capif.processBearerRefreshTokenPeriod}")
+ private String processBearerRefreshTokenPeriod;
+
+
+ @Autowired
+ CapifService capifService;
+
+ @Autowired
+ ResourceRepoService resourceRepoService;
+
+ @Override
+ public void configure() throws Exception {
+
+
+ String EVENT_CREATE = "jms:queue:CREATE/"+compcategory+"/" + compversion;
+
+ String EVENT_UPDATE = "jms:queue:UPDATE/"+compcategory+"/" + compversion;
+
+ String EVENT_DELETE = "jms:queue:DELETE/"+compcategory+"/" + compversion;
+
+ from(EVENT_CREATE)
+ .log(LoggingLevel.INFO, log, EVENT_CREATE + " message received!")
+ .to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
+ .json(JsonLibrary.Jackson, ResourceCreate.class, true)
+ .bean( resourceRepoService, "createResource( ${headers}, ${body} )")
+ .marshal().json( JsonLibrary.Jackson)
+ .convertBodyTo( String.class );
+
+ from(EVENT_UPDATE)
+ .log(LoggingLevel.INFO, log, EVENT_UPDATE + " message received!")
+ .to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
+ .json(JsonLibrary.Jackson, ResourceUpdate.class, true)
+ .bean( resourceRepoService, "updateResource( ${headers},${body} )")
+ .marshal().json( JsonLibrary.Jackson)
+ .convertBodyTo( String.class );;
+
+ from(EVENT_DELETE)
+ .log(LoggingLevel.INFO, log, EVENT_DELETE + " message received!")
+ .to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
+ .json(JsonLibrary.Jackson, ResourceUpdate.class, true)
+ .bean( resourceRepoService, "deleteResource( ${headers}, ${body} )")
+ .marshal().json( JsonLibrary.Jackson)
+ .convertBodyTo( String.class );;
+
+ logger.info( "Setting up timer routes for refresh tokens" );
+ logger.info( " authRefreshTokensPeriod = " + authRefreshTokensPeriod );
+ logger.info( " processBearerRefreshTokenPeriod = " + processBearerRefreshTokenPeriod );
+
+ from( "timer://processAuthRefreshTokens?delay=60000&period=" + authRefreshTokensPeriod )//every 6 minutes refresh auth token 360000
+ .log(LoggingLevel.INFO, log, "===== processAuthRefreshToken authorizeToCapifService! =====")
+ .to("log:DEBUG?showBody=true&showHeaders=true")
+ .bean( capifService, "authorizeToCapifService()");
+
+
+ from( "timer://processBearerRefreshTokens?delay=60000&period=" + processBearerRefreshTokenPeriod )//every 3 minutes refresh tokens
+ .log(LoggingLevel.INFO, log, "===== processBearerRefreshTokens! =====")
+ .to("log:DEBUG?showBody=true&showHeaders=true")
+ .bean( resourceRepoService, "processBearerRefreshTokens()");
+ }
+
+
+
+ static T toJsonObj(String content, Class valueType) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ return mapper.readValue(content, valueType);
+ }
+
+ static String toJsonString(Object object) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ return mapper.writeValueAsString(object);
+ }
+
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/ResourceRepoService.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/ResourceRepoService.java
new file mode 100644
index 0000000000000000000000000000000000000000..8db191d704cd6ee5676a8d176691eaac25012668
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/ResourceRepoService.java
@@ -0,0 +1,154 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+import org.etsi.osl.tmf.common.model.EValueType;
+import org.etsi.osl.tmf.ri639.model.Resource;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.etsi.osl.tmf.ri639.model.ResourceStatusType;
+import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+@Service
+public class ResourceRepoService {
+
+ private static final Logger logger = LoggerFactory.getLogger("org.etsi.osl.controllers.capif.invoker");
+
+ @Autowired
+ CatalogClient aCatalogClient;
+
+ @Autowired
+ SimpleResourceMapper simpleResourceMapper;
+
+ @Autowired
+ InvokerManagement invokerManagement;
+
+ @Value("${osl-controller.category}")
+ private String compcategory;
+
+ @Value("${osl-controller.version}")
+ private String compversion;
+
+
+ /**
+ * keeps a map of which resources are using the equivalent Invoker
+ */
+ Map resourceToInvokerMap = new ConcurrentHashMap<>();
+
+
+ public Resource createResource( Map headers, ResourceCreate resourceRequested) {
+
+ logger.info("In createResource");
+
+ ResourceUpdate resourceUpdate = simpleResourceMapper.resourceCreateToResourceUpdate(resourceRequested);
+
+ return updateResource(headers, resourceUpdate );
+ }
+
+ public Resource updateResource( Map headers, ResourceUpdate resourceUpdate) {
+ String resourceid = "";
+
+ if ( headers.get("org.etsi.osl.serviceId") !=null ) {
+
+ }
+ if ( headers.get("org.etsi.osl.resourceId") !=null ) { //the resource to update back
+ resourceid = (String) headers.get("org.etsi.osl.resourceId") ;
+ }
+ if ( headers.get("org.etsi.osl.serviceOrderId") !=null ) {
+
+ }
+
+ resourceUpdate.setResourceStatus(ResourceStatusType.UNKNOWN );
+
+ logger.info("In updateResource " + resourceid);
+
+ try {
+
+ CapifInvoker onboardedInvoker = invokerManagement.onboardInvokerByName( resourceUpdate.getResourceSpecification().getName() );
+ if ( onboardedInvoker != null ) {
+
+ CapifInvokerResource aCapifInvokerResource = new CapifInvokerResource( onboardedInvoker.getName(), compversion ,
+ onboardedInvoker.getDescription() , compcategory, onboardedInvoker);
+
+
+ resourceUpdate.addResourceCharacteristicItemShort("bearerAccessToken", onboardedInvoker.getBearerAccessToken() , EValueType.TEXT.getValue());
+ resourceUpdate.addResourceCharacteristicItemShort("status.discoveredServiceAPIs", onboardedInvoker.getDiscoveredServiceAPIs() , EValueType.TEXT.getValue());
+ resourceUpdate.addResourceCharacteristicItemShort("status.state", onboardedInvoker.getCapifInvokerState().name() , EValueType.TEXT.getValue());
+ resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", "" , EValueType.TEXT.getValue());
+ resourceUpdate.setResourceStatus(ResourceStatusType.AVAILABLE);
+
+ resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", "onboarded to CAPIF service" , EValueType.TEXT.getValue());
+ this.resourceToInvokerMap.put(resourceid, aCapifInvokerResource);
+
+ }
+
+ } catch (Exception e) {
+
+ e.printStackTrace();
+
+ resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", e.getLocalizedMessage() , EValueType.TEXT.getValue());
+ resourceUpdate.addResourceCharacteristicItemShort("status.state", CapifInvokerState.ERROR.name() , EValueType.TEXT.getValue());
+ resourceUpdate.setResourceStatus(ResourceStatusType.ALARM);
+ }
+
+ //send it to TMF API
+ Resource res = aCatalogClient.updateResourceById( resourceid, resourceUpdate);
+
+ return res;
+ }
+
+ public Resource deleteResource( Map headers, ResourceUpdate r) {
+ String resourceid = "";
+
+ if ( headers.get("org.etsi.osl.serviceId") !=null ) {
+
+ }
+ if ( headers.get("org.etsi.osl.resourceId") !=null ) { //the resource to update back
+ resourceid = (String) headers.get("org.etsi.osl.resourceId") ;
+ }
+ if ( headers.get("org.etsi.osl.serviceOrderId") !=null ) {
+
+ }
+
+ this.resourceToInvokerMap.remove(resourceid);
+
+ ResourceUpdate resourceUpdate = r;
+ resourceUpdate.setResourceStatus(ResourceStatusType.UNKNOWN);
+
+ resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", "all well deleted", EValueType.TEXT.getValue());
+ resourceUpdate.addResourceCharacteristicItemShort("status.Health", CapifInvokerState.MISSING.name() , EValueType.TEXT.getValue());
+
+ Resource res = aCatalogClient.updateResourceById( resourceid, resourceUpdate);
+
+ return res;
+ }
+
+
+ public void processBearerRefreshTokens() {
+ //update all the bearers and passes it back to the resources
+ for (Entry res : resourceToInvokerMap.entrySet() ) {
+
+ CapifInvoker onboardedInvoker = invokerManagement.refreshBearer(res.getValue() .getRefCapifInvoker() );
+ ResourceUpdate resourceUpdate = new ResourceUpdate();
+
+ resourceUpdate.addResourceCharacteristicItemShort("bearerAccessToken", onboardedInvoker.getBearerAccessToken() , EValueType.TEXT.getValue());
+
+ resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", "Bearer token refreshed " + (new Date()) , EValueType.TEXT.getValue());
+ String resourceid = res.getKey() ;
+ aCatalogClient.updateResourceById( resourceid , resourceUpdate);
+
+
+ }
+
+
+ }
+
+
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/SelfSignedCertFromCSR.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/SelfSignedCertFromCSR.java
new file mode 100644
index 0000000000000000000000000000000000000000..503fde8bec651e8d53ff09d2fdd7f3fd710320c4
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/SelfSignedCertFromCSR.java
@@ -0,0 +1,90 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.openssl.PEMParser;
+import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+
+import java.io.*;
+import java.math.BigInteger;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+public class SelfSignedCertFromCSR {
+
+ static {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+
+ // Load Private Key from PEM
+ public static PrivateKey loadPrivateKey(String privateKeyPem) throws Exception {
+ PEMParser pemParser = new PEMParser(new StringReader(privateKeyPem));
+ Object object = pemParser.readObject();
+ pemParser.close();
+ return new JcaPEMKeyConverter().getPrivateKey((org.bouncycastle.asn1.pkcs.PrivateKeyInfo) object);
+ }
+
+ // Load CSR from PEM
+ public static PKCS10CertificationRequest loadCSR(String csrPem) throws IOException {
+ PEMParser pemParser = new PEMParser(new StringReader(csrPem));
+ Object object = pemParser.readObject();
+ pemParser.close();
+ return (PKCS10CertificationRequest) object;
+ }
+
+ // Generate self-signed certificate from CSR and Private Key
+ public static X509Certificate generateSelfSignedCert(PrivateKey privateKey, PKCS10CertificationRequest csr) throws Exception {
+ X500Name issuer = csr.getSubject();
+ BigInteger serial = new BigInteger(Long.toString(System.currentTimeMillis()));
+
+ Date notBefore = new Date();
+ Date notAfter = new Date(System.currentTimeMillis() + (365L * 24 * 60 * 60 * 1000)); // 1 year validity
+
+ X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
+ issuer, serial, notBefore, notAfter, csr.getSubject(), csr.getSubjectPublicKeyInfo());
+
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
+ .setProvider("BC")
+ .build(privateKey);
+
+ X509CertificateHolder holder = certBuilder.build(signer);
+
+ return new JcaX509CertificateConverter()
+ .setProvider("BC")
+ .getCertificate(holder);
+ }
+
+ public static String getCertPem (String privateKeyPem, String csrPem) {
+
+ PrivateKey privateKey;
+ try {
+ privateKey = loadPrivateKey(privateKeyPem);
+ PKCS10CertificationRequest csr = loadCSR(csrPem);
+
+ X509Certificate selfSignedCert = generateSelfSignedCert(privateKey, csr);
+
+ // Print certificate in PEM format
+ StringWriter certPem = new StringWriter();
+ try (JcaPEMWriter pemWriter = new JcaPEMWriter(certPem)) {
+ pemWriter.writeObject(selfSignedCert);
+ }
+
+ return certPem.toString();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+
+ return csrPem;
+ }
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/SimpleResourceMapper.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/SimpleResourceMapper.java
new file mode 100644
index 0000000000000000000000000000000000000000..9a5ed399c851e47c577b64be8c56a6d758fdfb19
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/SimpleResourceMapper.java
@@ -0,0 +1,14 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import org.etsi.osl.tmf.ri639.model.Resource;
+import org.etsi.osl.tmf.ri639.model.ResourceCreate;
+import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
+import org.mapstruct.Mapper;
+
+@Mapper(componentModel = "spring")
+public interface SimpleResourceMapper {
+
+ ResourceUpdate resourceToResourceUpdate(Resource source);
+ ResourceUpdate resourceCreateToResourceUpdate(ResourceCreate source);
+
+}
diff --git a/src/main/java/org/etsi/osl/controllers/capif/invoker/SpringCapifInvokersConfig.java b/src/main/java/org/etsi/osl/controllers/capif/invoker/SpringCapifInvokersConfig.java
new file mode 100644
index 0000000000000000000000000000000000000000..0c616f420d85b47b290d516a499d7c453c78ad00
--- /dev/null
+++ b/src/main/java/org/etsi/osl/controllers/capif/invoker/SpringCapifInvokersConfig.java
@@ -0,0 +1,90 @@
+package org.etsi.osl.controllers.capif.invoker;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+import java.util.List;
+
+@Configuration
+@ConfigurationProperties(prefix = "capif")
+public class SpringCapifInvokersConfig {
+
+ private List invokers;
+
+ public static class Invoker {
+ private String name;
+ private String privatekey;
+ private String publickey;
+ private String description;
+ private List apinames;
+
+ public static class ApiName {
+ private String api;
+
+ public String getApi() {
+ return api;
+ }
+
+ public void setApi(String api) {
+ this.api = api;
+ }
+ }
+
+
+
+ /**
+ * @return the description
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * @param description the description to set
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ // Getters and setters
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPrivatekey() {
+ return privatekey;
+ }
+
+ public void setPrivatekey(String privatekey) {
+ this.privatekey = privatekey;
+ }
+
+ public String getPublickey() {
+ return publickey;
+ }
+
+ public void setPublickey(String publickey) {
+ this.publickey = publickey;
+ }
+
+
+ public List getApinames() {
+ return apinames;
+ }
+
+ public void setApinames(List apinames) {
+ this.apinames = apinames;
+ }
+ }
+
+ public List getInvokers() {
+ return invokers;
+ }
+
+ public void setInvokers(List invokers) {
+ this.invokers = invokers;
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8c55313a1ff32370666a951a0a9497e5263b153b
--- /dev/null
+++ b/src/main/resources/application.yml
@@ -0,0 +1,113 @@
+osl-controller:
+ category: invoker.capif.osl.etsi.org
+ version: 0.0.1
+
+server:
+ port: 0
+
+spring:
+ config:
+ activate:
+ on-profile: "default"
+ application:
+ name: CAPIFInvokerController
+ description: "OSL CAPIF Invoker"
+ servlet:
+ multipart.max-file-size: 10MB
+ multipart.max-request-size: 10MB
+ activemq:
+ brokerUrl: tcp://portal.openslice.eu:61616?jms.watchTopicAdvisories=false
+ user: artemis
+ password: artemis
+ pool:
+ enabled: true
+ max-connections: 100
+ packages:
+ trust-all: true
+ autoconfigure.exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
+
+logging:
+ level:
+ root: INFO
+ org.etsi.osl.controllers.capif.invoker.*: DEBUG
+ org.springframework: INFO
+ org.apache.camel: INFO
+ com.zaxxer.hikari: INFO
+ pattern:
+ console: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
+ file: "%d %p %c{1.} [%t] %m%n"
+
+
+capif:
+ REGISTER_HOSTNAME: localhost
+ REGISTER_PORT: 8084
+ USER_NAME: custom_user
+ USER_PASSWORD: user_pass
+ CAPIF_HOSTNAME: capifcore
+ CAPIF_PORT: 443
+ ONBOARDING_URL: api-provider-management/v1/registrations
+ ONBOARDING_URL_INVOKER: api-invoker-management/v1/onboardedInvokers
+ DISCOVER_URL: service-apis/v1/allServiceAPIs
+ ALLOW_INSECURE: true
+ TRUSTSTORE_PATH: none
+ TRUSTSTORE_PASSWORD: none
+ authRefreshTokensPeriod: 36000
+ processBearerRefreshTokenPeriod: 180000
+ invokers:
+ - name: exampleInvoker
+ description: an example invoker
+ privatekey: selfsign
+ publickey: selfsign
+ apinames:
+ - api: hello_api_demo
+ - name: exampleInvoker2
+ invokerversion: 0.1.0
+ description: another example invoker
+ privatekey: selfsign
+ publickey: selfsign
+ apinames:
+ - api: hello_api_demo
+ otherexample:
+ - name: exampleInvokerWithKey
+ description: an example invoker
+ privatekey: |
+ -----BEGIN PRIVATE KEY-----
+ MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAphuJvVOLCuSIbYMIppTiZXAM
+ PHJfyZXAIiNTzgRqCgXDiafF1yaIvpkjeNP7gtaa+slePxbLG1fYFef2/nOCSI99ycPYX4DGlP42
+ epEu+z0bhG/ar9G8EbZfyD+neOFHdUQtang2+DpGtw0kX8qVlxPFrc0bwgUgd7VAvSEaX5tf1gnq
+ IHj54B3Xg9kCXmNJ93UuJZDSqV7+KUOaXPUJnE/rwY/KzEc1WABae/mcdWcaE0iuzCFzYoKRL5ei
+ KBAcPIqDbWsAaHNuRlbxDovBcyQsx33yYnXlvMa58HwNvR7Pxi4j8B48p8l5FFqVUSb66Kv6fkLi
+ D1PQe0gBd28TAgMBAAECggEAJQtL3E6Vk/UCQOGeArnVgzsyMoglDho7O3jVBjZlTuaieRktM7PN
+ axoLZHDFgmWEUsTKl97VyTR2zcxYkHwZRgIh5XQ4vpCOuKDJyTwEUt5ov7PVtl18nQdi5EQjSVbL
+ Kux3sav5dciBnDtywX3R/LXSTX7AJAhI6BdcuRglF2bZk1hXNYAlCtVj4Yi+vVRfhK74THCMsN0X
+ amQBgVSpoIYtmRBZH4ImnczZvnIGA9f2uxpe+TUEgEcnO0lxt2BM3nxTQuPDCGwjrUHLv6maRTL3
+ dc9xUK4Bsm/aF16VSjOcpL8i68vU1NwBi5KXZsoYeAEaJsMZ4oY7Za9QLgODgQKBgQDieFEQ+Gbt
+ pKkWJLwyRPK34sOqn5dOJzfLPpmv+Nqm9UytkV7E12cFiyPMTu7I3YduY6rDp98rkqbsqg+GqDB8
+ h0AfsCf7DjzH8+Qlo0SodaFBjbIG5Y87MiEpKheX1FRpxjgQB1iMNy8WzVxUXdGC3H0MrdxOVKQy
+ fHfhIOH48wKBgQDZxNMMki4D25CFI+re4w+BxzKNbEnmfuDvIdpVzs5sXTPXgrDBSLrmFtrzqc3c
+ kPqtNAJWZOZDP7BCmwOv8GDhaQBx1E6KJckaZ/LucL4GlgXgVJfw2g2lOG53bXY7cAk2jblaYqkw
+ vibIX/wOo7PSt7hoK1UdG3QHh+GkcW45YQKBgQDOR2UfngKyxt60qrU43JBwaf5rdX3t088AM37t
+ SDBxDtHO7rBxfvn5lKkAuYzKLO3k4Kd0G34tRCEDREtsDdpMMy13L47bIDbAsifHGJW7E5nUCep0
+ WbhC5QBLbGmdA+v3hHMgNnCzFrivflJxDht9pLPKTrpyJqqAydqvlrH9fQKBgQCA2YWqpX+Whr5/
+ GJ5q3NybBDr0FMOxHxeGRniCVwgqdActl8Vvx9HWPGW20JzeyeWYv/I2HiNkXPW0ozXOTyNznAZI
+ U79Y3DyeZC0ISisViITXlBYGy25ReQ9bmKfhSUwaPEcUpNXI4mneG3TvUIsgvdXdxO3qeAjyP8MR
+ 4o++YQKBgQCQSbY4YOYdg+eLrqpc6kcZXlajz2BSBuBCFYQRCO9fblxalS9SJOCoRRdCzMiAAm1J
+ WmD6ocD8RVCzdYF1NuhFC6gaB+q0ZGpr3E/BbUn6DwZxwWzdxUQmLSJOa6WQWW8PHiY50MOTu3+Y
+ 6owNEzuPci0ihc3Bk0JHCOncH3cZtQ==
+ -----END PRIVATE KEY-----
+ publickey: "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwKYbib1TiwrkiG2DCKaU4mVwDDxyX8mVwCIjU84EagoFw4mnxdcmiL6ZI3jT+4LWmvrJXj8WyxtX2BXn9v5zgkiPfcnD2F+AxpT+NnqRLvs9G4Rv2q/RvBG2X8g/p3jhR3VELWp4Nvg6RrcNJF/KlZcTxa3NG8IFIHe1QL0hGl+bX9YJ6iB4+eAd14PZAl5jSfd1LiWQ0qle/ilDmlz1CZxP68GPysxHNVgAWnv5nHVnGhNIrswhc2KCkS+XoigQHDyKg21rAGhzbkZW8Q6LwXMkLMd98mJ15bzGufB8Db0ez8YuI/AePKfJeRRalVEm+uir+n5C4g9T0HtIAXdvEwIDAQAB-----END PUBLIC KEY-----"
+ apinames:
+ - api: hello_api_demo
+
+
+
+#RESOURCES MESSAGES
+CATALOG_ADD_RESOURCE: "jms:queue:CATALOG.ADD.RESOURCE"
+CATALOG_UPD_RESOURCE: "jms:queue:CATALOG.UPD.RESOURCE"
+CATALOG_UPDADD_RESOURCE: "jms:queue:CATALOG.UPDADD.RESOURCE"
+CATALOG_GET_RESOURCE_BY_ID: "jms:queue:CATALOG.GET.RESOURCE"
+CATALOG_ADD_RESOURCESPEC: "jms:queue:CATALOG.ADD.RESOURCESPEC"
+CATALOG_UPD_RESOURCESPEC: "jms:queue:CATALOG.UPD.RESOURCESPEC"
+CATALOG_UPDADD_RESOURCESPEC: "jms:queue:CATALOG.UPDADD.RESOURCESPEC"
+CATALOG_GET_RESOURCESPEC_BY_ID: "jms:queue:CATALOG.GET.RESOURCESPEC_BY_ID"
+CATALOG_GET_RESOURCESPEC_BY_NAME_CATEGORY: "jms:queue:CATALOG.GET.RESOURCESPEC_BY_NAME_CATEGORY"
diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt
new file mode 100644
index 0000000000000000000000000000000000000000..74229cd400fb31f76673214d76c0256f438e4ccc
--- /dev/null
+++ b/src/main/resources/banner.txt
@@ -0,0 +1,11 @@
+ ___ ____ _ _
+ / _ \ _ __ ___ _ __ / ___|| (_) ___ ___
+ | | | | '_ \ / _ \ '_ \\___ \| | |/ __/ _ \
+ | |_| | |_) | __/ | | |___) | | | (_| __/
+ \___/| .__/ \___|_| |_|____/|_|_|\___\___|
+ |_|
+ __ __________________
+ / / __ __ / __/_ __/ __/ _/
+ / _ \/ // / / _/ / / _\ \_/ /
+ /_.__/\_, / /___/ /_/ /___/___/
+ /___/
\ No newline at end of file