From 04a443b969c2506a05a69b1aa6be1950d87488cb Mon Sep 17 00:00:00 2001 From: Jim Marino Date: Wed, 13 Mar 2024 15:28:10 +0100 Subject: [PATCH] Initial commit --- .gitignore | 54 +++ DEPENDENCIES | 0 LICENSE | 201 ++++++++ NOTICE.md | 49 ++ README.md | 14 +- SECURITY.md | 17 + api/directory-api/build.gradle.kts | 34 ++ .../bdrs/api/directory/DirectoryApi.java | 7 + .../api/directory/DirectoryApiController.java | 47 ++ .../api/directory/DirectoryApiExtension.java | 51 ++ ...rg.eclipse.edc.spi.system.ServiceExtension | 21 + .../directory/DirectoryApiControllerTest.java | 71 +++ .../directory/DirectoryApiExtensionTest.java | 46 ++ api/management-api/build.gradle.kts | 36 ++ .../bdrs/api/management/BpnMapping.java | 15 + .../bdrs/api/management/ManagementApi.java | 21 + .../management/ManagementApiController.java | 69 +++ .../management/ManagementApiExtension.java | 66 +++ ...rg.eclipse.edc.spi.system.ServiceExtension | 21 + .../ManagementApiControllerTest.java | 125 +++++ .../ManagementApiExtensionTest.java | 59 +++ build.gradle.kts | 107 ++++ config/checkstyle/checkstyle.xml | 457 ++++++++++++++++++ config/checkstyle/suppressions.xml | 29 ++ core/core-services/build.gradle.kts | 30 ++ .../tractusx/bdrs/core/BdrsCoreExtension.java | 124 +++++ .../HealthCheckServiceConfiguration.java | 100 ++++ .../core/health/HealthCheckServiceImpl.java | 135 ++++++ .../core/store/InMemoryDidEntryStore.java | 116 +++++ .../bdrs/core/vault/InMemoryVault.java | 46 ++ ...rg.eclipse.edc.spi.system.ServiceExtension | 21 + .../core/store/InMemoryDidEntryStoreTest.java | 96 ++++ gradle.properties | 29 ++ gradle/libs.versions.toml | 33 ++ gradle/wrapper/gradle-wrapper.properties | 28 ++ gradlew | 254 ++++++++++ gradlew.bat | 92 ++++ runtimes/server/build.gradle.kts | 46 ++ runtimes/server/notice.md | 29 ++ runtimes/server/src/main/docker/Dockerfile | 30 ++ settings.gradle.kts | 51 ++ spi/core-spi/build.gradle.kts | 28 ++ .../tractusx/bdrs/spi/store/DidEntry.java | 27 ++ .../bdrs/spi/store/DidEntryStore.java | 51 ++ 44 files changed, 2981 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 DEPENDENCIES create mode 100644 LICENSE create mode 100644 NOTICE.md create mode 100644 SECURITY.md create mode 100644 api/directory-api/build.gradle.kts create mode 100644 api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApi.java create mode 100644 api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiController.java create mode 100644 api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtension.java create mode 100644 api/directory-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension create mode 100644 api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiControllerTest.java create mode 100644 api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtensionTest.java create mode 100644 api/management-api/build.gradle.kts create mode 100644 api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/BpnMapping.java create mode 100644 api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApi.java create mode 100644 api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiController.java create mode 100644 api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtension.java create mode 100644 api/management-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension create mode 100644 api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiControllerTest.java create mode 100644 api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtensionTest.java create mode 100644 build.gradle.kts create mode 100644 config/checkstyle/checkstyle.xml create mode 100644 config/checkstyle/suppressions.xml create mode 100644 core/core-services/build.gradle.kts create mode 100644 core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/BdrsCoreExtension.java create mode 100644 core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceConfiguration.java create mode 100644 core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceImpl.java create mode 100644 core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStore.java create mode 100644 core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/vault/InMemoryVault.java create mode 100644 core/core-services/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension create mode 100644 core/core-services/src/test/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStoreTest.java create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 runtimes/server/build.gradle.kts create mode 100644 runtimes/server/notice.md create mode 100644 runtimes/server/src/main/docker/Dockerfile create mode 100644 settings.gradle.kts create mode 100644 spi/core-spi/build.gradle.kts create mode 100644 spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntry.java create mode 100644 spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntryStore.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b57c87f --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +.idea +.vs +.vscode + +/secrets + +distributions/**/github.properties + +# ignore all certificates + +.terraform* + +.DS_Store +**/secrets + +**/terraform.tfvars +**/.terraform* +launchers/demo-e2e/edc-config.properties +**/out +*.hprof + +.env +runtime_settings.properties +generated_backend.tf diff --git a/DEPENDENCIES b/DEPENDENCIES new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /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/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..bd08079 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,49 @@ +# Notices for Eclipse Tractus-X + +This content is produced and maintained by the Eclipse Tractus-X project. + +* Project home: + +See the AUTHORS file(s) distributed with this work for additional information regarding authorship. + +## Trademarks + +Eclipse Tractus-X is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Apache License, Version 2.0 which is available at +. + +SPDX-License-Identifier: Apache-2.0 + +## Source Code + +The project maintains the following source code repositories +in the GitHub organization : + +* + +## Third-party Content + +This project leverages the following third party content. + +- OpenTelemetry Agent v1.32.0: + +For additional dependencies, see [DEPENDENCIES](./DEPENDENCIES) file. + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. diff --git a/README.md b/README.md index 2315a98..08f91c9 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,12 @@ -# bpn-did-resolution-service -Tractus-X Resolver Service for BPN <> DID resolution +# BPN-DID Resolution Service + +The BPN-DID Resolution Service (BDRS) provides a directory of Business Partner Numbers (BPN) and their associated DIDs. +The directory is used by dataspace participant agents to resolve a DID for a BPN. + +The directory is requested via a RESTFul HTTPS API and is designed to be cached locally for resolution operations. When +requesting the directory, the client must include a JWT with a presentation containing its `MembershipCrediential` for +authentication. + +## Implementation + +The BDRS is a collection of extensions to the [EDC core runtime](https://github.com/eclipse-edc/Connector). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..837c782 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Reporting a Vulnerability + +Please do **not** report security vulnerabilities through public GitHub issues. + +Please report vulnerabilities to this repository via **GitHub security advisories** instead. + +How? Inside affected repository → security tab + +for contributor: +→ Report a vulnerability + +for committer: +→ advisories → New draft security advisory + +In severe cases, you can also report a found vulnerability via mail or eclipse issue here: + +See [Eclipse Foundation Vulnerability Reporting Policy](https://www.eclipse.org/projects/handbook/#vulnerability) diff --git a/api/directory-api/build.gradle.kts b/api/directory-api/build.gradle.kts new file mode 100644 index 0000000..05c9fb5 --- /dev/null +++ b/api/directory-api/build.gradle.kts @@ -0,0 +1,34 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +plugins { + `java-library` +} + +dependencies { + implementation(libs.edc.spi.core) + implementation(libs.edc.spi.web) + implementation(project(":spi:core-spi")) + + testImplementation(libs.restAssured) + testImplementation(testFixtures(libs.edc.core.jersey)) +} + diff --git a/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApi.java b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApi.java new file mode 100644 index 0000000..2155a4f --- /dev/null +++ b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApi.java @@ -0,0 +1,7 @@ +package org.eclipse.tractusx.bdrs.api.directory; + +/** + * Provides the public BPN Directory API. + */ +public interface DirectoryApi { +} diff --git a/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiController.java b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiController.java new file mode 100644 index 0000000..e0f1dbc --- /dev/null +++ b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiController.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.directory; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.Response.ok; + +/** + * Implements the BPN Directory API. The BPN Directory is returned in compressed (GZIP) form. + */ +@Path("/") +@Produces(APPLICATION_JSON) +public class DirectoryApiController implements DirectoryApi { + private final DidEntryStore store; + + public DirectoryApiController(DidEntryStore store) { + this.store = store; + } + + @Path("/bpn-directory") + @GET + public Response getData() { + return ok().entity((StreamingOutput) stream -> stream.write(store.entries())) + .encoding("gzip") + .build(); + } + +} diff --git a/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtension.java b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtension.java new file mode 100644 index 0000000..5cfb4b5 --- /dev/null +++ b/api/directory-api/src/main/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtension.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.directory; + +import org.eclipse.edc.runtime.metamodel.annotation.BaseExtension; +import org.eclipse.edc.runtime.metamodel.annotation.Extension; +import org.eclipse.edc.runtime.metamodel.annotation.Inject; +import org.eclipse.edc.spi.system.ServiceExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.web.spi.WebService; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import static org.eclipse.tractusx.bdrs.api.directory.DirectoryApiExtension.NAME; + +/** + * Loads resources for the BPN Directory API. + */ +@BaseExtension +@Extension(NAME) +public class DirectoryApiExtension implements ServiceExtension { + public static final String NAME = "BPN Directory API"; + + @Inject + private DidEntryStore store; + + @Inject + private WebService webService; + + @Override + public String name() { + return NAME; + } + + @Override + public void initialize(ServiceExtensionContext context) { + webService.registerResource(new DirectoryApiController(store)); + } + +} diff --git a/api/directory-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension b/api/directory-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension new file mode 100644 index 0000000..821696a --- /dev/null +++ b/api/directory-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension @@ -0,0 +1,21 @@ +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# +org.eclipse.tractusx.bdrs.api.directory.DirectoryApiExtension diff --git a/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiControllerTest.java b/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiControllerTest.java new file mode 100644 index 0000000..0a6c795 --- /dev/null +++ b/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiControllerTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.directory; + +import io.restassured.path.json.JsonPath; +import io.restassured.specification.RequestSpecification; +import org.eclipse.edc.web.jersey.testfixtures.RestControllerTestBase; +import org.eclipse.tractusx.bdrs.spi.store.DidEntry; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.zip.GZIPOutputStream; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.JSON; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class DirectoryApiControllerTest extends RestControllerTestBase { + private static final String BPN = "BPN123"; + private static final String DID = "did:web:localhost:member"; + + private DidEntryStore store; + + @Test + void verifyGetEntries() throws IOException { + var entries = Map.of(BPN, new DidEntry(BPN, DID)); + var serialized = objectMapper.writeValueAsString(entries); + var serializedStream = new ByteArrayOutputStream(); + try (var gzip = new GZIPOutputStream(serializedStream)) { + gzip.write(serialized.getBytes()); + } + + when(store.entries()).thenReturn(serializedStream.toByteArray()); + + var expectedJson = new JsonPath(serialized); + baseRequest().get("") + .then() + .statusCode(200) + .contentType(JSON) + .body("", equalTo(expectedJson.getMap(""))); + } + + @Override + protected Object controller() { + store = mock(DidEntryStore.class); + return new DirectoryApiController(store); + } + + private RequestSpecification baseRequest() { + return given().baseUri("http://localhost:" + port).basePath("/bpn-directory").when(); + } + +} + diff --git a/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtensionTest.java b/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtensionTest.java new file mode 100644 index 0000000..d2f14f7 --- /dev/null +++ b/api/directory-api/src/test/java/org/eclipse/tractusx/bdrs/api/directory/DirectoryApiExtensionTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.directory; + +import org.eclipse.edc.junit.extensions.DependencyInjectionExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.web.spi.WebService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +@ExtendWith(DependencyInjectionExtension.class) +class DirectoryApiExtensionTest { + + private WebService webService; + + @Test + void verifyBoot(DirectoryApiExtension extension, ServiceExtensionContext context) { + extension.initialize(context); + + verify(webService).registerResource(isA(DirectoryApiController.class)); + } + + @BeforeEach + void setUp(ServiceExtensionContext context) { + webService = mock(WebService.class); + context.registerService(WebService.class, webService); + } + +} diff --git a/api/management-api/build.gradle.kts b/api/management-api/build.gradle.kts new file mode 100644 index 0000000..ac13ce6 --- /dev/null +++ b/api/management-api/build.gradle.kts @@ -0,0 +1,36 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +plugins { + `java-library` +} + +dependencies { + implementation(libs.edc.spi.core) + implementation(libs.edc.spi.web) + implementation(libs.edc.spi.auth) + implementation(project(":spi:core-spi")) + + testImplementation(libs.edc.junit) + testImplementation(libs.restAssured) + testImplementation(testFixtures(libs.edc.core.jersey)) +} + diff --git a/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/BpnMapping.java b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/BpnMapping.java new file mode 100644 index 0000000..0a4d508 --- /dev/null +++ b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/BpnMapping.java @@ -0,0 +1,15 @@ +package org.eclipse.tractusx.bdrs.api.management; + +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; + +/** + * Maps a BPN to a DID. + */ +public record BpnMapping(@NotNull String bpn, @NotNull String did) { + public BpnMapping { + requireNonNull(bpn, "bpn"); + requireNonNull(did, "did"); + } +} diff --git a/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApi.java b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApi.java new file mode 100644 index 0000000..f295116 --- /dev/null +++ b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApi.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.management; + +/** + * Exposes the BDRS management API. Note that this API should not be exposed over a public network. + */ +public interface ManagementApi { +} diff --git a/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiController.java b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiController.java new file mode 100644 index 0000000..95c104b --- /dev/null +++ b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiController.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.management; + +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; +import org.eclipse.tractusx.bdrs.spi.store.DidEntry; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.Response.ok; + +/** + * Implements the BPN Directory Management API. + */ +@Path("/") +@Produces(APPLICATION_JSON) +public class ManagementApiController implements ManagementApi { + private final DidEntryStore store; + + public ManagementApiController(DidEntryStore store) { + this.store = store; + } + + @Path("/bpn-directory") + @GET + public Response getData() { + return ok().entity((StreamingOutput) stream -> stream.write(store.entries())) + .encoding("gzip") + .build(); + } + + @Path("/bpn-directory") + @POST + public void save(BpnMapping mapping) { + store.save(new DidEntry(mapping.bpn(), mapping.did())); + } + + @Path("/bpn-directory") + @PUT + public void update(BpnMapping mapping) { + store.update(new DidEntry(mapping.bpn(), mapping.did())); + } + + @Path("/bpn-directory/{bpn}") + @DELETE + public void delete(@PathParam("bpn") String bpn) { + store.delete(bpn); + } +} diff --git a/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtension.java b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtension.java new file mode 100644 index 0000000..12e95da --- /dev/null +++ b/api/management-api/src/main/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtension.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.management; + +import org.eclipse.edc.api.auth.spi.AuthenticationRequestFilter; +import org.eclipse.edc.api.auth.spi.AuthenticationService; +import org.eclipse.edc.runtime.metamodel.annotation.BaseExtension; +import org.eclipse.edc.runtime.metamodel.annotation.Extension; +import org.eclipse.edc.runtime.metamodel.annotation.Inject; +import org.eclipse.edc.spi.system.ServiceExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.web.spi.WebServer; +import org.eclipse.edc.web.spi.WebService; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import static org.eclipse.tractusx.bdrs.api.management.ManagementApiExtension.NAME; + +/** + * Loads resources for the BPN Directory Management API. + */ +@BaseExtension +@Extension(NAME) +public class ManagementApiExtension implements ServiceExtension { + public static final String NAME = "Management API"; + static final String CONTEXT_NAME = "management"; + static final String PATH = "/management/v1"; + static final int PORT = 8282; + + @Inject + private DidEntryStore store; + + @Inject + private WebService webService; + + @Inject + private WebServer webServer; + + @Inject + private AuthenticationService authService; + + @Override + public String name() { + return NAME; + } + + @Override + public void initialize(ServiceExtensionContext context) { + webServer.addPortMapping(CONTEXT_NAME, PORT, PATH); + webService.registerResource(CONTEXT_NAME, new ManagementApiController(store)); + webService.registerResource(CONTEXT_NAME, new AuthenticationRequestFilter(authService)); + } + +} + diff --git a/api/management-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension b/api/management-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension new file mode 100644 index 0000000..bbeb15d --- /dev/null +++ b/api/management-api/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension @@ -0,0 +1,21 @@ +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# +org.eclipse.tractusx.bdrs.api.management.ManagementApiExtension diff --git a/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiControllerTest.java b/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiControllerTest.java new file mode 100644 index 0000000..7be0428 --- /dev/null +++ b/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiControllerTest.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.management; + +import io.restassured.path.json.JsonPath; +import io.restassured.specification.RequestSpecification; +import org.eclipse.edc.web.jersey.testfixtures.RestControllerTestBase; +import org.eclipse.tractusx.bdrs.spi.store.DidEntry; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.zip.GZIPOutputStream; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.JSON; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ManagementApiControllerTest extends RestControllerTestBase { + private static final String BPN = "BPN123"; + private static final String DID = "did:web:localhost:member"; + + private DidEntryStore store; + + @Test + void verifyGetEntries() throws IOException { + var entries = Map.of(BPN, new DidEntry(BPN, DID)); + var serialized = objectMapper.writeValueAsString(entries); + var serializedStream = new ByteArrayOutputStream(); + try (var gzip = new GZIPOutputStream(serializedStream)) { + gzip.write(serialized.getBytes()); + } + + when(store.entries()).thenReturn(serializedStream.toByteArray()); + + var expectedJson = new JsonPath(serialized); + baseRequest().get("") + .then() + .statusCode(200) + .contentType(JSON) + .body("", equalTo(expectedJson.getMap(""))); + } + + @Test + void verifySave() throws IOException { + var serialized = objectMapper.writeValueAsString(new DidEntry(BPN, DID)); + + var captor = ArgumentCaptor.forClass(DidEntry.class); + + baseRequest() + .contentType(JSON) + .body(serialized) + .post("") + .then() + .statusCode(204); + + verify(store).save(captor.capture()); + + assertThat(captor.getValue().bpn()).isEqualTo(BPN); + assertThat(captor.getValue().did()).isEqualTo(DID); + } + + @Test + void verifyUpdate() throws IOException { + var serialized = objectMapper.writeValueAsString(new DidEntry(BPN, DID)); + + var captor = ArgumentCaptor.forClass(DidEntry.class); + + baseRequest() + .contentType(JSON) + .body(serialized) + .put("") + .then() + .statusCode(204); + + verify(store).update(captor.capture()); + + assertThat(captor.getValue().bpn()).isEqualTo(BPN); + assertThat(captor.getValue().did()).isEqualTo(DID); + } + + @Test + void verifyDelete() { + var captor = ArgumentCaptor.forClass(String.class); + + baseRequest() + .contentType(JSON) + .delete("/" + BPN) + .then() + .statusCode(204); + + verify(store).delete(captor.capture()); + + assertThat(captor.getValue()).isEqualTo(BPN); + } + + @Override + protected Object controller() { + store = mock(DidEntryStore.class); + return new ManagementApiController(store); + } + + private RequestSpecification baseRequest() { + return given().baseUri("http://localhost:" + port).basePath("/bpn-directory").when(); + } +} diff --git a/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtensionTest.java b/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtensionTest.java new file mode 100644 index 0000000..1f24225 --- /dev/null +++ b/api/management-api/src/test/java/org/eclipse/tractusx/bdrs/api/management/ManagementApiExtensionTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.api.management; + +import org.eclipse.edc.junit.extensions.DependencyInjectionExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.web.spi.WebServer; +import org.eclipse.edc.web.spi.WebService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.eclipse.tractusx.bdrs.api.management.ManagementApiExtension.CONTEXT_NAME; +import static org.eclipse.tractusx.bdrs.api.management.ManagementApiExtension.PATH; +import static org.eclipse.tractusx.bdrs.api.management.ManagementApiExtension.PORT; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * + */ +@ExtendWith(DependencyInjectionExtension.class) +class ManagementApiExtensionTest { + + private WebServer webServer; + private WebService webService; + + @Test + void verifyBoot(ManagementApiExtension extension, ServiceExtensionContext context) { + extension.initialize(context); + + verify(webServer).addPortMapping(CONTEXT_NAME, PORT, PATH); + verify(webService).registerResource(eq(CONTEXT_NAME), isA(ManagementApiController.class)); + } + + @BeforeEach + void setUp(ServiceExtensionContext context) { + webServer = mock(WebServer.class); + context.registerService(WebServer.class, webServer); + + webService = mock(WebService.class); + context.registerService(WebService.class, webService); + } + +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..8ce59f2 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,107 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage +import com.github.jengelman.gradle.plugins.shadow.ShadowJavaPlugin + +plugins { + `java-library` + id("com.bmuschko.docker-remote-api") version "9.4.0" + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +buildscript { + dependencies { + val edcGradlePluginsVersion: String by project + classpath("org.eclipse.edc.edc-build:org.eclipse.edc.edc-build.gradle.plugin:${edcGradlePluginsVersion}") + } +} + +val metaModelVersion: String by project +val annotationProcessorVersion: String by project + +allprojects { + apply(plugin = "org.eclipse.edc.edc-build") + + // configure which version of the annotation processor to use. defaults to the same version as the plugin + configure { + outputDirectory.set(project.buildDir) + processorVersion.set(annotationProcessorVersion) + } + + configure { + versions { + // override default dependency versions here + metaModel.set(metaModelVersion) + } + } + + // EdcRuntimeExtension uses this to determine the runtime classpath of the module to run. + tasks.register("printClasspath") { + doLast { + println(sourceSets["main"].runtimeClasspath.asPath) + } + } +} +// the "dockerize" task is added to all projects that use the `shadowJar` plugin, e.g. runtimes +subprojects { + afterEvaluate { + if (project.plugins.hasPlugin("com.github.johnrengelman.shadow") && + file("${project.projectDir}/src/main/docker/Dockerfile").exists() + ) { + + // this task copies some legal docs into the build folder, so we can easily copy them into the docker images + val copyLegalDocs = tasks.create("copyLegalDocs", Copy::class) { + + into("${project.layout.buildDirectory.asFile.get()}") + into("legal") { + from("${project.rootProject.projectDir}/SECURITY.md") + from("${project.rootProject.projectDir}/NOTICE.md") + from("${project.rootProject.projectDir}/DEPENDENCIES") + from("${project.rootProject.projectDir}/LICENSE") + from("${projectDir}/notice.md") + + } + dependsOn(tasks.named(ShadowJavaPlugin.SHADOW_JAR_TASK_NAME)) + } + + //actually apply the plugin to the (sub-)project + apply(plugin = "com.bmuschko.docker-remote-api") + // configure the "dockerize" task + val dockerTask: DockerBuildImage = tasks.create("dockerize", DockerBuildImage::class) { + val dockerContextDir = project.projectDir + dockerFile.set(file("$dockerContextDir/src/main/docker/Dockerfile")) + images.add("${project.name}:${project.version}") + images.add("${project.name}:latest") + // specify platform with the -Dplatform flag: + if (System.getProperty("platform") != null) + platform.set(System.getProperty("platform")) + buildArgs.put("JAR", "build/libs/${project.name}.jar") + buildArgs.put("ADDITIONAL_FILES", "build/legal/*") + inputDir.set(file(dockerContextDir)) + } + // make sure always runs after "dockerize" and after "copyOtel" + dockerTask + .dependsOn(tasks.named(ShadowJavaPlugin.SHADOW_JAR_TASK_NAME)) + .dependsOn(copyLegalDocs) + } + } +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000..544982e --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,457 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000..e40a824 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,29 @@ + + + + + + + + diff --git a/core/core-services/build.gradle.kts b/core/core-services/build.gradle.kts new file mode 100644 index 0000000..97c7295 --- /dev/null +++ b/core/core-services/build.gradle.kts @@ -0,0 +1,30 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +plugins { + `java-library` +} + +dependencies { + implementation(libs.edc.spi.core) + implementation(project(":spi:core-spi")) +} + diff --git a/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/BdrsCoreExtension.java b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/BdrsCoreExtension.java new file mode 100644 index 0000000..4b2cb91 --- /dev/null +++ b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/BdrsCoreExtension.java @@ -0,0 +1,124 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +package org.eclipse.tractusx.bdrs.core; + +import org.eclipse.edc.runtime.metamodel.annotation.BaseExtension; +import org.eclipse.edc.runtime.metamodel.annotation.Extension; +import org.eclipse.edc.runtime.metamodel.annotation.Inject; +import org.eclipse.edc.runtime.metamodel.annotation.Provider; +import org.eclipse.edc.runtime.metamodel.annotation.Setting; +import org.eclipse.edc.spi.security.Vault; +import org.eclipse.edc.spi.system.ExecutorInstrumentation; +import org.eclipse.edc.spi.system.ServiceExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.spi.system.health.HealthCheckService; +import org.eclipse.edc.spi.types.TypeManager; +import org.eclipse.tractusx.bdrs.core.health.HealthCheckServiceConfiguration; +import org.eclipse.tractusx.bdrs.core.health.HealthCheckServiceImpl; +import org.eclipse.tractusx.bdrs.core.store.InMemoryDidEntryStore; +import org.eclipse.tractusx.bdrs.core.vault.InMemoryVault; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import java.time.Duration; + +import static org.eclipse.tractusx.bdrs.core.BdrsCoreExtension.NAME; + +/** + * Loads BDRS core services + */ +@BaseExtension +@Extension(NAME) +public class BdrsCoreExtension implements ServiceExtension { + public static final String NAME = "BDRS Core"; + + @Setting + public static final String LIVENESS_PERIOD_SECONDS_SETTING = "edc.core.system.health.check.liveness-period"; + + @Setting + public static final String STARTUP_PERIOD_SECONDS_SETTING = "edc.core.system.health.check.startup-period"; + + @Setting + public static final String READINESS_PERIOD_SECONDS_SETTING = "edc.core.system.health.check.readiness-period"; + + @Setting + public static final String THREADPOOL_SIZE_SETTING = "edc.core.system.health.check.threadpool-size"; + + private static final long DEFAULT_DURATION = 60; + private static final int DEFAULT_TP_SIZE = 3; + + @Inject + private TypeManager typeManager; + + private HealthCheckServiceImpl healthCheckService; + + @Override + public String name() { + return NAME; + } + + @Override + public void initialize(ServiceExtensionContext context) { + var config = getHealthCheckConfig(context); + var instrumentation = new ExecutorInstrumentation() { + }; + healthCheckService = new HealthCheckServiceImpl(config, instrumentation); + } + + @Override + public void start() { + healthCheckService.start(); + } + + @Override + public void shutdown() { + healthCheckService.stop(); + ServiceExtension.super.shutdown(); + } + + @Provider + public HealthCheckService healthCheckService() { + return healthCheckService; + } + + @Provider(isDefault = true) + public DidEntryStore defaultDidEntryStore() { + var store = new InMemoryDidEntryStore(typeManager.getMapper()); + // var stream = IntStream.range(0, 20000).mapToObj((i) -> new DidEntry(randomUUID().toString(), randomUUID().toString())); + // store.save(stream); + return store; + } + + @Provider(isDefault = true) + public Vault defaultVault() { + return new InMemoryVault(); + } + + private HealthCheckServiceConfiguration getHealthCheckConfig(ServiceExtensionContext context) { + return HealthCheckServiceConfiguration.Builder.newInstance() + .livenessPeriod(Duration.ofSeconds(context.getSetting(LIVENESS_PERIOD_SECONDS_SETTING, DEFAULT_DURATION))) + .startupStatusPeriod(Duration.ofSeconds(context.getSetting(STARTUP_PERIOD_SECONDS_SETTING, DEFAULT_DURATION))) + .readinessPeriod(Duration.ofSeconds(context.getSetting(READINESS_PERIOD_SECONDS_SETTING, DEFAULT_DURATION))) + .readinessPeriod(Duration.ofSeconds(context.getSetting(READINESS_PERIOD_SECONDS_SETTING, DEFAULT_DURATION))) + .threadPoolSize(context.getSetting(THREADPOOL_SIZE_SETTING, DEFAULT_TP_SIZE)) + .build(); + } +} diff --git a/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceConfiguration.java b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceConfiguration.java new file mode 100644 index 0000000..9bbfb81 --- /dev/null +++ b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceConfiguration.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2022 Amadeus + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Amadeus - Initial implementation + * + */ + +package org.eclipse.tractusx.bdrs.core.health; + +import org.eclipse.edc.spi.system.health.LivenessProvider; +import org.eclipse.edc.spi.system.health.ReadinessProvider; +import org.eclipse.edc.spi.system.health.StartupStatusProvider; + +import java.time.Duration; + +/** + * Temporarily copied from the EDC to avoid dragging in Connector dependencies. This will be removed in the future. + */ +public class HealthCheckServiceConfiguration { + public static final long DEFAULT_PERIOD_SECONDS = 60; + public static final int DEFAULT_THREADPOOL_SIZE = 3; + private int threadPoolSize = DEFAULT_THREADPOOL_SIZE; + private Duration readinessPeriod = Duration.ofSeconds(DEFAULT_PERIOD_SECONDS); + private Duration livenessPeriod = Duration.ofSeconds(DEFAULT_PERIOD_SECONDS); + private Duration startupStatusPeriod = Duration.ofSeconds(DEFAULT_PERIOD_SECONDS); + + /** + * how many threads should be used by the health check service for periodic polling + */ + public int getThreadPoolSize() { + return threadPoolSize; + } + + /** + * Time delay between before {@link ReadinessProvider}s are checked again. + * Defaults to 10 seconds. + */ + public Duration getReadinessPeriod() { + return readinessPeriod; + } + + /** + * Time delay between before {@link LivenessProvider}s are checked again. + * Defaults to 10 seconds. + */ + public Duration getLivenessPeriod() { + return livenessPeriod; + } + + /** + * Time delay between before {@link StartupStatusProvider}s are checked again. + * Defaults to 10 seconds. + */ + public Duration getStartupStatusPeriod() { + return startupStatusPeriod; + } + + public static final class Builder { + private final HealthCheckServiceConfiguration config; + + private Builder() { + config = new HealthCheckServiceConfiguration(); + } + + public static Builder newInstance() { + return new Builder(); + } + + public Builder readinessPeriod(Duration readinessPeriod) { + config.readinessPeriod = readinessPeriod; + return this; + } + + public Builder livenessPeriod(Duration livenessPeriod) { + config.livenessPeriod = livenessPeriod; + return this; + } + + public Builder startupStatusPeriod(Duration startupStatusPeriod) { + config.startupStatusPeriod = startupStatusPeriod; + return this; + } + + public Builder threadPoolSize(int threadPoolSize) { + config.threadPoolSize = threadPoolSize; + return this; + } + + public HealthCheckServiceConfiguration build() { + return config; + } + } +} diff --git a/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceImpl.java b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceImpl.java new file mode 100644 index 0000000..aff0214 --- /dev/null +++ b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/health/HealthCheckServiceImpl.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2022 Amadeus + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Amadeus - Initial implementation + * + */ + +package org.eclipse.tractusx.bdrs.core.health; + +import org.eclipse.edc.spi.system.ExecutorInstrumentation; +import org.eclipse.edc.spi.system.health.HealthCheckResult; +import org.eclipse.edc.spi.system.health.HealthCheckService; +import org.eclipse.edc.spi.system.health.HealthStatus; +import org.eclipse.edc.spi.system.health.LivenessProvider; +import org.eclipse.edc.spi.system.health.ReadinessProvider; +import org.eclipse.edc.spi.system.health.StartupStatusProvider; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * Temporarily copied from the EDC to avoid dragging in Connector dependencies. This will be removed in the future. + */ +public class HealthCheckServiceImpl implements HealthCheckService { + private final List livenessProviders; + private final List readinessProviders; + private final List startupStatusProviders; + + private final Map cachedLivenessResults; + private final Map cachedReadinessResults; + private final Map cachedStartupStatus; + + private final ScheduledExecutorService executor; + private final HealthCheckServiceConfiguration configuration; + + public HealthCheckServiceImpl(HealthCheckServiceConfiguration configuration, + ExecutorInstrumentation executorInstrumentation) { + this.configuration = configuration; + readinessProviders = new CopyOnWriteArrayList<>(); + livenessProviders = new CopyOnWriteArrayList<>(); + startupStatusProviders = new CopyOnWriteArrayList<>(); + + cachedLivenessResults = new ConcurrentHashMap<>(); + cachedReadinessResults = new ConcurrentHashMap<>(); + cachedStartupStatus = new ConcurrentHashMap<>(); + + executor = executorInstrumentation.instrument( + Executors.newScheduledThreadPool(configuration.getThreadPoolSize()), + HealthCheckService.class.getSimpleName()); + } + + @Override + public void addLivenessProvider(LivenessProvider provider) { + livenessProviders.add(provider); + } + + @Override + public void addReadinessProvider(ReadinessProvider provider) { + readinessProviders.add(provider); + } + + @Override + public void addStartupStatusProvider(StartupStatusProvider provider) { + startupStatusProviders.add(provider); + } + + @Override + public HealthStatus isLive() { + return new HealthStatus(cachedLivenessResults.values()); + } + + @Override + public HealthStatus isReady() { + return new HealthStatus(cachedReadinessResults.values()); + } + + @Override + public HealthStatus getStartupStatus() { + return new HealthStatus(cachedStartupStatus.values()); + } + + @Override + public void refresh() { + executor.execute(this::queryReadiness); + executor.execute(this::queryLiveness); + executor.execute(this::queryStartupStatus); + } + + public void stop() { + if (!executor.isShutdown()) { + executor.shutdownNow(); + } + } + + public void start() { + //todo: maybe providers should provide their desired timeout instead of a global config? + executor.scheduleAtFixedRate(this::queryReadiness, 0, configuration.getReadinessPeriod().toMillis(), TimeUnit.MILLISECONDS); + executor.scheduleAtFixedRate(this::queryLiveness, 0, configuration.getLivenessPeriod().toMillis(), TimeUnit.MILLISECONDS); + executor.scheduleAtFixedRate(this::queryStartupStatus, 0, configuration.getStartupStatusPeriod().toMillis(), TimeUnit.MILLISECONDS); + } + + private void queryReadiness() { + readinessProviders.parallelStream().forEach(provider -> updateCache(provider, cachedReadinessResults)); + } + + private void queryLiveness() { + livenessProviders.parallelStream().forEach(provider -> updateCache(provider, cachedLivenessResults)); + } + + private void queryStartupStatus() { + startupStatusProviders.parallelStream().forEach(provider -> updateCache(provider, cachedStartupStatus)); + } + + private > void updateCache(T provider, Map cache) { + try { + cache.put(provider, provider.get()); + } catch (Exception ex) { + cache.put(provider, HealthCheckResult.failed(ex.getMessage())); + } + } + +} diff --git a/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStore.java b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStore.java new file mode 100644 index 0000000..e68298e --- /dev/null +++ b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStore.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.core.store; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.eclipse.edc.spi.EdcException; +import org.eclipse.tractusx.bdrs.spi.store.DidEntry; +import org.eclipse.tractusx.bdrs.spi.store.DidEntryStore; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; + +import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +/** + * A non-persistent, concurrent store implementation. + */ +public class InMemoryDidEntryStore implements DidEntryStore { + private static final int LOCK_TIMEOUT = 1000; + + private final AtomicReference cache = new AtomicReference<>(new byte[0]); + private final Map backingStore = new HashMap<>(); + + private final ObjectMapper mapper; + private final ReadWriteLock lock; + + public InMemoryDidEntryStore(ObjectMapper mapper) { + this.mapper = mapper; + lock = new ReentrantReadWriteLock(true); + updateCache(); + + } + + @Override + public byte[] entries() { + return cache.get(); + } + + @Override + public void save(DidEntry entry) { + requireNonNull(entry); + writeLock(() -> { + backingStore.put(entry.bpn(), entry.did()); + updateCache(); + }); + } + + @Override + public void save(Stream entries) { + writeLock(() -> { + entries.forEach(entry -> backingStore.put(entry.bpn(), entry.did())); + updateCache(); + }); + } + + @Override + public void delete(String bpn) { + requireNonNull(bpn); + writeLock(() -> { + backingStore.remove(bpn); + updateCache(); + }); + updateCache(); + } + + private void updateCache() { + var bas = new ByteArrayOutputStream(); + try (var gzip = new GZIPOutputStream(bas)) { + gzip.write(mapper.writeValueAsBytes(backingStore)); + } catch (IOException e) { + throw new RuntimeException(e); + } + cache.set(bas.toByteArray()); + } + + /** + * Attempts to obtain a write lock. + */ + private void writeLock(Runnable work) { + try { + if (!lock.writeLock().tryLock(LOCK_TIMEOUT, MILLISECONDS)) { + throw new EdcException("Timeout acquiring write lock"); + } + try { + work.run(); + } finally { + lock.writeLock().unlock(); + } + } catch (InterruptedException e) { + //noinspection ResultOfMethodCallIgnored + Thread.interrupted(); + throw new EdcException(e); + } + } + +} diff --git a/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/vault/InMemoryVault.java b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/vault/InMemoryVault.java new file mode 100644 index 0000000..d892be7 --- /dev/null +++ b/core/core-services/src/main/java/org/eclipse/tractusx/bdrs/core/vault/InMemoryVault.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.core.vault; + +import org.eclipse.edc.spi.result.Result; +import org.eclipse.edc.spi.security.Vault; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A concurrent, non-persistent vault. + */ +public class InMemoryVault implements Vault { + private final Map cache = new ConcurrentHashMap<>(); + + @Override + public @Nullable String resolveSecret(String key) { + return cache.get(key); + } + + @Override + public Result storeSecret(String key, String value) { + cache.put(key, value); + return Result.success(); + } + + @Override + public Result deleteSecret(String key) { + cache.remove(key); + return Result.success(); + } +} diff --git a/core/core-services/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension b/core/core-services/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension new file mode 100644 index 0000000..3d6f347 --- /dev/null +++ b/core/core-services/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension @@ -0,0 +1,21 @@ +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# +org.eclipse.tractusx.bdrs.core.BdrsCoreExtension diff --git a/core/core-services/src/test/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStoreTest.java b/core/core-services/src/test/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStoreTest.java new file mode 100644 index 0000000..e1e6b5c --- /dev/null +++ b/core/core-services/src/test/java/org/eclipse/tractusx/bdrs/core/store/InMemoryDidEntryStoreTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.core.store; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.eclipse.tractusx.bdrs.spi.store.DidEntry; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Map; +import java.util.stream.Stream; +import java.util.zip.GZIPInputStream; + +import static org.assertj.core.api.Assertions.assertThat; + +class InMemoryDidEntryStoreTest { + private static final String BPN = "BPN12345"; + private static final String DID = "did:web:localhost:member"; + private static final String DID2 = "did:web:localhost:member2"; + + private ObjectMapper mapper; + private InMemoryDidEntryStore store; + + @Test + void verifySave() throws IOException { + store.save(new DidEntry(BPN, DID)); + + var bytes = store.entries(); + + var entries = deserialize(bytes); + + assertThat(entries.get(BPN)).isEqualTo(DID); + } + + @Test + void verifyStreamSave() throws IOException { + store.save(Stream.of(new DidEntry(BPN, DID))); + var bytes = store.entries(); + + var entries = deserialize(bytes); + + assertThat(entries.get(BPN)).isEqualTo(DID); + } + + @Test + void verifyUpdate() throws IOException { + store.save(new DidEntry(BPN, DID)); + store.update(new DidEntry(BPN, DID2)); + + var bytes = store.entries(); + + var entries = deserialize(bytes); + + assertThat(entries.get(BPN)).isEqualTo(DID2); + } + + @Test + void verifyRemove() throws IOException { + store.save(new DidEntry(BPN, DID)); + store.delete(BPN); + + var bytes = store.entries(); + + var entries = deserialize(bytes); + + assertThat(entries).isEmpty(); + } + + @BeforeEach + void setUp() { + mapper = new ObjectMapper(); + store = new InMemoryDidEntryStore(mapper); + } + + private Map deserialize(byte[] bytes) throws IOException { + var stream = new GZIPInputStream(new ByteArrayInputStream(bytes)); + var decompressed = stream.readAllBytes(); + //noinspection unchecked + return mapper.readValue(decompressed, Map.class); + } + +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..d678f68 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,29 @@ +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# + +group=org.eclipse.tractusx +version=0.0.1 + +# these define the versions of the EDC Build Plugin, the Annotation Processor and the Metamodel. +# generally this should match the version of EDC in gradle/libs.versions.toml +edcGradlePluginsVersion=0.5.0 +annotationProcessorVersion=0.5.0 +metaModelVersion=0.5.0 \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..31a7d90 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,33 @@ +[metadata] +format.version = "1.1" + +[versions] +edc = "0.5.0" +nimbus = "9.37.3" +restAssured = "5.4.0" + +[libraries] +edc-core-jetty = { module = "org.eclipse.edc:jetty-core", version.ref = "edc" } +edc-core-jersey = { module = "org.eclipse.edc:jersey-core", version.ref = "edc" } + +edc-boot = { module = "org.eclipse.edc:boot", version.ref = "edc" } +edc-spi-core = { module = "org.eclipse.edc:core-spi", version.ref = "edc" } +edc-spi-web = { module = "org.eclipse.edc:web-spi", version.ref = "edc" } +edc-connector-core = { module = "org.eclipse.edc:connector-core", version.ref = "edc" } +#edc-spi-identity-trust = { module = "org.eclipse.edc:identity-trust-spi", version.ref = "edc" } +edc-spi-jwt = { module = "org.eclipse.edc:jwt-spi", version.ref = "edc" } +edc-spi-auth = { module = "org.eclipse.edc:auth-spi", version.ref = "edc" } +edc-auth-tokenbased = { module = "org.eclipse.edc:auth-tokenbased", version.ref = "edc" } +edc-vault-filesystem = { module = "org.eclipse.edc:vault-filesystem", version.ref = "edc" } +edc-junit = { module = "org.eclipse.edc:junit", version.ref = "edc" } + +# Third party libs +nimbus-jwt = { module = "com.nimbusds:nimbus-jose-jwt", version.ref = "nimbus" } +restAssured = { module = "io.rest-assured:rest-assured", version.ref = "restAssured" } + +[plugins] +shadow = { id = "com.github.johnrengelman.shadow", version = "8.1.1" } + +[bundles] +# TODO: "edc-vault-filesystem" - remove dependency on org.eclipse.edc.vault.filesystem.JskPrivateKeyResolverExtension +bdrs-boot = ["edc-core-jetty", "edc-core-jersey", "edc-boot", "edc-spi-auth", "edc-auth-tokenbased"] diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..173613c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,28 @@ +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# + +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..efee75e --- /dev/null +++ b/gradlew @@ -0,0 +1,254 @@ +#!/bin/sh + +# +# +# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/runtimes/server/build.gradle.kts b/runtimes/server/build.gradle.kts new file mode 100644 index 0000000..7340536 --- /dev/null +++ b/runtimes/server/build.gradle.kts @@ -0,0 +1,46 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +plugins { + id("application") + alias(libs.plugins.shadow) +} + +dependencies { + runtimeOnly(libs.bundles.bdrs.boot) + runtimeOnly(project(":core:core-services")) + runtimeOnly(project(":api:directory-api")) + runtimeOnly(project(":api:management-api")) +} + +tasks.withType { + exclude("**/pom.properties", "**/pom.xm") + mergeServiceFiles() + archiveFileName.set("${project.name}.jar") +} + +application { + mainClass.set("org.eclipse.edc.boot.system.runtime.BaseRuntime") +} + +edcBuild { + publish.set(false) +} diff --git a/runtimes/server/notice.md b/runtimes/server/notice.md new file mode 100644 index 0000000..167b791 --- /dev/null +++ b/runtimes/server/notice.md @@ -0,0 +1,29 @@ +# Notice for Docker image + +Eclipse Tractus-X product(s) installed within the image: + +## BDRS + +Launch: + +> docker run -p 8181:8181 -p 8282:8282 -e EDC_API_AUTH_KEY="1234" server + +- Project license: [Apache License, Version 2.0](https://github.com/eclipse-tractusx/tractusx-edc/blob/main/LICENSE) + +## Used base image + +- [eclipse-temurin:21.0.2_13-jre-alpine](https://github.com/adoptium/containers) +- Official Eclipse Temurin DockerHub page: +- Eclipse Temurin Project: +- Additional information about the Eclipse Temurin + images: + +## Third-Party Software + +- OpenTelemetry Agent v1.32.0: + +As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc +from the base distribution, along with any direct or indirect dependencies of the primary software being contained). + +As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies +with any relevant licenses for all software contained within. diff --git a/runtimes/server/src/main/docker/Dockerfile b/runtimes/server/src/main/docker/Dockerfile new file mode 100644 index 0000000..5f573a5 --- /dev/null +++ b/runtimes/server/src/main/docker/Dockerfile @@ -0,0 +1,30 @@ +# -buster is required to have apt available +FROM eclipse-temurin:21.0.2_13-jre-alpine + +# Optional JVM arguments, such as memory settings +ARG JVM_ARGS="" +ARG JAR +ARG ADDITIONAL_FILES + +RUN apk --no-cache add curl + +WORKDIR /app + + +COPY ${JAR} server.jar +COPY ${ADDITIONAL_FILES} ./ + +EXPOSE 8080 + +ENV WEB_HTTP_PORT="8181" +ENV WEB_HTTP_PATH="/" +ENV EDC_PARTICIPANT_ID="BDRS" +ENV EDC_CONNECTOR_NAME="BDRS" + +HEALTHCHECK --interval=5s --timeout=5s --retries=10 CMD curl --fail http://localhost:8080/api/check/health + +# Use "exec" for graceful termination (SIGINT) to reach JVM. +# ARG can not be used in ENTRYPOINT so storing value in an ENV variable +ENV ENV_JVM_ARGS=$JVM_ARGS +# use the "exec" syntax so that SIGINT reaches the JVM -> graceful termination +CMD ["sh", "-c", "exec java -Djava.util.logging.config.file=/app/logging.properties -Djava.security.egd=file:/dev/urandom -jar server.jar"] diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5159fa2 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +// this is needed to have access to snapshot builds of plugins +pluginManagement { + repositories { + mavenLocal() + maven { + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + + repositories { + maven { + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } + mavenCentral() + mavenLocal() + } +} + +rootProject.name = "tractusx-bdrs" + +include(":spi:core-spi") +include(":core:core-services") +include(":api:directory-api") +include(":api:management-api") +include(":runtimes:server") diff --git a/spi/core-spi/build.gradle.kts b/spi/core-spi/build.gradle.kts new file mode 100644 index 0000000..d065ee3 --- /dev/null +++ b/spi/core-spi/build.gradle.kts @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +plugins { + `java-library` +} + +dependencies { +} + diff --git a/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntry.java b/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntry.java new file mode 100644 index 0000000..e73d1fb --- /dev/null +++ b/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntry.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.spi.store; + +import static java.util.Objects.requireNonNull; + +/** + * A BPN to DID mapping. + */ +public record DidEntry(String bpn, String did) { + public DidEntry { + requireNonNull(bpn, "bpn"); + requireNonNull(did, "did"); + } +} diff --git a/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntryStore.java b/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntryStore.java new file mode 100644 index 0000000..2da3297 --- /dev/null +++ b/spi/core-spi/src/main/java/org/eclipse/tractusx/bdrs/spi/store/DidEntryStore.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + * + * Contributors: + * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation + * + */ + +package org.eclipse.tractusx.bdrs.spi.store; + +import java.util.stream.Stream; + +/** + * Stores {@link DidEntry}s. + */ +public interface DidEntryStore { + + /** + * Returns all serialized JSON entries as a compressed (GZIP) byte array. + */ + byte[] entries(); + + /** + * Adds a new BPN-DID mapping. + */ + void save(DidEntry entry); + + /** + * Bulk adds a new BPN-DID mapping. + */ + void save(Stream entries); + + /** + * Updates a BPN-DID mapping. + */ + default void update(DidEntry entry) { + this.save(entry); + } + + /** + * Removes a BPN-DID mapping. + */ + void delete(String bpn); + +}