diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 4662abef..5b20da4b 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -2,7 +2,7 @@ name: Java Maven Build on: push: - branches: + branches: - '**' paths-ignore: - '**/README.md' @@ -18,46 +18,46 @@ jobs: runs-on: ubuntu-latest steps: - - name: Checkout source - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - name: Set up JDK - uses: actions/setup-java@v3 - with: - java-version: '17' - distribution: 'zulu' - cache: maven - - - name: Show versions - run: java -version && ./mvnw -version && gpg --version - - - name: Cache SonarCloud packages - uses: actions/cache@v3 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - - name: Cache Maven packages - uses: actions/cache@v3 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - - name: Import GPG key - uses: crazy-max/ghaction-import-gpg@v5 - with: - gpg_private_key: ${{ secrets.OSS_SONATYPE_GPG_PRIVATE_KEY }} - passphrase: ${{ secrets.OSS_SONATYPE_GPG_PASSPHRASE }} - - - name: Build with Maven - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OSS_SONATYPE_USERNAME: michael-schnell - OSS_SONATYPE_TOKEN: ${{ secrets.OSS_SONATYPE_TOKEN }} - OSS_SONATYPE_GPG_PASSPHRASE: ${{ secrets.OSS_SONATYPE_GPG_PASSPHRASE }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: ./mvnw clean deploy jacoco:report sonar:sonar -U -B -P sonatype-oss-release --file pom.xml -s settings.xml + - name: Checkout source + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up JDK + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'zulu' + cache: maven + + - name: Show versions + run: java -version && ./mvnw -version && gpg --version + + - name: Cache SonarCloud packages + uses: actions/cache@v3 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + - name: Cache Maven packages + uses: actions/cache@v3 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + - name: Import GPG key + uses: crazy-max/ghaction-import-gpg@v5 + with: + gpg_private_key: ${{ secrets.OSS_SONATYPE_GPG_PRIVATE_KEY }} + passphrase: ${{ secrets.OSS_SONATYPE_GPG_PASSPHRASE }} + + - name: Build with Maven + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + OSS_SONATYPE_USERNAME: michael-schnell + OSS_SONATYPE_TOKEN: ${{ secrets.OSS_SONATYPE_TOKEN }} + OSS_SONATYPE_GPG_PASSPHRASE: ${{ secrets.OSS_SONATYPE_GPG_PASSPHRASE }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: ./mvnw clean deploy jacoco:report sonar:sonar -U -B -P sonatype-oss-release --file pom.xml -s settings.xml diff --git a/README.md b/README.md index 4b220e71..5b238ffa 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # event-store-commons -Defines a common event store Java interface and provides some adapters (like for Greg Young's [event store](https://www.geteventstore.com/)) and implementations (like in-memory or file-based). + +Defines a common event store Java interface and provides some adapters (like for Greg +Young's [event store](https://www.geteventstore.com/)) and implementations (like in-memory or file-based). [![Java Maven Build](https://github.com/fuinorg/event-store-commons/actions/workflows/maven.yml/badge.svg)](https://github.com/fuinorg/event-store-commons/actions/workflows/maven.yml) [![Coverage Status](https://sonarcloud.io/api/project_badges/measure?project=org.fuin.esc%3Aevent-store-commons&metric=coverage)](https://sonarcloud.io/dashboard?id=org.fuin.esc%3Aevent-store-commons) @@ -8,41 +10,39 @@ Defines a common event store Java interface and provides some adapters (like for [![Java Development Kit 17](https://img.shields.io/badge/JDK-17-green.svg)](https://openjdk.java.net/projects/jdk/17/) ## Versions -- 0.7.x = New **GRPC** client / Removed **http**/**esjc** modules + +- 0.8.x = Refactoring if the module structure (Incompatible!) +- 0.7.x = New **GRPC** client / Removed **http**/**esjc** modules - 0.6.x = **Java 17** and JUnit5 - 0.5.x = **Java 11** with new **jakarta** namespace - 0.4.x = **Java 11** before namespace change from 'javax' to 'jakarta' - 0.3.2 (or less) = **Java 8** - -*Caution*: The code coverage value is not correct (it's actually higher than above value) as the 'test' module is not considered correctly (See [Issue #4](https://github.com//fuinorg/event-store-commons/issues/4)) - +*Caution*: The code coverage value is not correct (it's actually higher than above value) as the 'test' module is not +considered correctly (See [Issue #4](https://github.com//fuinorg/event-store-commons/issues/4)) ## Status -![Warning](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/warning.gif) **This is work in progress** ![Warning](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/warning.gif) -| Module | Description | Status | Comment | -|:------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------|--------|:-----------------------------| -| [esc-api](api) | Defines the event store commons API. | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~92% | -| [esc-http-admin](admin) | HTTP projection admin adapter for Greg Young's [event store](https://www.geteventstore.com/) | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~80% | -| [esc-grpc](grpc) | [Event Store DB Client](https://github.com/EventStore/EventStoreDB-Client-Java) adapter for Greg Young's [event store](https://www.geteventstore.com/) | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~80% | -| [esc-jpa](jpa) | JPA adapter | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~59% | -| [esc-mem](mem) | In-memory implementation | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~60% | -| [esc-spi](spi) | Helper classes for adapters and implementations | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Test coverage ~67% | -| [esc-test](test) | Cucumber tests for adapters and implementations | ![OK](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/ok.png) | Subscriptions not tested yet | - -Deprecated modules: - -| Module | Description | Comment | -|:-------------------|:-------------------------------------------------------------|:------------------------------------------------------| -| [esc-http](eshttp) | HTTP adapter for Greg Young's event store | No longer supported by event store (use GRPC instead) | -| [esc-esjc](esjc) | Event Store Java Client adapter for Greg Young's event store | No longer supported by event store (use GRPC instead) | +![Warning](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/warning.gif) **This is work in +progress** ![Warning](https://raw.githubusercontent.com/fuinorg/event-store-commons/master/doc/warning.gif) +| Module | Description | +|:-------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------| +| [esc-api](api) | Defines the event store commons API. | +| [esc-grpc](grpc) | [Event Store DB Client](https://github.com/EventStore/EventStoreDB-Client-Java) adapter for Greg Young's [event store](https://www.geteventstore.com/) | +| [esc-jaxb](jaxb) | JAX-B serialization support | +| [esc-jpa](jpa) | JPA adapter | +| [esc-jsonb](jsonb) | JSON-B serialization support | +| [esc-mem](mem) | In-memory implementation | +| [esc-spi](spi) | Helper classes for adapters and implementations | +| [esc-test](test) | Cucumber tests for adapters and implementations | ## Architecture + ![Layers](https://raw.github.com/fuinorg/event-store-commons/master/doc/event-store-commons.png) ## Examples + - [Simple in-memory example](test/src/test/java/org/fuin/esc/test/examples/InMemoryExample.java) - [Event store with HTTP interface and XML (JAX-B)](test/src/test/java/org/fuin/esc/test/examples/EsHttpXmlExample.java) - [Event store with HTTP interface and JSON (JSON-B)](test/src/test/java/org/fuin/esc/test/examples/EsHttpJsonbExample.java) @@ -50,9 +50,12 @@ Deprecated modules: ### Snapshots -Snapshots can be found on the [OSS Sonatype Snapshots Repository](https://oss.sonatype.org/content/repositories/snapshots/org/fuin/esc/ "Snapshot Repository"). +Snapshots can be found on +the [OSS Sonatype Snapshots Repository](https://oss.sonatype.org/content/repositories/snapshots/org/fuin/esc/ "Snapshot Repository"). -Add the following to your [.m2/settings.xml](http://maven.apache.org/ref/3.2.1/maven-settings/settings.html "Reference configuration") to enable snapshots in your Maven build: +Add the following to +your [.m2/settings.xml](http://maven.apache.org/ref/3.2.1/maven-settings/settings.html "Reference configuration") to +enable snapshots in your Maven build: ```xml diff --git a/api/README.md b/api/README.md index 7e9eae4a..b0ca090f 100644 --- a/api/README.md +++ b/api/README.md @@ -1,18 +1,20 @@ # esc-api + Defines the event store commons API. -| Interface (Synchronous) | Description | -|:------------------------|:------------| -| [ReadableEventStore](src/main/java/org/fuin/esc/api/ReadableEventStore.java) | Read only functionality | -| [WritableEventStore](src/main/java/org/fuin/esc/api/WritableEventStore.java) | Write Only functionality | -| [EventStore](src/main/java/org/fuin/esc/api/EventStore.java) | Combined read and write functionality | -| [SubscribableEventStore](src/main/java/org/fuin/esc/api/SubscribableEventStore.java) | Handles volatile subscriptions | +| Interface (Synchronous) | Description | +|:-------------------------------------------------------------------------------------|:--------------------------------------| +| [ReadableEventStore](src/main/java/org/fuin/esc/api/ReadableEventStore.java) | Read only functionality | +| [WritableEventStore](src/main/java/org/fuin/esc/api/WritableEventStore.java) | Write Only functionality | +| [EventStore](src/main/java/org/fuin/esc/api/EventStore.java) | Combined read and write functionality | +| [SubscribableEventStore](src/main/java/org/fuin/esc/api/SubscribableEventStore.java) | Handles volatile subscriptions | -| Interface (Asynchronous) | Description | -|:-------------------------|:------------| -| [ReadableEventStoreAsync](src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java) | Read only functionality | -| [WritableEventStoreAsync](src/main/java/org/fuin/esc/api/WritableEventStoreAsync.java) | Write Only functionality | -| [EventStoreAsync](src/main/java/org/fuin/esc/api/EventStoreAsync.java) | Combined read and write functionality | -| [SubscribableEventStoreAsync](src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java) | Handles volatile subscriptions | +| Interface (Asynchronous) | Description | +|:-----------------------------------------------------------------------------------------------|:--------------------------------------| +| [ReadableEventStoreAsync](src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java) | Read only functionality | +| [WritableEventStoreAsync](src/main/java/org/fuin/esc/api/WritableEventStoreAsync.java) | Write Only functionality | +| [EventStoreAsync](src/main/java/org/fuin/esc/api/EventStoreAsync.java) | Combined read and write functionality | +| [SubscribableEventStoreAsync](src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java) | Handles volatile subscriptions | -Simple delegating asynchronous event store that uses a synchronous one internally: [DelegatingAsyncEventStore](src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java) \ No newline at end of file +Simple delegating asynchronous event store that uses a synchronous one +internally: [DelegatingAsyncEventStore](src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java) \ No newline at end of file diff --git a/api/pom.xml b/api/pom.xml index 154768a5..df61bba7 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 @@ -16,17 +16,6 @@ esc-api Defines the event store commons API. - - https://github.com/fuinorg/event-store-commons/ - scm:git:git://github.com/fuinorg/event-store-commons.git - scm:git:git@github.com:fuinorg/event-store-commons.git - - - - GitHub Issues - https://github.com/fuinorg/event-store-commons/issues - - @@ -36,11 +25,6 @@ objects4j-common - - org.fuin - utils4j - - org.fuin.objects4j objects4j-core @@ -49,37 +33,21 @@ jakarta.validation jakarta.validation-api - true - - - - jakarta.xml.bind - jakarta.xml.bind-api - - - - jakarta.json.bind - jakarta.json.bind-api - - - - org.apache.commons - commons-lang3 - org.slf4j - slf4j-api + com.google.code.findbugs + jsr305 - jakarta.json - jakarta.json-api + jakarta.annotation + jakarta.annotation-api - io.smallrye - jandex + jakarta.activation + jakarta.activation-api @@ -121,32 +89,32 @@ - org.xmlunit - xmlunit-core + nl.jqno.equalsverifier + equalsverifier test - nl.jqno.equalsverifier - equalsverifier + com.tngtech.archunit + archunit test - commons-io - commons-io + com.tngtech.archunit + archunit-junit5 test - commons-codec - commons-codec + org.fuin + units4j test - - org.eclipse - yasson + + org.fuin + utils4j test @@ -162,6 +130,11 @@ + + org.apache.maven.plugins + maven-dependency-plugin + + org.apache.maven.plugins maven-compiler-plugin @@ -194,7 +167,20 @@ org.apache.maven.plugins - maven-jdeps-plugin + maven-dependency-plugin + + + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + diff --git a/api/src/main/java/org/fuin/esc/api/CommonEvent.java b/api/src/main/java/org/fuin/esc/api/CommonEvent.java index 16887fb0..646e3482 100644 --- a/api/src/main/java/org/fuin/esc/api/CommonEvent.java +++ b/api/src/main/java/org/fuin/esc/api/CommonEvent.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,42 +29,42 @@ public interface CommonEvent { /** * Returns the ID of the event, used as part of the idempotent write check. This is type string to allow * different UUID implementations. It has to be a valid UUID string representation. - * + * * @return Unique event identifier. */ @NotNull - public EventId getId(); + EventId getId(); /** * Returns the event type. - * + * * @return Never changing unique event type name. */ @NotNull - public TypeName getDataType(); + TypeName getDataType(); /** * Returns the event data. - * + * * @return Event data. */ @NotNull - public Object getData(); + Object getData(); /** - * Returns the meta data type. - * + * Returns the metadata type. + * * @return Never changing unique event meta data type name. */ @Nullable - public TypeName getMetaType(); - + TypeName getMetaType(); + /** - * Returns the meta data. - * + * Returns the metadata. + * * @return Meta data. */ @Nullable - public Object getMeta(); + Object getMeta(); } diff --git a/api/src/main/java/org/fuin/esc/api/Converter.java b/api/src/main/java/org/fuin/esc/api/Converter.java index 1f50ba9c..fc32c8a3 100644 --- a/api/src/main/java/org/fuin/esc/api/Converter.java +++ b/api/src/main/java/org/fuin/esc/api/Converter.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,7 @@ /** * Converts a type into another one. - * + * * @param Source type. * @param Target type. */ @@ -27,25 +27,25 @@ public interface Converter { /** * Returns the source type. - * + * * @return Input type. */ - public Class getSourceType(); + Class getSourceType(); /** * Returns the target type. - * + * * @return Output type. */ - public Class getTargetType(); - + Class getTargetType(); + /** * Converts the given source type into the target type. - * + * * @param source Type to convert. - * + * * @return Converted type. */ - public TARGET convert(SOURCE source); - + TARGET convert(SOURCE source); + } diff --git a/api/src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java b/api/src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java index 9a2aae89..2bd987c9 100644 --- a/api/src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java +++ b/api/src/main/java/org/fuin/esc/api/DelegatingAsyncEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -30,13 +30,13 @@ */ public final class DelegatingAsyncEventStore implements EventStoreAsync { - private Executor executor; + private final Executor executor; - private EventStore delegate; + private final EventStore delegate; /** * Constructor with all mandatory data. - * + * * @param executor * Executor used to create the completable futures. * @param delegate @@ -51,7 +51,7 @@ public DelegatingAsyncEventStore(@NotNull final Executor executor, @NotNull fina } @Override - public final CompletableFuture open() { + public CompletableFuture open() { return CompletableFuture.runAsync(new Runnable() { @Override public void run() { @@ -61,12 +61,12 @@ public void run() { } @Override - public final void close() { + public void close() { delegate.close(); } @Override - public final CompletableFuture readEvent(final StreamId streamId, final long eventNumber) { + public CompletableFuture readEvent(final StreamId streamId, final long eventNumber) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -78,8 +78,8 @@ public CommonEvent get() { } @Override - public final CompletableFuture readEventsForward(final StreamId streamId, - final long start, final int count) { + public CompletableFuture readEventsForward(final StreamId streamId, + final long start, final int count) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -91,8 +91,8 @@ public StreamEventsSlice get() { } @Override - public final CompletableFuture readEventsBackward(final StreamId streamId, - final long start, final int count) { + public CompletableFuture readEventsBackward(final StreamId streamId, + final long start, final int count) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -104,8 +104,8 @@ public StreamEventsSlice get() { } @Override - public final CompletableFuture deleteStream(final StreamId streamId, final long expected, - final boolean hardDelete) { + public CompletableFuture deleteStream(final StreamId streamId, final long expected, + final boolean hardDelete) { return CompletableFuture.runAsync(new Runnable() { @Override @@ -117,7 +117,7 @@ public void run() { } @Override - public final CompletableFuture deleteStream(final StreamId streamId, final boolean hardDelete) { + public CompletableFuture deleteStream(final StreamId streamId, final boolean hardDelete) { return CompletableFuture.runAsync(new Runnable() { @Override @@ -129,8 +129,8 @@ public void run() { } @Override - public final CompletableFuture appendToStream(final StreamId streamId, final long expectedVersion, - final List toAppend) { + public CompletableFuture appendToStream(final StreamId streamId, final long expectedVersion, + final List toAppend) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -142,8 +142,8 @@ public Long get() { } @Override - public final CompletableFuture appendToStream(final StreamId streamId, final long expectedVersion, - final CommonEvent... events) { + public CompletableFuture appendToStream(final StreamId streamId, final long expectedVersion, + final CommonEvent... events) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -155,8 +155,8 @@ public Long get() { } @Override - public final CompletableFuture appendToStream(final StreamId streamId, - final List toAppend) { + public CompletableFuture appendToStream(final StreamId streamId, + final List toAppend) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -168,8 +168,8 @@ public Long get() { } @Override - public final CompletableFuture appendToStream(final StreamId streamId, - final CommonEvent... events) { + public CompletableFuture appendToStream(final StreamId streamId, + final CommonEvent... events) { return CompletableFuture.supplyAsync(new Supplier() { @Override @@ -181,7 +181,7 @@ public Long get() { } @Override - public final CompletableFuture streamExists(final StreamId streamId) { + public CompletableFuture streamExists(final StreamId streamId) { return CompletableFuture.supplyAsync(new Supplier() { @Override public Boolean get() { @@ -191,7 +191,7 @@ public Boolean get() { } @Override - public final CompletableFuture streamState(final StreamId streamId) { + public CompletableFuture streamState(final StreamId streamId) { return CompletableFuture.supplyAsync(new Supplier() { @Override public StreamState get() { @@ -201,7 +201,7 @@ public StreamState get() { } @Override - public final boolean isSupportsCreateStream() { + public boolean isSupportsCreateStream() { return delegate.isSupportsCreateStream(); } diff --git a/api/src/main/java/org/fuin/esc/api/Deserializer.java b/api/src/main/java/org/fuin/esc/api/Deserializer.java index d9cd9eee..3f1050ec 100644 --- a/api/src/main/java/org/fuin/esc/api/Deserializer.java +++ b/api/src/main/java/org/fuin/esc/api/Deserializer.java @@ -1,23 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; -import org.fuin.esc.api.SerializedDataType; +import jakarta.validation.constraints.NotNull; /** * Serializes an object. @@ -26,7 +26,7 @@ public interface Deserializer { /** * Converts the given data into an object. - * + * * @param data * Serialized object. Can have different types like byte[], Node * (XML), JsonArray or JsonObject. The possible input depends on the @@ -35,12 +35,12 @@ public interface Deserializer { * Unique name of the data type. * @param mimeType * Type of the data in the byte array. - * + * * @return Deserialized object. - * + * * @param * Type the data is converted into. */ - public T unmarshal(Object data, SerializedDataType dataType, EnhancedMimeType mimeType); + T unmarshal(@NotNull Object data, @NotNull SerializedDataType dataType, @NotNull EnhancedMimeType mimeType); } diff --git a/api/src/main/java/org/fuin/esc/api/DeserializerRegistry.java b/api/src/main/java/org/fuin/esc/api/DeserializerRegistry.java index 119e3810..bfdc5022 100644 --- a/api/src/main/java/org/fuin/esc/api/DeserializerRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/DeserializerRegistry.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -27,65 +27,65 @@ public interface DeserializerRegistry { /** * Tries to find a deserializer for the given combination. - * + * * @param type * Unique identifier for the type of data. * @param mimeType * Mime type. - * + * * @return Deserializer instance configured with the arguments or throws an * {@link IllegalArgumentException} if no deserializer was found for the type. */ @NotNull - public Deserializer getDeserializer(@NotNull SerializedDataType type, @NotNull EnhancedMimeType mimeType); + Deserializer getDeserializer(@NotNull SerializedDataType type, @NotNull EnhancedMimeType mimeType); /** * Tries to find a deserializer for the given type using the * {@link #getDefaultContentType(SerializedDataType)}. This method fails if the default mime type is not * set. - * + * * @param type * Unique identifier for the type of data. - * + * * @return Deserializer instance configured with the arguments oor throws an * {@link IllegalArgumentException} if no deserializer was found for the type. */ @NotNull - public Deserializer getDeserializer(@NotNull SerializedDataType type); + Deserializer getDeserializer(@NotNull SerializedDataType type); /** * Returns the default mime type for the given type. - * + * * @param type * Unique identifier for the type of data. - * + * * @return Default mime type or NULL if nothing was configured for the given type. */ @Nullable - public EnhancedMimeType getDefaultContentType(@NotNull SerializedDataType type); + EnhancedMimeType getDefaultContentType(@NotNull SerializedDataType type); /** * Tries to find a deserializer for the given type using the * {@link #getDefaultContentType(SerializedDataType)}. This method fails if the default mime type is not * set. - * + * * @param type * Unique identifier for the type of data. - * + * * @return TRUE if a deserializer was found. */ - public boolean deserializerExists(@NotNull SerializedDataType type); + boolean deserializerExists(@NotNull SerializedDataType type); /** * Tries to find a deserializer for the given combination. - * + * * @param type * Unique identifier for the type of data. * @param mimeType * Mime type. - * + * * @return TRUE if a deserializer was found. */ - public boolean deserializerExists(@NotNull SerializedDataType type, @NotNull EnhancedMimeType mimeType); + boolean deserializerExists(@NotNull SerializedDataType type, @NotNull EnhancedMimeType mimeType); } diff --git a/api/src/main/java/org/fuin/esc/api/DeserializerRegistryRequired.java b/api/src/main/java/org/fuin/esc/api/DeserializerRegistryRequired.java index 1425f8ce..51e2a189 100644 --- a/api/src/main/java/org/fuin/esc/api/DeserializerRegistryRequired.java +++ b/api/src/main/java/org/fuin/esc/api/DeserializerRegistryRequired.java @@ -8,9 +8,9 @@ public interface DeserializerRegistryRequired { /** * Sets the registry to use. - * + * * @param registry Actual registry. */ - public void setRegistry(DeserializerRegistry registry); + void setRegistry(DeserializerRegistry registry); } diff --git a/api/src/main/java/org/fuin/esc/api/EnhancedMimeType.java b/api/src/main/java/org/fuin/esc/api/EnhancedMimeType.java index 98e6e8cc..979b487b 100644 --- a/api/src/main/java/org/fuin/esc/api/EnhancedMimeType.java +++ b/api/src/main/java/org/fuin/esc/api/EnhancedMimeType.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -48,10 +48,10 @@ public EnhancedMimeType() { /** * Constructor with all data. - * + * * @param str - * Contains base type, sub type and parameters. - * + * Contains base type, subtype and parameters. + * * @throws MimeTypeParseException * If the string is not valid. */ @@ -60,15 +60,15 @@ public EnhancedMimeType(@NotNull final String str) throws MimeTypeParseException } /** - * Constructor with primary and sub type (no parameters). - * + * Constructor with primary and subtype (no parameters). + * * @param primary * Primary type. * @param sub - * Sub type. - * + * Subtype. + * * @throws MimeTypeParseException - * If the primary type or sub type is not a valid token + * If the primary type or subtype is not a valid token */ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub) throws MimeTypeParseException { @@ -76,20 +76,20 @@ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub } /** - * Constructor with primary, sub type and encoding. - * + * Constructor with primary, subtype and encoding. + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. - * + * * @throws MimeTypeParseException - * If the primary type or sub type is not a valid token + * If the primary type or subtype is not a valid token */ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub, - @Nullable final Charset encoding) throws MimeTypeParseException { + @Nullable final Charset encoding) throws MimeTypeParseException { super(primary, sub); if (encoding != null) { super.setParameter(ENCODING, encoding.name()); @@ -97,45 +97,45 @@ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub } /** - * Constructor with primary, sub type, encoding and version. - * + * Constructor with primary, subtype, encoding and version. + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. * @param version * Version. - * + * * @throws MimeTypeParseException - * If the primary type or sub type is not a valid token + * If the primary type or subtype is not a valid token */ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub, - @Nullable final Charset encoding, @Nullable final String version) throws MimeTypeParseException { + @Nullable final Charset encoding, @Nullable final String version) throws MimeTypeParseException { this(primary, sub, encoding, version, null); } /** * Constructor with all data. - * + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. * @param version * Version. * @param params * Other parameters than version and encoding. - * + * * @throws MimeTypeParseException - * If the primary type or sub type is not a valid token + * If the primary type or subtype is not a valid token */ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub, - @Nullable final Charset encoding, @Nullable final String version, - @Nullable final Map params) throws MimeTypeParseException { + @Nullable final Charset encoding, @Nullable final String version, + @Nullable final Map params) throws MimeTypeParseException { super(primary, sub); if (encoding != null) { super.setParameter(ENCODING, encoding.name()); @@ -164,21 +164,21 @@ public EnhancedMimeType(@NotNull final String primary, @NotNull final String sub /** * Returns the version from the parameters. - * + * * @return Version or null if not available. */ @Nullable - public final String getVersion() { + public String getVersion() { return getParameter(VERSION); } /** * Returns the encoding from the parameters. - * + * * @return Encoding or null as default if not available. */ @Nullable - public final Charset getEncoding() { + public Charset getEncoding() { final String parameter = getParameter(ENCODING); if (parameter == null) { return null; @@ -188,42 +188,42 @@ public final Charset getEncoding() { /** * Returns the information if the base type is "application/json". - * + * * @return TRUE if it's JSON content, else FALSE: */ - public final boolean isJson() { + public boolean isJson() { return getBaseType().equals("application/json"); } /** * Returns the information if the base type is "application/xml". - * + * * @return TRUE if it's XML content, else FALSE: */ - public final boolean isXml() { + public boolean isXml() { return getBaseType().equals("application/xml"); } /** - * Determine if the primary, sub type and encoding of this object is the same as what is in the given + * Determine if the primary, subtype and encoding of this object is the same as what is in the given * type. - * + * * @param other * The MimeType object to compare with. - * + * * @return True if they match. */ - public final boolean matchEncoding(final EnhancedMimeType other) { + public boolean matchEncoding(final EnhancedMimeType other) { return match(other) && Objects.equals(getEncoding(), other.getEncoding()); } /** * Creates an instance with all data. Exceptions are wrapped to runtime exceptions. - * + * * @param str - * Contains base type, sub type, version and parameters. - * + * Contains base type, subtype, version and parameters. + * * @return New instance. */ @Nullable @@ -239,14 +239,14 @@ public static EnhancedMimeType create(@Nullable final String str) { } /** - * Creates an instance with primary and sub type (no version, no parameters). Exceptions are wrapped to + * Creates an instance with primary and subtype (no version, no parameters). Exceptions are wrapped to * runtime exceptions. - * + * * @param primary * Primary type. * @param sub - * Sub type. - * + * Subtype. + * * @return New instance. */ @NotNull @@ -255,64 +255,64 @@ public static EnhancedMimeType create(@NotNull final String primary, @NotNull fi } /** - * Creates an instance with primary, sub type and encoding (no version). Exceptions are wrapped to runtime + * Creates an instance with primary, subtype and encoding (no version). Exceptions are wrapped to runtime * exceptions. - * + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. - * + * * @return New instance. */ @NotNull public static EnhancedMimeType create(@NotNull final String primary, @NotNull final String sub, - final Charset encoding) { + final Charset encoding) { return create(primary, sub, encoding, null, null); } /** - * Creates an instance with primary, sub type, encoding and version. Exceptions are wrapped to runtime + * Creates an instance with primary, subtype, encoding and version. Exceptions are wrapped to runtime * exceptions. - * + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. * @param version * Version. - * + * * @return New instance. */ @NotNull public static EnhancedMimeType create(@NotNull final String primary, @NotNull final String sub, - final Charset encoding, final String version) { + final Charset encoding, final String version) { return create(primary, sub, encoding, version, new HashMap()); } /** * Creates an instance with all data and exceptions wrapped to runtime exceptions. - * + * * @param primary * Primary type. * @param sub - * Sub type. + * Subtype. * @param encoding * Encoding. * @param version * Version. * @param parameters * Additional parameters. - * + * * @return New instance. */ @NotNull public static EnhancedMimeType create(@NotNull final String primary, @NotNull final String sub, - final Charset encoding, final String version, final Map parameters) { + final Charset encoding, final String version, final Map parameters) { try { return new EnhancedMimeType(primary, sub, encoding, version, parameters); } catch (final MimeTypeParseException ex) { @@ -321,12 +321,12 @@ public static EnhancedMimeType create(@NotNull final String primary, @NotNull fi } @Override - public final int hashCode() { + public int hashCode() { return toString().hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } diff --git a/api/src/main/java/org/fuin/esc/api/EscApiUtils.java b/api/src/main/java/org/fuin/esc/api/EscApiUtils.java index 6fa7a0e5..921e49e1 100644 --- a/api/src/main/java/org/fuin/esc/api/EscApiUtils.java +++ b/api/src/main/java/org/fuin/esc/api/EscApiUtils.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,7 +24,7 @@ public final class EscApiUtils { /** * TODO Replace this with an enum. - * + * * Only events will be seen that are added after subscription was * established. */ diff --git a/api/src/main/java/org/fuin/esc/api/EventId.java b/api/src/main/java/org/fuin/esc/api/EventId.java index e9f5cef8..0bc929dd 100644 --- a/api/src/main/java/org/fuin/esc/api/EventId.java +++ b/api/src/main/java/org/fuin/esc/api/EventId.java @@ -1,46 +1,44 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; +import org.fuin.objects4j.common.ValueObjectWithBaseType; import org.fuin.objects4j.core.UUIDStr; import org.fuin.objects4j.core.UUIDStrValidator; -import org.fuin.objects4j.common.ValueObjectWithBaseType; +import javax.annotation.concurrent.Immutable; import java.io.Serializable; +import java.util.Objects; import java.util.UUID; /** - * Represents a unique event identifier. + * Represents a unique event identifier based on a UUID. */ @Immutable -@XmlJavaTypeAdapter(EventIdConverter.class) -public final class EventId implements ValueObjectWithBaseType, - Comparable, Serializable { +public final class EventId implements ValueObjectWithBaseType, Comparable, Serializable { private static final long serialVersionUID = 1000L; - private long mostSigBits; + private final long mostSigBits; - private long leastSigBits; + private final long leastSigBits; // Do not access this variable directly inside this class. // Use asBaseType() to be sure this is initialized. @@ -59,7 +57,7 @@ public EventId() { /** * Creates a new event ID using the given string. - * + * * @param value * String that represents a UUID. */ @@ -69,7 +67,7 @@ public EventId(@NotNull @UUIDStr final String value) { /** * Creates a new event ID using the given value. - * + * * @param value * UUID to use. */ @@ -82,12 +80,12 @@ public EventId(@NotNull final UUID value) { } @Override - public final Class getBaseType() { + public Class getBaseType() { return UUID.class; } @Override - public final UUID asBaseType() { + public UUID asBaseType() { if (uuid == null) { uuid = new UUID(mostSigBits, leastSigBits); } @@ -95,7 +93,7 @@ public final UUID asBaseType() { } @Override - public final String toString() { + public String toString() { if (str == null) { str = uuid.toString(); } @@ -103,27 +101,20 @@ public final String toString() { } @Override - public final int hashCode() { - return asBaseType().hashCode(); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final EventId eventId = (EventId) o; + return mostSigBits == eventId.mostSigBits && leastSigBits == eventId.leastSigBits; } @Override - public final boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof EventId)) { - return false; - } - final EventId other = (EventId) obj; - return asBaseType().equals(other.asBaseType()); + public int hashCode() { + return Objects.hash(mostSigBits, leastSigBits); } @Override - public final int compareTo(final EventId other) { + public int compareTo(final EventId other) { return asBaseType().compareTo(other.asBaseType()); } diff --git a/api/src/main/java/org/fuin/esc/api/EventNotFoundException.java b/api/src/main/java/org/fuin/esc/api/EventNotFoundException.java index 887e4f64..bea66681 100644 --- a/api/src/main/java/org/fuin/esc/api/EventNotFoundException.java +++ b/api/src/main/java/org/fuin/esc/api/EventNotFoundException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,8 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Signals that an event with the given number was not found. @@ -35,14 +36,14 @@ public final class EventNotFoundException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique identifier of the stream. * @param eventNumber * Number of the event that was not found. */ public EventNotFoundException(@NotNull final StreamId streamId, - final long eventNumber) { + final long eventNumber) { super("Version " + eventNumber + " does not exist on stream '" + streamId + "'"); @@ -54,20 +55,20 @@ public EventNotFoundException(@NotNull final StreamId streamId, /** * Returns the unique ID of the stream. - * + * * @return Stream with version that was not found. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } /** * Returns the number of the event. - * + * * @return Number that was not found. */ - public final long getVersion() { + public long getVersion() { return version; } diff --git a/api/src/main/java/org/fuin/esc/api/EventStore.java b/api/src/main/java/org/fuin/esc/api/EventStore.java index f86ce4c5..b2ecb368 100644 --- a/api/src/main/java/org/fuin/esc/api/EventStore.java +++ b/api/src/main/java/org/fuin/esc/api/EventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/main/java/org/fuin/esc/api/EventStoreAsync.java b/api/src/main/java/org/fuin/esc/api/EventStoreAsync.java index 2f87c1b6..a219519c 100644 --- a/api/src/main/java/org/fuin/esc/api/EventStoreAsync.java +++ b/api/src/main/java/org/fuin/esc/api/EventStoreAsync.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/main/java/org/fuin/esc/api/EventStoreBasics.java b/api/src/main/java/org/fuin/esc/api/EventStoreBasics.java index 4773b633..2513137c 100644 --- a/api/src/main/java/org/fuin/esc/api/EventStoreBasics.java +++ b/api/src/main/java/org/fuin/esc/api/EventStoreBasics.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -25,15 +25,15 @@ public interface EventStoreBasics extends AutoCloseable { /** * Opens a connection to the event store. Opening an already opened event * store is ignored. - * + * * @return This event store. */ - public EventStoreBasics open(); + EventStoreBasics open(); /** * Closes the connection to the event store. Closing an already closed or * never opened event store is simply ignored. */ - public void close(); + void close(); } diff --git a/api/src/main/java/org/fuin/esc/api/EventStoreBasicsAsync.java b/api/src/main/java/org/fuin/esc/api/EventStoreBasicsAsync.java index d9fe904a..e6095e4e 100644 --- a/api/src/main/java/org/fuin/esc/api/EventStoreBasicsAsync.java +++ b/api/src/main/java/org/fuin/esc/api/EventStoreBasicsAsync.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,16 +28,16 @@ public interface EventStoreBasicsAsync extends AutoCloseable { /** * Opens a connection to the event store. - * + * * @return Nothing. */ @NotNull - public CompletableFuture open(); + CompletableFuture open(); /** * Closes the connection to the event store. Closing an already closed or * never opened event store is simply ignored. */ - public void close(); - + void close(); + } diff --git a/api/src/main/java/org/fuin/esc/api/ExpectedVersion.java b/api/src/main/java/org/fuin/esc/api/ExpectedVersion.java index ae02e02a..f83279f4 100644 --- a/api/src/main/java/org/fuin/esc/api/ExpectedVersion.java +++ b/api/src/main/java/org/fuin/esc/api/ExpectedVersion.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,15 +31,15 @@ public enum ExpectedVersion { /** This specifies the expectation that target stream does not yet exist or is empty. */ NO_OR_EMPTY_STREAM(-1); - private long no; + private final long no; - private ExpectedVersion(final long no) { + ExpectedVersion(final long no) { this.no = no; } /** * Returns the value for the enum. - * + * * @return Version value. */ public final long getNo() { @@ -48,10 +48,10 @@ public final long getNo() { /** * Determines if the given name is a valid one. - * + * * @param name * Name to test. - * + * * @return TRUE if the name is valid, else FALSE. */ public static boolean valid(@Nullable final String name) { @@ -68,11 +68,11 @@ public static boolean valid(@Nullable final String name) { /** * Returns the value of the given constant or if it cannot be found the string converted to an int. - * + * * @param name * Name of a constant or a valid Integer value. If the argument is null the enum * {@link #ANY} will be returned. - * + * * @return Value. */ public static long no(@Nullable final String name) { diff --git a/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstant.java b/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstant.java index 6a4d1820..f0231099 100644 --- a/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstant.java +++ b/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstant.java @@ -3,7 +3,12 @@ import jakarta.validation.Constraint; import jakarta.validation.Payload; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * A class that has a public static constant of type {@link SerializedDataType}. @@ -13,7 +18,7 @@ @Target(ElementType.TYPE) @Inherited @Retention(RetentionPolicy.RUNTIME) -@Constraint(validatedBy = { HasSerializedDataTypeConstantValidator.class }) +@Constraint(validatedBy = {HasSerializedDataTypeConstantValidator.class}) public @interface HasSerializedDataTypeConstant { /** diff --git a/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstantValidator.java b/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstantValidator.java index c050aa18..d67886e8 100644 --- a/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstantValidator.java +++ b/api/src/main/java/org/fuin/esc/api/HasSerializedDataTypeConstantValidator.java @@ -4,13 +4,12 @@ import jakarta.validation.ConstraintValidatorContext; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Determines if the annotated class has a public static constant with the given name and {@link SerializedDataType} type. */ -public class HasSerializedDataTypeConstantValidator implements ConstraintValidator { +public final class HasSerializedDataTypeConstantValidator implements ConstraintValidator { private String name; @@ -66,7 +65,7 @@ private record Result(String message, Object value) { * Returns a constant of type {@link SerializedDataType} in a class. Throws an {@link IllegalArgumentException} * in case there is a problem with the field. * - * @param clasz Class to inspect. + * @param clasz Class to inspect. * @param fieldName Name of the public static field of type {@link SerializedDataType}. * @return Value of the constant. */ diff --git a/api/src/main/java/org/fuin/esc/api/IBase64Data.java b/api/src/main/java/org/fuin/esc/api/IBase64Data.java new file mode 100644 index 00000000..b0aa722a --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IBase64Data.java @@ -0,0 +1,54 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.api; + +/** + * Contains some Base64 encoded data. + */ +public interface IBase64Data extends IBaseType { + + /** + * Unique XML/JSON root element name of the type. + */ + String EL_ROOT_NAME = "Base64"; + + /** + * Unique name of the type. + */ + TypeName TYPE = new TypeName(EL_ROOT_NAME); + + /** + * Unique name of the serialized type. + */ + SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + /** + * Returns the Base64 encoded data. + * + * @return Base64 string. + */ + String getEncoded(); + + /** + * Returns the decoded data. + * + * @return Binary data. + */ + byte[] getDecoded(); + +} diff --git a/api/src/main/java/org/fuin/esc/api/IBaseType.java b/api/src/main/java/org/fuin/esc/api/IBaseType.java new file mode 100644 index 00000000..9a8467e5 --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IBaseType.java @@ -0,0 +1,7 @@ +package org.fuin.esc.api; + +/** + * Tag interface for common base types. + */ +public interface IBaseType { +} diff --git a/api/src/main/java/org/fuin/esc/api/IBaseTypeFactory.java b/api/src/main/java/org/fuin/esc/api/IBaseTypeFactory.java new file mode 100644 index 00000000..e1433f53 --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IBaseTypeFactory.java @@ -0,0 +1,34 @@ +package org.fuin.esc.api; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; + +/** + * Creates the bases types that are only known as interfaces in this module. + */ +public interface IBaseTypeFactory { + + /** + * Constructor with binary data that will be Base64 encoded. + * + * @param binaryData Binary data. + */ + IBase64Data createBase64Data(@NotNull byte[] binaryData); + + + /** + * Constructor with all data. + * + * @param dataType Type of the data. + * @param dataContentType Type of the data. + * @param metaType Unique name of the meta data type if available. + * @param metaContentType Type of the meta data if meta data is available. + * @param meta Meta data object if available. + */ + IEscMeta createEscMeta(@NotNull final String dataType, + @NotNull final EnhancedMimeType dataContentType, + @Nullable final String metaType, + @Nullable final EnhancedMimeType metaContentType, + @Nullable final Object meta); + +} diff --git a/api/src/main/java/org/fuin/esc/api/IData.java b/api/src/main/java/org/fuin/esc/api/IData.java new file mode 100644 index 00000000..96455f8a --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IData.java @@ -0,0 +1,71 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.api; + +import jakarta.validation.constraints.NotNull; +import org.fuin.objects4j.common.ValueObject; + +import java.io.Serializable; + +/** + * Helper class that allows sending the data of an event as XML directly to the + * event store. Represents a block of data in a serialized form. This class + * might be useful for tests. It's not used in the 'esc-spi' code itself + */ +public interface IData extends IBaseType, ValueObject, Serializable { + + /** + * Unique XML/JSON root element name of the type. + */ + String EL_ROOT_NAME = "data"; + + /** + * XML/JSON name of the {@link #getType()} field. + */ + String EL_TYPE = "type"; + + /** + * XML/JSON name of the {@link #getMimeType()} field. + */ + String EL_MIME_TYPE = "mime-type"; + + /** + * Returns the unique identifier for the type of data. + * + * @return Unique and never changing type name. + */ + @NotNull + String getType(); + + /** + * Returns the Internet Media Type that classifies the data. + * + * @return Mime type. + */ + @NotNull + EnhancedMimeType getMimeType(); + + /** + * Returns the raw data block. + * + * @return Raw data. + */ + @NotNull + String getContent(); + +} diff --git a/api/src/main/java/org/fuin/esc/api/ToJsonCapable.java b/api/src/main/java/org/fuin/esc/api/IDataWrapper.java similarity index 69% rename from api/src/main/java/org/fuin/esc/api/ToJsonCapable.java rename to api/src/main/java/org/fuin/esc/api/IDataWrapper.java index bf49d4a7..92d520b6 100644 --- a/api/src/main/java/org/fuin/esc/api/ToJsonCapable.java +++ b/api/src/main/java/org/fuin/esc/api/IDataWrapper.java @@ -1,36 +1,38 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; -import jakarta.json.JsonStructure; import jakarta.validation.constraints.NotNull; /** - * Marks an object that can be converted into a JSON object or array. + * A structure that wraps another object of different types. */ -public interface ToJsonCapable { +public interface IDataWrapper extends IBaseType { + + /** Unique name of the type. */ + String EL_ROOT = "Wrapper"; /** - * Returns the instance as JSON structure. - * - * @return JSON representation of the instance. + * Returns the wrapped object. + * + * @return Inner object. */ @NotNull - public JsonStructure toJson(); + Object getObj(); } diff --git a/api/src/main/java/org/fuin/esc/api/IEscEvent.java b/api/src/main/java/org/fuin/esc/api/IEscEvent.java new file mode 100644 index 00000000..2492478f --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IEscEvent.java @@ -0,0 +1,75 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.api; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; + +/** + * An event structure. + */ +public interface IEscEvent extends IBaseType { + + /** Unique XML/JSON root element name of the type. */ + String EL_ROOT_NAME = "Event"; + + /** XML/JSON name of the {@link #getEventId()} field. */ + String EL_EVENT_ID = "EventId"; + + /** XML/JSON name of the {@link #getEventType()} field. */ + String EL_EVENT_TYPE = "EventType"; + + /** XML/JSON name of the {@link #getData()} field. */ + String EL_DATA = "Data"; + + /** XML/JSON name of the {@link #getMeta()} field. */ + String EL_META_DATA = "MetaData"; + + /** + * Returns the unique event identifier. + * + * @return Event ID. + */ + @NotNull + String getEventId(); + + /** + * Returns the unique type name of the event. + * + * @return Event type. + */ + @NotNull + String getEventType(); + + /** + * Returns the data. + * + * @return Data. + */ + @NotNull + IDataWrapper getData(); + + /** + * Returns the metadata. + * + * @return Metadata. + */ + @Nullable + IDataWrapper getMeta(); + +} diff --git a/api/src/main/java/org/fuin/esc/api/IEscEvents.java b/api/src/main/java/org/fuin/esc/api/IEscEvents.java new file mode 100644 index 00000000..a38bb708 --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IEscEvents.java @@ -0,0 +1,44 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.api; + +import java.util.List; + +/** + * A list of events. + */ +public interface IEscEvents extends IBaseType { + + /** + * Unique root element name of the type. + */ + String EL_ROOT_NAME = "Events"; + + /** + * XML/JSON name of the elements in the list. + */ + String EL_EVENT = "Event"; + + /** + * Returns an immutable event list. + * + * @return Unmodifiable list of events. + */ + List getList(); + +} diff --git a/api/src/main/java/org/fuin/esc/api/IEscMeta.java b/api/src/main/java/org/fuin/esc/api/IEscMeta.java new file mode 100644 index 00000000..c10e5ae7 --- /dev/null +++ b/api/src/main/java/org/fuin/esc/api/IEscMeta.java @@ -0,0 +1,89 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.api; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; + +/** + * A structure that contains the user's metadata and the system's meta information. + */ +public interface IEscMeta extends IBaseType { + + /** Unique name of the type. */ + TypeName TYPE = new TypeName("EscMeta"); + + /** Unique name of the serialized type. */ + SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + /** Unique XML/JSON root element name of the type. */ + String EL_ROOT_NAME = "esc-meta"; + + /** XML/JSON tag name of the {@link #getDataType()}. */ + String EL_DATA_TYPE = "data-type"; + + /** XML/JSON tag name of the {@link #getDataContentType()}. */ + String EL_DATA_CONTENT_TYPE = "data-content-type"; + + /** XML/JSON tag name of the {@link #getMetaType()}. */ + String EL_META_TYPE = "meta-type"; + + /** XML/JSON tag name of the {@link #getMetaContentType()}. */ + String EL_META_CONTENT_TYPE = "meta-content-type"; + + /** + * Returns the unique name of the data type. + * + * @return Data type. + */ + @NotNull + String getDataType(); + + /** + * Returns the type of the data. + * + * @return Data type. + */ + @NotNull + EnhancedMimeType getDataContentType(); + + /** + * Returns the unique name of the metadata type if available. + * + * @return Metadata type. + */ + @Nullable + String getMetaType(); + + /** + * Returns the type of the metadata if metadata is available. + * + * @return Meta type. + */ + @Nullable + EnhancedMimeType getMetaContentType(); + + /** + * Returns the metadata object. + * + * @return Metadata object. + */ + @NotNull + Object getMeta(); + +} diff --git a/api/src/main/java/org/fuin/esc/api/JsonDeSerializer.java b/api/src/main/java/org/fuin/esc/api/JsonDeSerializer.java deleted file mode 100644 index 8fe91653..00000000 --- a/api/src/main/java/org/fuin/esc/api/JsonDeSerializer.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.api; - -import jakarta.json.Json; -import jakarta.json.JsonReader; -import jakarta.json.JsonStructure; -import jakarta.json.JsonWriter; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.SerDeserializer; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.ToJsonCapable; - -import java.io.*; -import java.nio.charset.Charset; - -/** - * Serializes and deserializes a JSON object. The content type for serialization is always "application/json". - * This implementation supports {@link JsonStructure} and byte[] for unmarshalling content. Type - * {@link JsonStructure} will simply return the input without any change. - */ -public final class JsonDeSerializer implements SerDeserializer { - - private final EnhancedMimeType mimeType; - - /** - * Constructor with UTF-8 encoding. - */ - public JsonDeSerializer() { - this(Charset.forName("utf-8")); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public JsonDeSerializer(final Charset encoding) { - super(); - this.mimeType = EnhancedMimeType.create("application", "json", encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return mimeType; - } - - @Override - public final byte[] marshal(final Object obj, final SerializedDataType type) { - - final JsonStructure struct; - if (obj instanceof ToJsonCapable) { - struct = ((ToJsonCapable) obj).toJson(); - } else if (obj instanceof JsonStructure) { - struct = (JsonStructure) obj; - } else { - throw new IllegalArgumentException("Can only handle instances of type '" - + ToJsonCapable.class.getSimpleName() + "' or '" + JsonStructure.class.getSimpleName() - + "', but not: " + obj.getClass()); - } - - final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - final Writer writer = new OutputStreamWriter(bos, mimeType.getEncoding()); - final JsonWriter jsonWriter = Json.createWriter(writer); - try { - jsonWriter.write(struct); - } finally { - jsonWriter.close(); - } - return bos.toByteArray(); - } - - @SuppressWarnings("unchecked") - @Override - public final T unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - - if (data instanceof byte[]) { - final Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) data), - mimeType.getEncoding()); - final JsonReader jsonReader = Json.createReader(reader); - try { - return (T) jsonReader.read(); - } finally { - jsonReader.close(); - } - } - if (data instanceof JsonStructure) { - // Simply return it - return (T) data; - } - throw new IllegalArgumentException("This deserializer only supports input of type '" - + JsonStructure.class.getName() + "' and 'byte[]', but was: " + data); - - } - -} diff --git a/api/src/main/java/org/fuin/esc/api/ProjectionAdminEventStore.java b/api/src/main/java/org/fuin/esc/api/ProjectionAdminEventStore.java index 7645c6d2..5953062b 100644 --- a/api/src/main/java/org/fuin/esc/api/ProjectionAdminEventStore.java +++ b/api/src/main/java/org/fuin/esc/api/ProjectionAdminEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,55 +28,55 @@ public interface ProjectionAdminEventStore extends AutoCloseable { /** * Opens a connection to the event store. - * + * * @return Event store instance. */ - public ProjectionAdminEventStore open(); + ProjectionAdminEventStore open(); /** * Closes the connection to the event store. */ - public void close(); - + void close(); + /** * Determines if a projection exists. - * + * * @param projectionId * Unique identifier of the projection. - * + * * @return TRUE if the projection exists, else FALSE. */ - public boolean projectionExists(@NotNull StreamId projectionId); + boolean projectionExists(@NotNull StreamId projectionId); /** * Enables an existing projection. If the projection is already enabled, the * command is ignored. - * + * * @param projectionId * Unique projection identifier. - * + * * @throws StreamNotFoundException * The given projection could not be enabled because it does not * exist. */ - public void enableProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; + void enableProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; /** * Disables an existing projection. If the projection is already disabled, * the command is ignored. - * + * * @param projectionId * Unique projection identifier. - * + * * @throws StreamNotFoundException * The given projection could not be disabled because it does * not exist. */ - public void disableProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; + void disableProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; /** * Creates a new projection that selects an array of events by their type. - * + * * @param projectionId * Unique name of the projection to create. * @param enable @@ -84,17 +84,17 @@ public interface ProjectionAdminEventStore extends AutoCloseable { * (false). * @param eventType * Unique type names of events to select. - * + * * @throws StreamAlreadyExistsException * The given projection could not be created because it already * exists. */ - public void createProjection(@NotNull StreamId projectionId, boolean enable, - @NotNull TypeName... eventType) throws StreamAlreadyExistsException; + void createProjection(@NotNull StreamId projectionId, boolean enable, + @NotNull TypeName... eventType) throws StreamAlreadyExistsException; /** * Creates a new projection that selects a list of events by their type. - * + * * @param projectionId * Unique name of the projection to create. * @param enable @@ -102,24 +102,24 @@ public void createProjection(@NotNull StreamId projectionId, boolean enable, * (false). * @param eventTypes * Unique type names of events to select. - * + * * @throws StreamAlreadyExistsException * The given projection could not be created because it already * exists. */ - public void createProjection(@NotNull StreamId projectionId, boolean enable, - @NotNull List eventTypes) throws StreamAlreadyExistsException; + void createProjection(@NotNull StreamId projectionId, boolean enable, + @NotNull List eventTypes) throws StreamAlreadyExistsException; /** * Deletes an existing projection. - * + * * @param projectionId * Projection to delete. - * + * * @throws StreamNotFoundException * The given projection could not be deleted because it does not * exist. */ - public void deleteProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; + void deleteProjection(@NotNull StreamId projectionId) throws StreamNotFoundException; } diff --git a/api/src/main/java/org/fuin/esc/api/ProjectionStreamId.java b/api/src/main/java/org/fuin/esc/api/ProjectionStreamId.java index 97e6c923..b8642ea0 100644 --- a/api/src/main/java/org/fuin/esc/api/ProjectionStreamId.java +++ b/api/src/main/java/org/fuin/esc/api/ProjectionStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,9 +19,9 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.KeyValue; +import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; @@ -37,7 +37,7 @@ public final class ProjectionStreamId implements StreamId { /** * Constructor for projection. - * + * * @param name * Unique name. */ @@ -47,37 +47,37 @@ public ProjectionStreamId(@NotNull final String name) { } @Override - public final String getName() { + public String getName() { return name; } @Override - public final boolean isProjection() { + public boolean isProjection() { return true; } @Override - public final T getSingleParamValue() { + public T getSingleParamValue() { throw new UnsupportedOperationException(getClass().getSimpleName() + " has no parameters"); } @Override - public final List getParameters() { + public List getParameters() { return Collections.emptyList(); } @Override - public final String asString() { + public String asString() { return name; } @Override - public final int hashCode() { + public int hashCode() { return name.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -92,7 +92,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return name; } diff --git a/api/src/main/java/org/fuin/esc/api/ReadableEventStore.java b/api/src/main/java/org/fuin/esc/api/ReadableEventStore.java index b0503a47..7b9d93cb 100644 --- a/api/src/main/java/org/fuin/esc/api/ReadableEventStore.java +++ b/api/src/main/java/org/fuin/esc/api/ReadableEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,17 +28,17 @@ public interface ReadableEventStore extends EventStoreBasics { /** * Reads count Events from an Event Stream forwards (e.g. oldest to newest) * starting from position start. traing to read from a non-open - * + * * @param streamId * The stream to read from. * @param start * The starting point to read from. * @param count * The count of items to read. - * + * * @return A slice containing the results of the read operation. Never * null, but may be an empty list. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -47,23 +47,23 @@ public interface ReadableEventStore extends EventStoreBasics { * deleted. */ @NotNull - public StreamEventsSlice readEventsForward(@NotNull StreamId streamId, - long start, int count); + StreamEventsSlice readEventsForward(@NotNull StreamId streamId, + long start, int count); /** * Reads count Events from an Event Stream backwards (e.g. newest to oldest) * starting from position start. - * + * * @param streamId * The stream to read from. * @param start * The starting point to read from. * @param count * The count of items to read. - * + * * @return A slice containing the results of the read operation. Never * null, but may be an empty list. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -72,19 +72,19 @@ public StreamEventsSlice readEventsForward(@NotNull StreamId streamId, * deleted. */ @NotNull - public StreamEventsSlice readEventsBackward(@NotNull StreamId streamId, - long start, int count); + StreamEventsSlice readEventsBackward(@NotNull StreamId streamId, + long start, int count); /** * Reads a single event from a stream. - * + * * @param streamId * The stream to read from. * @param eventNumber * The event number to read. - * + * * @return A result containing the results of the read operation. - * + * * @throws EventNotFoundException * An event with the given number was not found in the stream. * @throws StreamNotFoundException @@ -95,32 +95,32 @@ public StreamEventsSlice readEventsBackward(@NotNull StreamId streamId, * deleted. */ @NotNull - public CommonEvent readEvent(@NotNull StreamId streamId, long eventNumber); + CommonEvent readEvent(@NotNull StreamId streamId, long eventNumber); /** * Determines if a stream exists. - * + * * @param streamId * Unique identifier of the stream. - * + * * @return TRUE if the stream exists, else FALSE. */ - public boolean streamExists(@NotNull StreamId streamId); + boolean streamExists(@NotNull StreamId streamId); /** * Returns the state of the stream. - * + * * @param streamId * Unique identifier of the stream. - * + * * @return State. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. */ @NotNull - public StreamState streamState(@NotNull StreamId streamId); + StreamState streamState(@NotNull StreamId streamId); /** * Reads all events until the end of the stream. A stream that does not @@ -130,7 +130,7 @@ public StreamEventsSlice readEventsBackward(@NotNull StreamId streamId, * application exceptions using the "ejb-jar.xml" (If you don't know what * this is, just google for "ejb-jar.xml assembly-descriptor * application-exception"). - * + * * @param streamId * Unique identifier of the stream. * @param startingAtEventNumber @@ -139,27 +139,27 @@ public StreamEventsSlice readEventsBackward(@NotNull StreamId streamId, * Number of events to read in a single operation. * @param handler * Handler to pass a read chunk to. - * + * * @throws StreamDeletedException * A stream with the given name previously existed but was * deleted. */ - public void readAllEventsForward(StreamId streamId, - long startingAtEventNumber, int chunkSize, - ChunkEventHandler handler); + void readAllEventsForward(StreamId streamId, + long startingAtEventNumber, int chunkSize, + ChunkEventHandler handler); /** * Handles a number of events. */ - public interface ChunkEventHandler { + interface ChunkEventHandler { /** * List of events to handle. - * + * * @param currentSlice * Slice with events to handle. */ - public void handle(StreamEventsSlice currentSlice); + void handle(StreamEventsSlice currentSlice); } diff --git a/api/src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java b/api/src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java index 6fe59e32..dbabd88a 100644 --- a/api/src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java +++ b/api/src/main/java/org/fuin/esc/api/ReadableEventStoreAsync.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -30,17 +30,17 @@ public interface ReadableEventStoreAsync extends EventStoreBasicsAsync { /** * Reads count Events from an Event Stream forwards (e.g. oldest to newest) * starting from position start. - * + * * @param streamId * The stream to read from. * @param start * The starting point to read from. * @param count * The count of items to read. - * + * * @return A slice containing the results of the read operation. Never * null, but may be an empty list. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -49,23 +49,23 @@ public interface ReadableEventStoreAsync extends EventStoreBasicsAsync { * deleted. */ @NotNull - public CompletableFuture readEventsForward(@NotNull StreamId streamId, long start, - int count); + CompletableFuture readEventsForward(@NotNull StreamId streamId, long start, + int count); /** * Reads count Events from an Event Stream backwards (e.g. newest to oldest) * starting from position start. - * + * * @param streamId * The stream to read from. * @param start * The starting point to read from. * @param count * The count of items to read. - * + * * @return A slice containing the results of the read operation. Never * null, but may be an empty list. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -74,19 +74,19 @@ public CompletableFuture readEventsForward(@NotNull StreamId * deleted. */ @NotNull - public CompletableFuture readEventsBackward(@NotNull StreamId streamId, long start, - int count); + CompletableFuture readEventsBackward(@NotNull StreamId streamId, long start, + int count); /** * Reads a single event from a stream. - * + * * @param streamId * The stream to read from. * @param eventNumber * The event number to read. - * + * * @return A result containing the results of the read operation. - * + * * @throws EventNotFoundException * An event with the given number was not found in the stream. * @throws StreamNotFoundException @@ -97,32 +97,32 @@ public CompletableFuture readEventsBackward(@NotNull StreamId * deleted. */ @NotNull - public CompletableFuture readEvent(@NotNull StreamId streamId, long eventNumber); + CompletableFuture readEvent(@NotNull StreamId streamId, long eventNumber); /** * Determines if a stream exists. - * + * * @param streamId * Unique identifier of the stream. - * + * * @return TRUE if the stream exists, else FALSE. */ @NotNull - public CompletableFuture streamExists(@NotNull StreamId streamId); + CompletableFuture streamExists(@NotNull StreamId streamId); /** * Returns the state of the stream. - * + * * @param streamId * Unique identifier of the stream. - * + * * @return State. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. */ @NotNull - public CompletableFuture streamState(@NotNull StreamId streamId); + CompletableFuture streamState(@NotNull StreamId streamId); } diff --git a/api/src/main/java/org/fuin/esc/api/SerDeserializer.java b/api/src/main/java/org/fuin/esc/api/SerDeserializer.java index 688356bc..fb2a53c7 100644 --- a/api/src/main/java/org/fuin/esc/api/SerDeserializer.java +++ b/api/src/main/java/org/fuin/esc/api/SerDeserializer.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/main/java/org/fuin/esc/api/SerDeserializerRegistry.java b/api/src/main/java/org/fuin/esc/api/SerDeserializerRegistry.java index b84326e8..d73614e9 100644 --- a/api/src/main/java/org/fuin/esc/api/SerDeserializerRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/SerDeserializerRegistry.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/main/java/org/fuin/esc/api/SerializedDataType.java b/api/src/main/java/org/fuin/esc/api/SerializedDataType.java index ac2a2b60..788b6ce1 100644 --- a/api/src/main/java/org/fuin/esc/api/SerializedDataType.java +++ b/api/src/main/java/org/fuin/esc/api/SerializedDataType.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -20,9 +20,10 @@ import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.AbstractStringValueObject; +import javax.annotation.concurrent.Immutable; + /** * Uniquely identifies a type of serialized data. */ @@ -43,7 +44,7 @@ protected SerializedDataType() { //NOSONAR Ignore uninitialized fields /** * Constructor with unique type name. - * + * * @param value * Type name. */ @@ -54,12 +55,12 @@ public SerializedDataType(@NotEmpty final String value) { } @Override - public final String asBaseType() { + public String asBaseType() { return value; } @Override - public final String toString() { + public String toString() { return asBaseType(); } diff --git a/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistry.java b/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistry.java index c1fbc7d9..64124c41 100644 --- a/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistry.java @@ -1,24 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.SerializedDataType; /** * Locates a class for a given type. @@ -27,13 +26,13 @@ public interface SerializedDataTypeRegistry { /** * Tries to find a class for the given type. - * + * * @param type * Unique identifier for the type of data. - * + * * @return Class or throws a {@link IllegalArgumentException} if no class was found for that type. */ @NotNull - public Class findClass(@NotNull SerializedDataType type); - + Class findClass(@NotNull SerializedDataType type); + } diff --git a/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistryRequired.java b/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistryRequired.java index ae0af4ed..79ac0685 100644 --- a/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistryRequired.java +++ b/api/src/main/java/org/fuin/esc/api/SerializedDataTypeRegistryRequired.java @@ -8,10 +8,9 @@ public interface SerializedDataTypeRegistryRequired { /** * Sets the registry to use. - * - * @param registry - * Actual registry. + * + * @param registry Actual registry. */ - public void setRegistry(SerializedDataTypeRegistry registry); + void setRegistry(SerializedDataTypeRegistry registry); } diff --git a/api/src/main/java/org/fuin/esc/api/Serializer.java b/api/src/main/java/org/fuin/esc/api/Serializer.java index 585c9b23..296b731e 100644 --- a/api/src/main/java/org/fuin/esc/api/Serializer.java +++ b/api/src/main/java/org/fuin/esc/api/Serializer.java @@ -1,24 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.SerializedDataType; /** * Serializes an object. @@ -27,25 +26,25 @@ public interface Serializer { /** * Returns the mime type used to serialize the object. - * + * * @return Content type information. */ - public EnhancedMimeType getMimeType(); + @NotNull + EnhancedMimeType getMimeType(); /** * Converts the given object into a byte representation. - * + * * @param obj * Object to serialize. * @param type * Type of event. - * + * * @return Serialized object. - * + * * @param * Type the data is converted into. */ - @NotNull - public byte[] marshal(@NotNull T obj, @NotNull SerializedDataType type); + @NotNull byte[] marshal(@NotNull T obj, @NotNull SerializedDataType type); } diff --git a/api/src/main/java/org/fuin/esc/api/SerializerRegistry.java b/api/src/main/java/org/fuin/esc/api/SerializerRegistry.java index cc1002e8..3633560c 100644 --- a/api/src/main/java/org/fuin/esc/api/SerializerRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/SerializerRegistry.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -26,23 +26,23 @@ public interface SerializerRegistry { /** * Tries to find a serializer for the given type. - * + * * @param type * Unique identifier for the type of data. - * + * * @return Serializer instance or throws a {@link IllegalArgumentException} if no serializer was found. */ @NotNull - public Serializer getSerializer(@NotNull SerializedDataType type); + Serializer getSerializer(@NotNull SerializedDataType type); /** * Tries to find a serializer for the given type. - * + * * @param type * Unique identifier for the type of data. - * + * * @return TRUE if a serializer was found for the type. */ - public boolean serializerExists(@NotNull SerializedDataType type); + boolean serializerExists(@NotNull SerializedDataType type); } diff --git a/api/src/main/java/org/fuin/esc/api/SerializerRegistryRequired.java b/api/src/main/java/org/fuin/esc/api/SerializerRegistryRequired.java index 1db1c090..3708442c 100644 --- a/api/src/main/java/org/fuin/esc/api/SerializerRegistryRequired.java +++ b/api/src/main/java/org/fuin/esc/api/SerializerRegistryRequired.java @@ -8,9 +8,9 @@ public interface SerializerRegistryRequired { /** * Sets the registry to use. - * + * * @param registry Actual registry. */ - public void setRegistry(SerializerRegistry registry); + void setRegistry(SerializerRegistry registry); } diff --git a/api/src/main/java/org/fuin/esc/api/SimpleCommonEvent.java b/api/src/main/java/org/fuin/esc/api/SimpleCommonEvent.java index 0b95d00d..b03370fb 100644 --- a/api/src/main/java/org/fuin/esc/api/SimpleCommonEvent.java +++ b/api/src/main/java/org/fuin/esc/api/SimpleCommonEvent.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -20,7 +20,8 @@ import jakarta.annotation.Nullable; import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Event that is uniquely identified by a UUID. It's equals and hash code methods are defined on the @@ -55,8 +56,8 @@ protected SimpleCommonEvent() { //NOSONAR Ignore uninitialized fields } /** - * Constructor without meta data. - * + * Constructor without metadata. + * * @param id * The ID of the event, used as part of the idempotent write check. This is type string to * allow different UUID implementations. It has to be a valid UUID string representation. @@ -64,16 +65,16 @@ protected SimpleCommonEvent() { //NOSONAR Ignore uninitialized fields * Unique name of the type of data. * @param data * Event data. - * + * */ public SimpleCommonEvent(@NotNull final EventId id, @NotNull final TypeName dataType, - @NotNull final Object data) { + @NotNull final Object data) { this(id, dataType, data, null, null); } /** - * Constructor with meta data. - * + * Constructor with metadata. + * * @param id * The ID of the event, used as part of the idempotent write check. This is type string to * allow different UUID implementations. It has to be a valid UUID string representation. @@ -82,13 +83,13 @@ public SimpleCommonEvent(@NotNull final EventId id, @NotNull final TypeName data * @param data * Event data. * @param metaType - * Unique name of the type of meta data. + * Unique name of the type of metadata. * @param meta * Meta data. - * + * */ public SimpleCommonEvent(@NotNull final EventId id, @NotNull final TypeName dataType, - @NotNull final Object data, @Nullable final TypeName metaType, @Nullable final Object meta) {//NOSONAR + @NotNull final Object data, @Nullable final TypeName metaType, @Nullable final Object meta) {//NOSONAR super(); Contract.requireArgNotNull("id", id); @@ -104,34 +105,32 @@ public SimpleCommonEvent(@NotNull final EventId id, @NotNull final TypeName data } @Override - public final EventId getId() { + public EventId getId() { return id; } @Override - public final TypeName getDataType() { + public TypeName getDataType() { return dataType; } @Override - public final Object getData() { + public Object getData() { return data; } @Override - public final TypeName getMetaType() { + public TypeName getMetaType() { return metaType; } @Override - public final Object getMeta() { + public Object getMeta() { return meta; } - // CHECKSTYLE:OFF Generated code - @Override - public final int hashCode() { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); @@ -139,23 +138,18 @@ public final int hashCode() { } @Override - public final boolean equals(Object obj) { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; - if (!(obj instanceof SimpleCommonEvent)) + if (!(obj instanceof SimpleCommonEvent other)) return false; - SimpleCommonEvent other = (SimpleCommonEvent) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; + return other.id == null; + } else return id.equals(other.id); } - // CHECKSTYLE:ON @Override public String toString() { diff --git a/api/src/main/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistry.java b/api/src/main/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistry.java index 3f536abf..99c0ac46 100644 --- a/api/src/main/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistry.java @@ -1,25 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.SerializedDataTypeRegistry; import org.fuin.objects4j.common.Contract; import java.util.HashMap; @@ -42,13 +40,13 @@ public SimpleSerializedDataTypeRegistry() { /** * Adds a new type/class combination to the registry. - * + * * @param type * Type of the data. * @param clasz * Class for the type. */ - public final void add(@NotNull final SerializedDataType type, final Class clasz) { + public void add(@NotNull final SerializedDataType type, final Class clasz) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("clasz", clasz); map.put(type, clasz); diff --git a/api/src/main/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistry.java b/api/src/main/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistry.java index ba4960e0..3334ef6a 100644 --- a/api/src/main/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistry.java +++ b/api/src/main/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistry.java @@ -1,24 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.*; import org.fuin.objects4j.common.Contract; import java.util.HashMap; @@ -40,14 +39,14 @@ public final class SimpleSerializerDeserializerRegistry implements SerDeserializ */ public SimpleSerializerDeserializerRegistry() { super(); - serMap = new HashMap(); - desMap = new HashMap(); - contentTypes = new HashMap(); + serMap = new HashMap<>(); + desMap = new HashMap<>(); + contentTypes = new HashMap<>(); } /** * Convenience method that adds both, a new serializer and deserializer to the registry. - * + * * @param type * Type of the data. * @param contentType @@ -56,8 +55,8 @@ public SimpleSerializerDeserializerRegistry() { * @param serDeserializer * Serializer and deserializer. */ - public final void add(@NotNull final SerializedDataType type, final String contentType, - @NotNull final SerDeserializer serDeserializer) { + public void add(@NotNull final SerializedDataType type, final String contentType, + @NotNull final SerDeserializer serDeserializer) { this.addSerializer(type, serDeserializer); this.addDeserializer(type, contentType, serDeserializer); @@ -66,7 +65,7 @@ public final void add(@NotNull final SerializedDataType type, final String conte /** * Adds a new deserializer to the registry. - * + * * @param type * Type of the data. * @param contentType @@ -75,8 +74,8 @@ public final void add(@NotNull final SerializedDataType type, final String conte * @param deserializer * Deserializer. */ - public final void addDeserializer(@NotNull final SerializedDataType type, final String contentType, - @NotNull final Deserializer deserializer) { + public void addDeserializer(@NotNull final SerializedDataType type, final String contentType, + @NotNull final Deserializer deserializer) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("contentType", contentType); @@ -89,15 +88,15 @@ public final void addDeserializer(@NotNull final SerializedDataType type, final /** * Sets the default content type to use if no content type is given. - * + * * @param type * Type of the data. * @param contentType * Content type like "application/xml" or "application/json" (without parameters - Only base * type). */ - public final void setDefaultContentType(@NotNull final SerializedDataType type, - final EnhancedMimeType contentType) { + public void setDefaultContentType(@NotNull final SerializedDataType type, + final EnhancedMimeType contentType) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("contentType", contentType); @@ -108,14 +107,14 @@ public final void setDefaultContentType(@NotNull final SerializedDataType type, /** * Adds a new serializer to the registry. - * + * * @param type * Type of the data. * @param serializer * Serializer. */ - public final void addSerializer(@NotNull final SerializedDataType type, - @NotNull final Serializer serializer) { + public void addSerializer(@NotNull final SerializedDataType type, + @NotNull final Serializer serializer) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("serializer", serializer); @@ -135,8 +134,8 @@ public Serializer getSerializer(final SerializedDataType type) { } @Override - public final Deserializer getDeserializer(final SerializedDataType type, - final EnhancedMimeType mimeType) { + public Deserializer getDeserializer(final SerializedDataType type, + final EnhancedMimeType mimeType) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("mimeType", mimeType); @@ -151,7 +150,7 @@ public final Deserializer getDeserializer(final SerializedDataType type, } @Override - public final Deserializer getDeserializer(final SerializedDataType type) { + public Deserializer getDeserializer(final SerializedDataType type) { Contract.requireArgNotNull("type", type); final EnhancedMimeType contentType = contentTypes.get(type); @@ -168,27 +167,19 @@ public final Deserializer getDeserializer(final SerializedDataType type) { } @Override - public final EnhancedMimeType getDefaultContentType(final SerializedDataType type) { + public EnhancedMimeType getDefaultContentType(final SerializedDataType type) { Contract.requireArgNotNull("type", type); - - final EnhancedMimeType contentType = contentTypes.get(type); - if (contentType == null) { - return null; - } - return contentType; + return contentTypes.get(type); } @Override - public final boolean serializerExists(final SerializedDataType type) { + public boolean serializerExists(final SerializedDataType type) { final Serializer ser = serMap.get(type); - if (ser == null) { - return false; - } - return true; + return ser != null; } @Override - public final boolean deserializerExists(final SerializedDataType type) { + public boolean deserializerExists(final SerializedDataType type) { Contract.requireArgNotNull("type", type); final EnhancedMimeType contentType = contentTypes.get(type); @@ -198,23 +189,17 @@ public final boolean deserializerExists(final SerializedDataType type) { final Key key = new Key(type, contentType.getBaseType()); final Deserializer des = desMap.get(key); - if (des == null) { - return false; - } - return true; + return des != null; } @Override - public final boolean deserializerExists(final SerializedDataType type, final EnhancedMimeType mimeType) { + public boolean deserializerExists(final SerializedDataType type, final EnhancedMimeType mimeType) { Contract.requireArgNotNull("type", type); Contract.requireArgNotNull("mimeType", mimeType); final Key key = new Key(type, mimeType.getBaseType()); final Deserializer des = desMap.get(key); - if (des == null) { - return false; - } - return true; + return des != null; } /** @@ -230,8 +215,6 @@ public Key(final SerializedDataType type, final String contentType) { this.contentType = contentType; } - // CHECKSTYLE:OFF Generated code - @Override public int hashCode() { final int prime = 31; @@ -247,23 +230,18 @@ public boolean equals(Object obj) { return true; if (obj == null) return false; - if (!(obj instanceof Key)) + if (!(obj instanceof Key other)) return false; - Key other = (Key) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (contentType == null) { - if (other.contentType != null) - return false; - } else if (!contentType.equals(other.contentType)) - return false; - return true; + return other.contentType == null; + } else return contentType.equals(other.contentType); } - // CHECKSTYLE:ON @Override public String toString() { diff --git a/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java b/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java index 72631989..36096cf4 100644 --- a/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java +++ b/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,9 +19,9 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.KeyValue; +import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; @@ -37,7 +37,7 @@ public final class SimpleStreamId implements StreamId { /** * Constructor with mandatory data. - * + * * @param name * Unique name. */ @@ -47,37 +47,37 @@ public SimpleStreamId(@NotNull final String name) { } @Override - public final String getName() { + public String getName() { return name; } @Override - public final boolean isProjection() { + public boolean isProjection() { return false; } @Override - public final T getSingleParamValue() { + public T getSingleParamValue() { throw new UnsupportedOperationException(getClass().getSimpleName() + " has no parameters"); } @Override - public final List getParameters() { + public List getParameters() { return Collections.emptyList(); } @Override - public final String asString() { + public String asString() { return name; } @Override - public final int hashCode() { + public int hashCode() { return name.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -92,7 +92,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return name; } diff --git a/api/src/main/java/org/fuin/esc/api/SimpleTenantId.java b/api/src/main/java/org/fuin/esc/api/SimpleTenantId.java index f4ed7347..05ddfbdf 100644 --- a/api/src/main/java/org/fuin/esc/api/SimpleTenantId.java +++ b/api/src/main/java/org/fuin/esc/api/SimpleTenantId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,8 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Tenant identifier that is based on a name. @@ -33,7 +34,7 @@ public final class SimpleTenantId implements TenantId { /** * Constructor with mandatory data. - * + * * @param name * Unique name. */ @@ -43,17 +44,17 @@ public SimpleTenantId(@NotNull final String name) { } @Override - public final String asString() { + public String asString() { return name; } @Override - public final int hashCode() { + public int hashCode() { return name.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -68,7 +69,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return name; } diff --git a/api/src/main/java/org/fuin/esc/api/StreamAlreadyExistsException.java b/api/src/main/java/org/fuin/esc/api/StreamAlreadyExistsException.java index 066665e4..c0a0fc04 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamAlreadyExistsException.java +++ b/api/src/main/java/org/fuin/esc/api/StreamAlreadyExistsException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,8 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Signals that a stream with that ID already exist and cannot be created. @@ -33,7 +34,7 @@ public final class StreamAlreadyExistsException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique name of the stream. */ @@ -45,11 +46,11 @@ public StreamAlreadyExistsException(@NotNull final StreamId streamId) { /** * Returns the unique identifier of the stream. - * + * * @return Stream that couldn't be created. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } diff --git a/api/src/main/java/org/fuin/esc/api/StreamDeletedException.java b/api/src/main/java/org/fuin/esc/api/StreamDeletedException.java index 1dff9ad1..1baab430 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamDeletedException.java +++ b/api/src/main/java/org/fuin/esc/api/StreamDeletedException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,8 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Signals that a stream with that name previously existed but was deleted. @@ -33,7 +34,7 @@ public final class StreamDeletedException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique name of the stream. */ @@ -45,11 +46,11 @@ public StreamDeletedException(@NotNull final StreamId streamId) { /** * Returns the unique identifier of the stream. - * + * * @return Stream that was not found. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } diff --git a/api/src/main/java/org/fuin/esc/api/StreamEventsSlice.java b/api/src/main/java/org/fuin/esc/api/StreamEventsSlice.java index 7bdff313..63bd7497 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamEventsSlice.java +++ b/api/src/main/java/org/fuin/esc/api/StreamEventsSlice.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,16 +19,15 @@ import jakarta.annotation.Nullable; import jakarta.validation.constraints.NotNull; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.fuin.objects4j.common.Immutable; +import javax.annotation.concurrent.Immutable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** - * + * Multiple ordered events read from an eventstore. */ @Immutable public final class StreamEventsSlice { @@ -43,7 +42,7 @@ public final class StreamEventsSlice { /** * Constructor with all data. - * + * * @param fromEventNumber * The starting point (represented as a sequence number) of the * read. @@ -53,17 +52,17 @@ public final class StreamEventsSlice { * @param nextEventNumber * The next event number that can be read. * @param endOfStream - * Determines whether or not this is the end of the stream. + * Determines whether this is the end of the stream. */ public StreamEventsSlice(final long fromEventNumber, - @Nullable final List events, final long nextEventNumber, - final boolean endOfStream) { + @Nullable final List events, final long nextEventNumber, + final boolean endOfStream) { this.fromEventNumber = fromEventNumber; - if (events == null || events.size() == 0) { - this.events = new ArrayList(); + if (events == null || events.isEmpty()) { + this.events = new ArrayList<>(); } else { - this.events = new ArrayList(events); + this.events = new ArrayList<>(events); } this.nextEventNumber = nextEventNumber; this.endOfStream = endOfStream; @@ -72,7 +71,7 @@ public StreamEventsSlice(final long fromEventNumber, /** * Returns the starting point (represented as a sequence number) of the read * operation. - * + * * @return Event number. */ public long getFromEventNumber() { @@ -81,7 +80,7 @@ public long getFromEventNumber() { /** * Returns the events read. - * + * * @return Unmodifiable list of events. */ @NotNull @@ -91,7 +90,7 @@ public List getEvents() { /** * Returns the next event number that can be read. - * + * * @return Next event number. */ public long getNextEventNumber() { @@ -99,38 +98,36 @@ public long getNextEventNumber() { } /** - * Returns a boolean representing whether or not this is the end of the + * Returns a boolean representing whether this is the end of the * stream. - * + * * @return TRUE if this is the end of the stream, else FALSE. */ public boolean isEndOfStream() { return endOfStream; } - // CHECKSTYLE:OFF Generated code @Override - public final int hashCode() { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (endOfStream ? 1231 : 1237); - result = prime * result + (int) (fromEventNumber ^ (fromEventNumber >>> 32)); - result = prime * result + (int) (nextEventNumber ^ (nextEventNumber >>> 32)); + result = prime * result + (int) (fromEventNumber ^ (fromEventNumber >>> 32)); + result = prime * result + (int) (nextEventNumber ^ (nextEventNumber >>> 32)); result = prime * result + ((events == null) ? 0 : Arrays.hashCode(events.toArray())); return result; } @Override - public final boolean equals(Object obj) { + public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; - if (!(obj instanceof StreamEventsSlice)) + if (!(obj instanceof StreamEventsSlice other)) return false; - StreamEventsSlice other = (StreamEventsSlice) obj; if (endOfStream != other.endOfStream) return false; if (fromEventNumber != other.fromEventNumber) @@ -138,43 +135,23 @@ public final boolean equals(Object obj) { if (nextEventNumber != other.nextEventNumber) return false; if (events == null) { - if (other.events != null) { - return false; - } + return other.events == null; } else { if (other.events == null) { return false; } - if (!Arrays.equals(events.toArray(), other.events.toArray())) { - return false; - } + return Arrays.equals(events.toArray(), other.events.toArray()); } - return true; } - // CHECKSTYLE:ON - - /** - * Returns a debug string representation with all data. - * - * @return Includes list content. - */ - @NotNull - public final String toDebugString() { - return new ToStringBuilder(this) - .append("fromEventNumber", fromEventNumber) - .append("nextEventNumber", nextEventNumber) - .append("endOfStream", endOfStream) - .append("events", events).toString(); - } - @Override - public final String toString() { - return new ToStringBuilder(this) - .append("fromEventNumber", fromEventNumber) - .append("nextEventNumber", nextEventNumber) - .append("endOfStream", endOfStream) - .append("events.size", events.size()).toString(); + public String toString() { + return "StreamEventsSlice{" + + "fromEventNumber=" + fromEventNumber + + ", nextEventNumber=" + nextEventNumber + + ", endOfStream=" + endOfStream + + ", events.size=" + events.size() + + '}'; } } diff --git a/api/src/main/java/org/fuin/esc/api/StreamId.java b/api/src/main/java/org/fuin/esc/api/StreamId.java index a5ff0d14..a1d383bd 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamId.java +++ b/api/src/main/java/org/fuin/esc/api/StreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -32,45 +32,44 @@ public interface StreamId extends Serializable { /** * Returns the name of the stream. - * + * * @return Unique name. */ @NotNull - public String getName(); + String getName(); /** * Returns the information if this identifier points to a projection. - * + * * @return TRUE if this is an identifier for a projection, else FALSE (stream). */ - public boolean isProjection(); + boolean isProjection(); /** * Convenience method that returns the one-and-only parameter value. CAUTION: This method will throw an exception if there are no - * parameters, more than one parameter or the type of the value cannot be casted to the expected result type. - * + * parameters, more than one parameter or the type of the value cannot be cast to the expected result type. + * * @return Value of the single parameter. - * + * * @param * Type of the returned value. */ - @NotNull - public T getSingleParamValue(); + @NotNull T getSingleParamValue(); /** * Returns the parameters used in addition to the pure stream name to identify the stream. - * + * * @return Ordered unmodifiable list of parameters - May be empty if no parameters exist. */ @NotNull - public List getParameters(); + List getParameters(); /** * Constructs a unique string from name and parameters. - * + * * @return String representation of the identifier. */ @NotNull - public String asString(); + String asString(); } diff --git a/api/src/main/java/org/fuin/esc/api/StreamNotFoundException.java b/api/src/main/java/org/fuin/esc/api/StreamNotFoundException.java index 8f67e675..00bb8902 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamNotFoundException.java +++ b/api/src/main/java/org/fuin/esc/api/StreamNotFoundException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,7 +19,8 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Signals that a stream with that ID doesn't exist. @@ -33,7 +34,7 @@ public final class StreamNotFoundException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique name of the stream. */ @@ -45,11 +46,11 @@ public StreamNotFoundException(@NotNull final StreamId streamId) { /** * Returns the unique identifier of the stream. - * + * * @return Stream that was not found. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } diff --git a/api/src/main/java/org/fuin/esc/api/StreamReadOnlyException.java b/api/src/main/java/org/fuin/esc/api/StreamReadOnlyException.java index ef7e69dc..230925c9 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamReadOnlyException.java +++ b/api/src/main/java/org/fuin/esc/api/StreamReadOnlyException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,10 +19,11 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** - * Signals that a an attempt was made to write to a stream that is read only. + * Signals that a attempt was made to write to a stream that is read only. */ @Immutable public final class StreamReadOnlyException extends RuntimeException { @@ -33,7 +34,7 @@ public final class StreamReadOnlyException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique name of the stream. */ @@ -45,11 +46,11 @@ public StreamReadOnlyException(@NotNull final StreamId streamId) { /** * Returns the unique identifier of the stream. - * + * * @return Stream that was not found. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } diff --git a/api/src/main/java/org/fuin/esc/api/StreamState.java b/api/src/main/java/org/fuin/esc/api/StreamState.java index fcb71ecf..3a50d199 100644 --- a/api/src/main/java/org/fuin/esc/api/StreamState.java +++ b/api/src/main/java/org/fuin/esc/api/StreamState.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -26,34 +26,34 @@ public enum StreamState { /** The stream was created and may contain events. */ ACTIVE(0), - + /** The stream was deleted, but may be recreated by appending new events to it. */ SOFT_DELETED(1), - + /** The stream was deleted, but cannot be recreated. */ HARD_DELETED(2); - - - private int dbValue; - - private StreamState(final int dbValue) { + + + private final int dbValue; + + StreamState(final int dbValue) { this.dbValue = dbValue; } - + /** * Returns the database value. - * + * * @return DB value. */ public final int dbValue() { return dbValue; } - + /** * Returns the enum from a database value. - * + * * @param db Database value to return an enum for. - * + * * @return Enum. */ @NotNull @@ -65,5 +65,5 @@ public static StreamState fromDbValue(final int db) { } throw new IllegalArgumentException("The db value is unknown: " + db); } - + } diff --git a/api/src/main/java/org/fuin/esc/api/SubscribableEventStore.java b/api/src/main/java/org/fuin/esc/api/SubscribableEventStore.java index d5dfd34a..e913836b 100644 --- a/api/src/main/java/org/fuin/esc/api/SubscribableEventStore.java +++ b/api/src/main/java/org/fuin/esc/api/SubscribableEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,7 +29,7 @@ public interface SubscribableEventStore extends EventStoreBasics { /** * Subscribe a stream starting with a given event number. - * + * * @param streamId * Unique stream identifier. * @param eventNumber @@ -41,9 +41,9 @@ public interface SubscribableEventStore extends EventStoreBasics { * @param onDrop * Will be called when the subscription was exceptionally * dropped. - * + * * @return Subscription result. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -52,17 +52,17 @@ public interface SubscribableEventStore extends EventStoreBasics { * deleted. */ @NotNull - public Subscription subscribeToStream(@NotNull StreamId streamId, long eventNumber, - @NotNull BiConsumer onEvent, - @NotNull BiConsumer onDrop); + Subscription subscribeToStream(@NotNull StreamId streamId, long eventNumber, + @NotNull BiConsumer onEvent, + @NotNull BiConsumer onDrop); /** * Unsubscribe from a stream. If the given subscription does not exist, * nothing happens. - * + * * @param subscription * to be terminated. */ - public void unsubscribeFromStream(@NotNull Subscription subscription); + void unsubscribeFromStream(@NotNull Subscription subscription); } diff --git a/api/src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java b/api/src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java index 21a324eb..9773fda3 100644 --- a/api/src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java +++ b/api/src/main/java/org/fuin/esc/api/SubscribableEventStoreAsync.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -30,7 +30,7 @@ public interface SubscribableEventStoreAsync extends EventStoreBasicsAsync { /** * Subscribe a stream starting with a given event number. - * + * * @param streamId * Unique stream identifier. * @param eventNumber @@ -42,23 +42,23 @@ public interface SubscribableEventStoreAsync extends EventStoreBasicsAsync { * @param onDrop * Will be called when the subscription was exceptionally * dropped. - * + * * @return Future with subscription result. */ @NotNull - public CompletableFuture subscribeToStream(@NotNull StreamId streamId, long eventNumber, - @NotNull BiConsumer onEvent, - @NotNull BiConsumer onDrop); + CompletableFuture subscribeToStream(@NotNull StreamId streamId, long eventNumber, + @NotNull BiConsumer onEvent, + @NotNull BiConsumer onDrop); /** * Unsubscribe from a stream. - * + * * @param subscription * to be terminated. - * + * * @return Future with no result. */ @NotNull - public CompletableFuture unsubscribeFromStream(@NotNull Subscription subscription); + CompletableFuture unsubscribeFromStream(@NotNull Subscription subscription); } diff --git a/api/src/main/java/org/fuin/esc/api/Subscription.java b/api/src/main/java/org/fuin/esc/api/Subscription.java index 50aa9753..05fa17f7 100644 --- a/api/src/main/java/org/fuin/esc/api/Subscription.java +++ b/api/src/main/java/org/fuin/esc/api/Subscription.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -23,7 +23,7 @@ import java.io.Serializable; /** - * Result of subscribing to a stream. The sub classes will contain + * Result of subscribing to a stream. The subclasses will contain * implementation specific data that is required to handle unsubscribe requests. */ public abstract class Subscription implements Serializable { @@ -36,21 +36,21 @@ public abstract class Subscription implements Serializable { /** * Constructor with all mandatory data. - * + * * @param streamId * Unique stream identifier. * @param lastEventNumber * Number of the last event written to the stream. */ public Subscription(@NotNull final StreamId streamId, - @Nullable final Long lastEventNumber) { + @Nullable final Long lastEventNumber) { this.streamId = streamId; this.lastEventNumber = lastEventNumber; } /** * Returns the unique stream identifier. - * + * * @return Stream ID. */ @NotNull @@ -60,7 +60,7 @@ public final StreamId getStreamId() { /** * Returns the number of the last event written to the stream. - * + * * @return Event number. */ @Nullable diff --git a/api/src/main/java/org/fuin/esc/api/TenantId.java b/api/src/main/java/org/fuin/esc/api/TenantId.java index c1cb5186..8055ed44 100644 --- a/api/src/main/java/org/fuin/esc/api/TenantId.java +++ b/api/src/main/java/org/fuin/esc/api/TenantId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,9 +28,9 @@ public interface TenantId extends Serializable { /** * Returns the identifier as string. - * + * * @return String representation of the ID. */ - public String asString(); - + String asString(); + } diff --git a/api/src/main/java/org/fuin/esc/api/TypeName.java b/api/src/main/java/org/fuin/esc/api/TypeName.java index 8820b64f..a82aa065 100644 --- a/api/src/main/java/org/fuin/esc/api/TypeName.java +++ b/api/src/main/java/org/fuin/esc/api/TypeName.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -20,15 +20,18 @@ import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.AbstractStringValueObject; +import javax.annotation.concurrent.Immutable; +import java.io.Serial; + /** * Name that uniquely identifies a type of data. */ @Immutable public final class TypeName extends AbstractStringValueObject { + @Serial private static final long serialVersionUID = 811127657088134517L; @NotNull @@ -43,7 +46,7 @@ protected TypeName() { //NOSONAR Ignore uninitialized fields /** * Constructor with unique type name. - * + * * @param value * Type name. */ @@ -54,12 +57,12 @@ public TypeName(@NotEmpty final String value) { } @Override - public final String asBaseType() { + public String asBaseType() { return value; } @Override - public final String toString() { + public String toString() { return asBaseType(); } diff --git a/api/src/main/java/org/fuin/esc/api/WritableEventStore.java b/api/src/main/java/org/fuin/esc/api/WritableEventStore.java index cf991bf5..3fa9769b 100644 --- a/api/src/main/java/org/fuin/esc/api/WritableEventStore.java +++ b/api/src/main/java/org/fuin/esc/api/WritableEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -32,40 +32,40 @@ public interface WritableEventStore extends EventStoreBasics { * creating a stream without appending events to it. If the event store does * not support a create operation, a call to {@link #createStream(StreamId)} * will do nothing, but it will not fail. - * + * * @return TRUE if it's possible to create a stream without appending events * to it or FALSE if only appending events implicitly creates a * stream. */ - public boolean isSupportsCreateStream(); + boolean isSupportsCreateStream(); /** - * Creates a new stream. Some implementations may do nothing, because the + * Creates a new stream. Some implementations may do nothing, because they * create streams when the first event is appended. If * {@link #isSupportsCreateStream()} returns FALSE, this method does * nothing, but is expected not fail. - * + * * @param streamId * The unique identifier of the stream to create. - * + * * @throws StreamAlreadyExistsException * The stream already exists. */ - public void createStream(@NotNull StreamId streamId) throws StreamAlreadyExistsException; + void createStream(@NotNull StreamId streamId) throws StreamAlreadyExistsException; /** * Appends one or more events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param expectedVersion * The version the stream should have. * @param events * Array of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -77,21 +77,21 @@ public interface WritableEventStore extends EventStoreBasics { * @throws StreamReadOnlyException * The given stream identifier points to a projection. */ - public long appendToStream(@NotNull StreamId streamId, long expectedVersion, @NotNull CommonEvent... events) + long appendToStream(@NotNull StreamId streamId, long expectedVersion, @NotNull CommonEvent... events) throws StreamNotFoundException, StreamDeletedException, WrongExpectedVersionException, StreamReadOnlyException; /** * Appends one or more events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param events * Array of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -101,22 +101,22 @@ public long appendToStream(@NotNull StreamId streamId, long expectedVersion, @No * @throws StreamReadOnlyException * The given stream identifier points to a projection. */ - public long appendToStream(@NotNull StreamId streamId, @NotNull CommonEvent... events) + long appendToStream(@NotNull StreamId streamId, @NotNull CommonEvent... events) throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException; /** * Appends a list of events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param expectedVersion * The version the stream should have. * @param events * List of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -127,21 +127,21 @@ public long appendToStream(@NotNull StreamId streamId, @NotNull CommonEvent... e * @throws StreamReadOnlyException * The given stream identifier points to a projection. */ - public long appendToStream(@NotNull StreamId streamId, long expectedVersion, - @NotNull List events) throws StreamNotFoundException, StreamDeletedException, + long appendToStream(@NotNull StreamId streamId, long expectedVersion, + @NotNull List events) throws StreamNotFoundException, StreamDeletedException, WrongExpectedVersionException, StreamReadOnlyException; /** * Appends a list of events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param events * List of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -150,7 +150,7 @@ public long appendToStream(@NotNull StreamId streamId, long expectedVersion, * @throws StreamReadOnlyException * The given stream identifier points to a projection. */ - public long appendToStream(@NotNull StreamId streamId, @NotNull List events) + long appendToStream(@NotNull StreamId streamId, @NotNull List events) throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException; /** @@ -159,7 +159,7 @@ public long appendToStream(@NotNull StreamId streamId, @NotNull List * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,36 +29,36 @@ public interface WritableEventStoreAsync extends EventStoreBasicsAsync { /** - * Creates a new stream. Some implementations may do nothing, because the + * Creates a new stream. Some implementations may do nothing, because they * create streams when the first event is appended. If * {@link #isSupportsCreateStream()} returns FALSE, this method does * nothing, but is expected not fail. - * + * * @param streamId * The unique identifier of the stream to create. - * + * * @return Nothing. - * + * * @throws StreamAlreadyExistsException * The stream already exists. */ @NotNull - public CompletableFuture createStream(@NotNull StreamId streamId) + CompletableFuture createStream(@NotNull StreamId streamId) throws StreamAlreadyExistsException; /** * Appends one or more events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param expectedVersion * The version the stream should have. * @param events * Array of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -71,20 +71,20 @@ public CompletableFuture createStream(@NotNull StreamId streamId) * The given stream identifier points to a projection. */ @NotNull - public CompletableFuture appendToStream(@NotNull StreamId streamId, long expectedVersion, - @NotNull CommonEvent... events); + CompletableFuture appendToStream(@NotNull StreamId streamId, long expectedVersion, + @NotNull CommonEvent... events); /** * Appends one or more events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param events * Array of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -95,22 +95,22 @@ public CompletableFuture appendToStream(@NotNull StreamId streamId, long e * The given stream identifier points to a projection. */ @NotNull - public CompletableFuture appendToStream(@NotNull StreamId streamId, - @NotNull CommonEvent... events); + CompletableFuture appendToStream(@NotNull StreamId streamId, + @NotNull CommonEvent... events); /** * Appends a list of events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param expectedVersion * The version the stream should have. * @param events * List of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -122,20 +122,20 @@ public CompletableFuture appendToStream(@NotNull StreamId streamId, * The given stream identifier points to a projection. */ @NotNull - public CompletableFuture appendToStream(@NotNull StreamId streamId, long expectedVersion, - @NotNull List events); + CompletableFuture appendToStream(@NotNull StreamId streamId, long expectedVersion, + @NotNull List events); /** * Appends a list of events to a stream. If the stream does not exist, the * implementation may create it on the fly. - * + * * @param streamId * The unique identifier of the stream to append the events to. * @param events * List of events to write to the stream - * + * * @return The next expected version for the stream. - * + * * @throws StreamNotFoundException * The stream does not exist in the repository and the * implementation cannot create it on-the-fly. @@ -145,12 +145,12 @@ public CompletableFuture appendToStream(@NotNull StreamId streamId, long e * The given stream identifier points to a projection. */ @NotNull - public CompletableFuture appendToStream(@NotNull StreamId streamId, - @NotNull List events); + CompletableFuture appendToStream(@NotNull StreamId streamId, + @NotNull List events); /** * Deletes a stream from the event store if it has a given version. - * + * * @param streamId * The unique identifier of the stream to be deleted * @param expectedVersion @@ -160,9 +160,9 @@ public CompletableFuture appendToStream(@NotNull StreamId streamId, * (soft delete) if appending to it will recreate it. Please note * that in this case the version numbers do not start at zero but * at where you previously soft deleted the stream from. - * + * * @return Nothing. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -173,13 +173,13 @@ public CompletableFuture appendToStream(@NotNull StreamId streamId, * The expected version didn't match the actual version. */ @NotNull - public CompletableFuture deleteStream(@NotNull StreamId streamId, long expectedVersion, - boolean hardDelete); + CompletableFuture deleteStream(@NotNull StreamId streamId, long expectedVersion, + boolean hardDelete); /** * Deletes a stream from the event store not matter what the current version * is. - * + * * @param streamId * The unique identifier of the stream to be deleted * @param hardDelete @@ -187,9 +187,9 @@ public CompletableFuture deleteStream(@NotNull StreamId streamId, long exp * (soft delete) if appending to it will recreate it. Please note * that in this case the version numbers do not start at zero but * at where you previously soft deleted the stream from. - * + * * @return Nothing. - * + * * @throws StreamNotFoundException * A stream with the given name does not exist in the * repository. @@ -198,7 +198,7 @@ public CompletableFuture deleteStream(@NotNull StreamId streamId, long exp * deleted. */ @NotNull - public CompletableFuture deleteStream(@NotNull StreamId streamId, boolean hardDelete); + CompletableFuture deleteStream(@NotNull StreamId streamId, boolean hardDelete); /** * Returns the information if the event store implementation supports @@ -206,11 +206,11 @@ public CompletableFuture deleteStream(@NotNull StreamId streamId, long exp * not support a create operation, a call to * {@link EventStore#createStream(StreamId)} will do nothing, but it will * not fail. - * + * * @return TRUE if it's possible to create a stream without appending events * to it or FALSE if only appending events implicitly creates a * stream. */ - public boolean isSupportsCreateStream(); + boolean isSupportsCreateStream(); } diff --git a/api/src/main/java/org/fuin/esc/api/WrongExpectedVersionException.java b/api/src/main/java/org/fuin/esc/api/WrongExpectedVersionException.java index 8e8b6fcd..5a0a683b 100644 --- a/api/src/main/java/org/fuin/esc/api/WrongExpectedVersionException.java +++ b/api/src/main/java/org/fuin/esc/api/WrongExpectedVersionException.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -20,7 +20,8 @@ import jakarta.annotation.Nullable; import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * Signals a conflict between an expected and an actual version. @@ -38,7 +39,7 @@ public final class WrongExpectedVersionException extends RuntimeException { /** * Constructor with all data. - * + * * @param streamId * Unique name of the stream. * @param expected @@ -47,11 +48,10 @@ public final class WrongExpectedVersionException extends RuntimeException { * Actual version. */ public WrongExpectedVersionException(@NotNull final StreamId streamId, - @NotNull final Long expected, @Nullable final Long actual) { - // CHECKSTYLE:OFF:AvoidInlineConditionals OK here + @NotNull final Long expected, @Nullable final Long actual) { super("Expected version " + expected + " for stream '" + streamId + (actual == null ? "'" : "', but was " + actual)); - // CHECKSTYLE:ON + Contract.requireArgNotNull("streamId", streamId); Contract.requireArgNotNull("expected", streamId); this.streamId = streamId; @@ -61,32 +61,32 @@ public WrongExpectedVersionException(@NotNull final StreamId streamId, /** * Returns the unique identifier of the stream. - * + * * @return Stream that was not found. */ @NotNull - public final StreamId getStreamId() { + public StreamId getStreamId() { return streamId; } /** * Returns the expected version. - * + * * @return Expected version. */ @NotNull - public final Long getExpected() { + public Long getExpected() { return expected; } /** * Returns the actual version. - * + * * @return Actual version or null if the event store didn't * tell us what version it expected. */ @Nullable - public final Long getActual() { + public Long getActual() { return actual; } diff --git a/api/src/test/java/org/fuin/esc/api/ArchitectureTest.java b/api/src/test/java/org/fuin/esc/api/ArchitectureTest.java new file mode 100644 index 00000000..c2e55594 --- /dev/null +++ b/api/src/test/java/org/fuin/esc/api/ArchitectureTest.java @@ -0,0 +1,56 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.api; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.objects4j.common.ConstraintViolationException; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(API_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(API_PACKAGE, + "java..", + "jakarta.activation..", + "jakarta.annotation..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.apache.commons.lang3..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core.." + ); + + +} + diff --git a/api/src/test/java/org/fuin/esc/api/BaseTest.java b/api/src/test/java/org/fuin/esc/api/BaseTest.java index 915c5e61..17788ec7 100644 --- a/api/src/test/java/org/fuin/esc/api/BaseTest.java +++ b/api/src/test/java/org/fuin/esc/api/BaseTest.java @@ -1,44 +1,45 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. + * along with this library. If not, see . */ package org.fuin.esc.api; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; -/** - * General tests for all classes. - */ -// CHECKSTYLE:OFF Test code -public class BaseTest { +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; - @Disabled("Implement with ArchUnit!") - @Test - public final void testCoverage() { - // Make sure all classes have a test - // TODO Implement! - } +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { - @Disabled("Implement with ArchUnit!") - @Test - public final void testNullability() { - // Make sure all public/protected methods have either @Nullable or @NotNull - // TODO Implement! - } + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/DelegatingAsyncEventStoreTest.java b/api/src/test/java/org/fuin/esc/api/DelegatingAsyncEventStoreTest.java index b0b15831..424ec2c7 100644 --- a/api/src/test/java/org/fuin/esc/api/DelegatingAsyncEventStoreTest.java +++ b/api/src/test/java/org/fuin/esc/api/DelegatingAsyncEventStoreTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -35,7 +35,6 @@ /** * Test for {@link DelegatingAsyncEventStore}. */ -// CHECKSTYLE:OFF Test @ExtendWith(MockitoExtension.class) public class DelegatingAsyncEventStoreTest { @@ -113,7 +112,7 @@ public void testAppendToStreamArrayAnyVersion() throws Exception { verify(delegate).appendToStream(streamId, eventOne, eventTwo); } - + @Test public void testReadEvent() throws Exception { @@ -211,7 +210,7 @@ public void testAppendToStreamListExpectedVersion() throws Exception { verify(delegate).appendToStream(streamId, ANY_VERSION, events); } - + @Test public void testAppendToStreamListAnyVersion() throws Exception { @@ -260,7 +259,7 @@ public void testStreamState() throws Exception { verify(delegate).streamState(streamId); } - + private static CommonEvent event(final String name) { return event(new EventId(), name); } @@ -270,4 +269,4 @@ private static CommonEvent event(final EventId id, final String name) { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/EnhancedMimeTypeTest.java b/api/src/test/java/org/fuin/esc/api/EnhancedMimeTypeTest.java index 7ac6e085..9f58e85e 100644 --- a/api/src/test/java/org/fuin/esc/api/EnhancedMimeTypeTest.java +++ b/api/src/test/java/org/fuin/esc/api/EnhancedMimeTypeTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,7 +21,6 @@ import jakarta.activation.MimeTypeParseException; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; -import org.fuin.esc.api.EnhancedMimeType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,7 +34,6 @@ /** * Tests the {@link EnhancedMimeType} class. */ -// CHECKSTYLE:OFF Test public class EnhancedMimeTypeTest { private EnhancedMimeType testee; diff --git a/api/src/test/java/org/fuin/esc/api/EscApiUtilsTest.java b/api/src/test/java/org/fuin/esc/api/EscApiUtilsTest.java index 8d17976e..42841a47 100644 --- a/api/src/test/java/org/fuin/esc/api/EscApiUtilsTest.java +++ b/api/src/test/java/org/fuin/esc/api/EscApiUtilsTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/test/java/org/fuin/esc/api/EventIdTest.java b/api/src/test/java/org/fuin/esc/api/EventIdTest.java index 999b15e4..62822e05 100644 --- a/api/src/test/java/org/fuin/esc/api/EventIdTest.java +++ b/api/src/test/java/org/fuin/esc/api/EventIdTest.java @@ -1,69 +1,16 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.api; - -import org.fuin.objects4j.common.ConstraintViolationException; -import org.junit.jupiter.api.Test; - -import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.fuin.utils4j.Utils4J.deserialize; -import static org.fuin.utils4j.Utils4J.serialize; - -// CHECKSTYLE:OFF Test code -public final class EventIdTest { - - @Test - public final void testSerialize() { - final UUID uuid = UUID.randomUUID(); - final EventId original = new EventId(uuid); - final EventId copy = deserialize(serialize(original)); - assertThat(original).isEqualTo(copy); - } - - @Test - public final void testConstructValid() { - final UUID uuid = UUID.randomUUID(); - assertThat(new EventId(uuid).asBaseType()).isEqualTo(uuid); - } - - @Test - public final void testConstructNullString() { - assertThatThrownBy(() -> { - new EventId((String) null); - }).isInstanceOf(ConstraintViolationException.class); - } - - @Test - public final void testConstructNullUUID() { - assertThatThrownBy(() -> { - new EventId((UUID) null); - }).isInstanceOf(ConstraintViolationException.class); - } - - @Test - public final void testConstructInvalidString() { - assertThatThrownBy(() -> { - new EventId("x"); - }).isInstanceOf(ConstraintViolationException.class); - } - -} -// CHECKSTYLE:ON +package org.fuin.esc.api; + +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +/** + * Test for the {@link EventId} class. + */ +public class EventIdTest { + + @Test + void testEqualsHashCode() { + EqualsVerifier.forClass(EventId.class).verify(); + } + +} diff --git a/api/src/test/java/org/fuin/esc/api/EventNotFoundExceptionTest.java b/api/src/test/java/org/fuin/esc/api/EventNotFoundExceptionTest.java index d51ca885..7bc6247a 100644 --- a/api/src/test/java/org/fuin/esc/api/EventNotFoundExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/EventNotFoundExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link EventNotFoundException} class. */ -// CHECKSTYLE:OFF Test public class EventNotFoundExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -71,4 +70,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/ExpectedVersionTest.java b/api/src/test/java/org/fuin/esc/api/ExpectedVersionTest.java index 0cad7678..3077ec25 100644 --- a/api/src/test/java/org/fuin/esc/api/ExpectedVersionTest.java +++ b/api/src/test/java/org/fuin/esc/api/ExpectedVersionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF Test code + public final class ExpectedVersionTest { @Test @@ -45,4 +45,4 @@ public final void testNo() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/JsonDeSerializerTest.java b/api/src/test/java/org/fuin/esc/api/JsonDeSerializerTest.java deleted file mode 100644 index bcbeda07..00000000 --- a/api/src/test/java/org/fuin/esc/api/JsonDeSerializerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.api; - -import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerializedDataType; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests the {@link JsonDeSerializer} class. - */ -// CHECKSTYLE:OFF Test -public class JsonDeSerializerTest { - - private JsonDeSerializer testee; - - @BeforeEach - public void setup() throws MimeTypeParseException { - testee = new JsonDeSerializer(); - } - - @AfterEach - public void teardown() { - testee = null; - } - - @Test - public void testMarshalUnmarshal() { - - // PREPARE - final SerializedDataType type = new SerializedDataType("Person"); - final JsonObject original = Json.createObjectBuilder().add("name", "Peter").add("age", 21).build(); - - // TEST - final byte[] data = testee.marshal(original, type); - final JsonObject copy = testee.unmarshal(data, type, EnhancedMimeType.create("application/json; encoding=utf-8")); - - // VERIFY - assertThat(copy.keySet()).contains("name", "age"); - assertThat(copy.getString("name")).isEqualTo("Peter"); - assertThat(copy.getInt("age")).isEqualTo(21); - - } - -} -// CHECKSTYLE:ON diff --git a/api/src/test/java/org/fuin/esc/api/MyEvent.java b/api/src/test/java/org/fuin/esc/api/MyEvent.java index 21dc7b9c..46b17c35 100644 --- a/api/src/test/java/org/fuin/esc/api/MyEvent.java +++ b/api/src/test/java/org/fuin/esc/api/MyEvent.java @@ -1,9 +1,11 @@ -// CHECKSTYLE:OFF Test package org.fuin.esc.api; +import com.tngtech.archunit.junit.ArchIgnore; + /** * Example event. */ +@ArchIgnore @HasSerializedDataTypeConstant public class MyEvent { @@ -45,4 +47,3 @@ public boolean equals(Object obj) { } } -// CHECKSTYLE:ON diff --git a/api/src/test/java/org/fuin/esc/api/ProjectionNotWritableExceptionTest.java b/api/src/test/java/org/fuin/esc/api/ProjectionNotWritableExceptionTest.java index 6d93f28b..4609b16e 100644 --- a/api/src/test/java/org/fuin/esc/api/ProjectionNotWritableExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/ProjectionNotWritableExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link StreamReadOnlyException} class. */ -// CHECKSTYLE:OFF Test public class ProjectionNotWritableExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -67,4 +66,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/ProjectionStreamIdTest.java b/api/src/test/java/org/fuin/esc/api/ProjectionStreamIdTest.java index bfd37b60..d573c118 100644 --- a/api/src/test/java/org/fuin/esc/api/ProjectionStreamIdTest.java +++ b/api/src/test/java/org/fuin/esc/api/ProjectionStreamIdTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link ProjectionStreamId} class. */ -// CHECKSTYLE:OFF Test public class ProjectionStreamIdTest { private static final String NAME = "MyProjection"; @@ -65,4 +64,4 @@ public void testGetSingleParamValue() { }).isInstanceOf(UnsupportedOperationException.class); } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SerializedDataTypeTest.java b/api/src/test/java/org/fuin/esc/api/SerializedDataTypeTest.java index 97b63dbe..c19914da 100644 --- a/api/src/test/java/org/fuin/esc/api/SerializedDataTypeTest.java +++ b/api/src/test/java/org/fuin/esc/api/SerializedDataTypeTest.java @@ -1,23 +1,22 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; -import org.fuin.esc.api.SerializedDataType; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.jupiter.api.Test; @@ -26,7 +25,7 @@ import static org.fuin.utils4j.Utils4J.deserialize; import static org.fuin.utils4j.Utils4J.serialize; -// CHECKSTYLE:OFF Test code + public final class SerializedDataTypeTest { @Test @@ -56,7 +55,7 @@ public final void testConstructEmpty() { assertThatThrownBy(() -> { new SerializedDataType(""); }).isInstanceOf(ConstraintViolationException.class); -} + } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SimpleCommonEventTest.java b/api/src/test/java/org/fuin/esc/api/SimpleCommonEventTest.java index 083c014d..8557382a 100644 --- a/api/src/test/java/org/fuin/esc/api/SimpleCommonEventTest.java +++ b/api/src/test/java/org/fuin/esc/api/SimpleCommonEventTest.java @@ -1,24 +1,22 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; -import jakarta.json.Json; -import jakarta.json.JsonObject; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.AfterEach; @@ -30,18 +28,17 @@ /** * Tests the {@link SimpleCommonEvent} class. */ -// CHECKSTYLE:OFF Test public class SimpleCommonEventTest { private static final EventId ID = new EventId(); private static final TypeName DATA_TYPE = new TypeName("MyEvent"); - private static MyEvent DATA = new MyEvent("Peter"); + private static final MyEvent DATA = new MyEvent("Peter"); private static final TypeName META_TYPE = new TypeName("MyMeta"); - private static JsonObject META = Json.createObjectBuilder().add("ip", "127.0.0.1").build(); + private static final String META = " { \"ip\" : \"127.0.0.1\" }"; private SimpleCommonEvent testee; @@ -70,4 +67,4 @@ public void testGetter() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistryTest.java b/api/src/test/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistryTest.java index e1ff601b..519fbe58 100644 --- a/api/src/test/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistryTest.java +++ b/api/src/test/java/org/fuin/esc/api/SimpleSerializedDataTypeRegistryTest.java @@ -1,24 +1,22 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,7 +25,6 @@ /** * Tests the {@link SimpleSerializedDataTypeRegistry} class. */ -// CHECKSTYLE:OFF Test public class SimpleSerializedDataTypeRegistryTest { @Test @@ -36,7 +33,7 @@ public void testFindClass() { final SimpleSerializedDataTypeRegistry testee = new SimpleSerializedDataTypeRegistry(); final SerializedDataType type = new SerializedDataType("String"); testee.add(type, String.class); - + assertThat(testee.findClass(type)).isEqualTo(String.class); try { @@ -48,4 +45,4 @@ public void testFindClass() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistryTest.java b/api/src/test/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistryTest.java index b11cfbc4..21d07203 100644 --- a/api/src/test/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistryTest.java +++ b/api/src/test/java/org/fuin/esc/api/SimpleSerializerDeserializerRegistryTest.java @@ -1,38 +1,35 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.activation.MimeTypeParseException; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; /** * Tests the {@link SimpleSerializerDeserializerRegistry} class. */ -// CHECKSTYLE:OFF Test public class SimpleSerializerDeserializerRegistryTest { private SimpleSerializerDeserializerRegistry testee; @@ -53,16 +50,15 @@ public void testAddGetDeserializer() { // PREPARE final SerializedDataType type = new SerializedDataType("MyType"); final String contentType = "application/json"; - final JsonDeSerializer deserializer = new JsonDeSerializer(); + final Deserializer deserializer = Mockito.mock(Deserializer.class); final EnhancedMimeType mimeType = EnhancedMimeType.create( - "application", "json", Charset.forName("utf-8"), "1"); + "application", "json", StandardCharsets.UTF_8, "1"); // TEST testee.addDeserializer(type, contentType, deserializer); // VERIFY - assertThat(testee.getDeserializer(type, mimeType)).isSameAs( - deserializer); + assertThat(testee.getDeserializer(type, mimeType)).isSameAs(deserializer); } @@ -72,9 +68,9 @@ public void testSetGetDefaultContentType() { // PREPARE final SerializedDataType type = new SerializedDataType("MyType"); final String contentType = "application/json"; - final JsonDeSerializer deserializer = new JsonDeSerializer(); + final Deserializer deserializer = Mockito.mock(Deserializer.class); final EnhancedMimeType mimeType = EnhancedMimeType.create( - "application", "json", Charset.forName("utf-8")); + "application", "json", StandardCharsets.UTF_8); testee.addDeserializer(type, contentType, deserializer); // TEST @@ -91,7 +87,7 @@ public void testAddGetSerializer() { // PREPARE final SerializedDataType type = new SerializedDataType("MyType"); - final JsonDeSerializer serializer = new JsonDeSerializer(); + final Serializer serializer = Mockito.mock(Serializer.class); // TEST testee.addSerializer(type, serializer); @@ -102,4 +98,4 @@ public void testAddGetSerializer() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SimpleStreamIdTest.java b/api/src/test/java/org/fuin/esc/api/SimpleStreamIdTest.java index 34b0ff9a..dd27df97 100644 --- a/api/src/test/java/org/fuin/esc/api/SimpleStreamIdTest.java +++ b/api/src/test/java/org/fuin/esc/api/SimpleStreamIdTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link SimpleStreamId} class. */ -// CHECKSTYLE:OFF Test public class SimpleStreamIdTest { private static final String NAME = "MyStream1"; @@ -65,4 +64,4 @@ public void testGetSingleParamValue() { }).isInstanceOf(UnsupportedOperationException.class); } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SimpleTenantIdTest.java b/api/src/test/java/org/fuin/esc/api/SimpleTenantIdTest.java index 42c296aa..0a3ebbdc 100644 --- a/api/src/test/java/org/fuin/esc/api/SimpleTenantIdTest.java +++ b/api/src/test/java/org/fuin/esc/api/SimpleTenantIdTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/api/src/test/java/org/fuin/esc/api/StreamAlreadyExistsExceptionTest.java b/api/src/test/java/org/fuin/esc/api/StreamAlreadyExistsExceptionTest.java index b0315ae7..f395f233 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamAlreadyExistsExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamAlreadyExistsExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link StreamAlreadyExistsException} class. */ -// CHECKSTYLE:OFF Test public class StreamAlreadyExistsExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -67,4 +66,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamDeletedExceptionTest.java b/api/src/test/java/org/fuin/esc/api/StreamDeletedExceptionTest.java index 7197bd95..2186a5f7 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamDeletedExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamDeletedExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link StreamDeletedException} class. */ -// CHECKSTYLE:OFF Test public class StreamDeletedExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -67,4 +66,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamEventsSliceTest.java b/api/src/test/java/org/fuin/esc/api/StreamEventsSliceTest.java index b949c8be..9191d552 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamEventsSliceTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamEventsSliceTest.java @@ -1,25 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.api; import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.JsonObject; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -34,7 +32,6 @@ /** * Tests the {@link StreamEventsSlice} class. */ -// CHECKSTYLE:OFF Test public class StreamEventsSliceTest { private static final int FROM = 0; @@ -51,7 +48,7 @@ public class StreamEventsSliceTest { public static void beforeClass() throws MimeTypeParseException { final TypeName dataType = new TypeName("MyEvent"); final TypeName metaType = new TypeName("MyMeta"); - final JsonObject meta = Json.createObjectBuilder().add("ip", "127.0.0.1").build(); + final String meta = "{ \"ip\" : \"127.0.0.1\" }"; events = new ArrayList(); events.add(new SimpleCommonEvent(new EventId(), dataType, new MyEvent("Peter"), metaType, meta)); events.add(new SimpleCommonEvent(new EventId(), dataType, new MyEvent("Mary Jane"), metaType, meta)); @@ -71,7 +68,7 @@ public void teardown() { public void testNullList() { assertThat(new StreamEventsSlice(FROM, null, NEXT, EOS).getEvents()).isEmpty(); } - + @Test public void testEqualsHashCode() { EqualsVerifier.forClass(StreamEventsSlice.class).verify(); @@ -87,4 +84,4 @@ public void testGetter() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamNotFoundExceptionTest.java b/api/src/test/java/org/fuin/esc/api/StreamNotFoundExceptionTest.java index ccb67e09..5f379124 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamNotFoundExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamNotFoundExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link StreamNotFoundException} class. */ -// CHECKSTYLE:OFF Test public class StreamNotFoundExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -67,4 +66,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamReadOnlyExceptionTest.java b/api/src/test/java/org/fuin/esc/api/StreamReadOnlyExceptionTest.java index fabd4659..fbc00461 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamReadOnlyExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamReadOnlyExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link StreamReadOnlyException} class. */ -// CHECKSTYLE:OFF Test public class StreamReadOnlyExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -67,4 +66,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamStateTest.java b/api/src/test/java/org/fuin/esc/api/StreamStateTest.java index 7289a3f7..3494a481 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamStateTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamStateTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF Test code + public final class StreamStateTest { @Test @@ -34,4 +34,4 @@ public final void testFromDbValue() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/StreamVersionConflictExceptionTest.java b/api/src/test/java/org/fuin/esc/api/StreamVersionConflictExceptionTest.java index 0782f727..bd5c8056 100644 --- a/api/src/test/java/org/fuin/esc/api/StreamVersionConflictExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/StreamVersionConflictExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link WrongExpectedVersionException} class. */ -// CHECKSTYLE:OFF Test public class StreamVersionConflictExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -76,4 +75,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/SubscriptionTest.java b/api/src/test/java/org/fuin/esc/api/SubscriptionTest.java index 3ecf17b0..e68b9cce 100644 --- a/api/src/test/java/org/fuin/esc/api/SubscriptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/SubscriptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,27 +21,27 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF Test code + public final class SubscriptionTest { @Test public final void testConstruction() { - + // PREPARE final StreamId streamId = new SimpleStreamId("stream1"); final Long lastEventNumber = 1L; - + // TEST final Subscription testee = new Subscription(streamId, lastEventNumber) { private static final long serialVersionUID = 1L; }; - + // VERIFY assertThat(testee.getStreamId()).isEqualTo(streamId); assertThat(testee.getLastEventNumber()).isEqualTo(lastEventNumber); - + } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/TypeNameTest.java b/api/src/test/java/org/fuin/esc/api/TypeNameTest.java index 16113976..ca0166e2 100644 --- a/api/src/test/java/org/fuin/esc/api/TypeNameTest.java +++ b/api/src/test/java/org/fuin/esc/api/TypeNameTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -25,7 +25,7 @@ import static org.fuin.utils4j.Utils4J.deserialize; import static org.fuin.utils4j.Utils4J.serialize; -// CHECKSTYLE:OFF Test code + public final class TypeNameTest { @Test @@ -58,4 +58,4 @@ public final void testConstructEmpty() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/java/org/fuin/esc/api/WrongExpectedVersionExceptionTest.java b/api/src/test/java/org/fuin/esc/api/WrongExpectedVersionExceptionTest.java index 5733b80d..f7ab8efe 100644 --- a/api/src/test/java/org/fuin/esc/api/WrongExpectedVersionExceptionTest.java +++ b/api/src/test/java/org/fuin/esc/api/WrongExpectedVersionExceptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,7 +28,6 @@ /** * Tests the {@link WrongExpectedVersionException} class. */ -// CHECKSTYLE:OFF Test public class WrongExpectedVersionExceptionTest { private static final StreamId STREAM_ID = new SimpleStreamId("MyStream"); @@ -75,4 +74,4 @@ public void testSerializeDeserialize() { } } -// CHECKSTYLE:ON + diff --git a/api/src/test/resources/logback-test.xml b/api/src/test/resources/logback-test.xml index 6062cc03..7078062a 100644 --- a/api/src/test/resources/logback-test.xml +++ b/api/src/test/resources/logback-test.xml @@ -1,18 +1,18 @@ - - - %d{yyyy.dd.MM HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - + + + %d{yyyy.dd.MM HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + - - - + + + - + diff --git a/client/pom.xml b/client/pom.xml new file mode 100644 index 00000000..c06a2c5f --- /dev/null +++ b/client/pom.xml @@ -0,0 +1,136 @@ + + + + 4.0.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + + + esc-client + jar + Functionality used by clients + + + + + + + org.fuin.esc + esc-api + + + + org.fuin + utils4j + + + + io.smallrye + jandex + + + + org.slf4j + slf4j-api + + + + jakarta.validation + jakarta.validation-api + + + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.fuin.objects4j + objects4j-common + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + + + **/* + + + + org.fuin.esc.client + + + + + + + org.apache.maven.plugins + maven-jdeps-plugin + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + + + + + + + diff --git a/api/src/main/java/org/fuin/esc/api/JandexSerializedDataTypeRegistry.java b/client/src/main/java/org/fuin/esc/client/JandexSerializedDataTypeRegistry.java similarity index 84% rename from api/src/main/java/org/fuin/esc/api/JandexSerializedDataTypeRegistry.java rename to client/src/main/java/org/fuin/esc/client/JandexSerializedDataTypeRegistry.java index 713b29a5..8e81cf91 100644 --- a/api/src/main/java/org/fuin/esc/api/JandexSerializedDataTypeRegistry.java +++ b/client/src/main/java/org/fuin/esc/client/JandexSerializedDataTypeRegistry.java @@ -1,15 +1,29 @@ -package org.fuin.esc.api; +package org.fuin.esc.client; import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.HasSerializedDataTypeConstantValidator; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; import org.fuin.utils4j.jandex.JandexIndexFileReader; import org.fuin.utils4j.jandex.JandexUtils; -import org.jboss.jandex.*; +import org.jboss.jandex.AnnotationInstance; +import org.jboss.jandex.ClassInfo; +import org.jboss.jandex.CompositeIndex; +import org.jboss.jandex.DotName; +import org.jboss.jandex.IndexView; +import org.jboss.jandex.Indexer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.lang.reflect.Modifier; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; /** * Registry that is built up by scanning for classes that are annotated with {@link HasSerializedDataTypeConstant}. diff --git a/api/src/test/java/org/fuin/esc/api/JandexSerializedDataTypeRegistryTest.java b/client/src/test/java/org/fuin/esc/client/JandexSerializedDataTypeRegistryTest.java similarity index 96% rename from api/src/test/java/org/fuin/esc/api/JandexSerializedDataTypeRegistryTest.java rename to client/src/test/java/org/fuin/esc/client/JandexSerializedDataTypeRegistryTest.java index 1083f1e8..ce8a7ee6 100644 --- a/api/src/test/java/org/fuin/esc/api/JandexSerializedDataTypeRegistryTest.java +++ b/client/src/test/java/org/fuin/esc/client/JandexSerializedDataTypeRegistryTest.java @@ -1,4 +1,4 @@ -package org.fuin.esc.api; +package org.fuin.esc.client; import org.junit.jupiter.api.Test; diff --git a/client/src/test/java/org/fuin/esc/client/MyEvent.java b/client/src/test/java/org/fuin/esc/client/MyEvent.java new file mode 100644 index 00000000..564d5555 --- /dev/null +++ b/client/src/test/java/org/fuin/esc/client/MyEvent.java @@ -0,0 +1,139 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.client; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.io.Serializable; +import java.util.UUID; + +/** + * Something interesting happened. Equals and hash code are based on the UUID. + */ +@HasSerializedDataTypeConstant +public final class MyEvent implements Serializable { + + private static final long serialVersionUID = 100L; + + /** Unique name of the event. */ + public static final TypeName TYPE = new TypeName("MyEvent"); + + /** Unique name of the serialized event. */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + private String id; + + private String description; + + /** + * Protected default constructor for JAXB. + */ + protected MyEvent() { + super(); + } + + /** + * Constructor with random UUID. + * + * @param description + * The description. + */ + public MyEvent(@NotEmpty final String description) { + super(); + Contract.requireArgNotEmpty("description", description); + this.id = UUID.randomUUID().toString(); + this.description = description; + } + + /** + * Constructor with all mandatory data. + * + * @param uuid + * The unique identifier of the event. + * @param description + * The description. + */ + public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { + super(); + Contract.requireArgNotNull("uuid", uuid); + Contract.requireArgNotEmpty("description", description); + this.id = uuid.toString(); + this.description = description; + } + + /** + * Returns the unique identifier. + * + * @return UUID string. + */ + @NotNull + public final String getId() { + return id; + } + + /** + * Returns the description. + * + * @return The description. + */ + @NotEmpty + public final String getDescription() { + return description; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyEvent other = (MyEvent) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + @Override + public final String toString() { + return "My event: " + description; + } + +} diff --git a/esgrpc/README.md b/esgrpc/README.md index 84ad53f3..43e7dc9e 100644 --- a/esgrpc/README.md +++ b/esgrpc/README.md @@ -1,3 +1,5 @@ # esc-esgrpc -Event store commons [gRPC](https://developers.eventstore.com/clients/grpc/) adapter for Greg Young's [Event Store](https://www.eventstore.com/). + +Event store commons [gRPC](https://developers.eventstore.com/clients/grpc/) adapter for Greg +Young's [Event Store](https://www.eventstore.com/). diff --git a/esgrpc/pom.xml b/esgrpc/pom.xml index 135354be..198f14cb 100644 --- a/esgrpc/pom.xml +++ b/esgrpc/pom.xml @@ -1,265 +1,301 @@ - - 4.0.0 - - - org.fuin.esc - esc-parent - 0.8.0-SNAPSHOT - - - esc-esgrpc - jar - esc-esgrpc - Event store commons esgrpc adapter for Greg Young's EventStore. - - - https://github.com/fuinorg/event-store-commons/ - scm:git:git://github.com/fuinorg/event-store-commons.git - - scm:git:git@github.com:fuinorg/event-store-commons.git - - - - GitHub Issues - https://github.com/fuinorg/event-store-commons/issues - - - - - - - - org.fuin.esc - esc-api - - - - org.fuin.esc - esc-spi - - - - org.fuin - utils4j - - - - org.fuin.objects4j - objects4j-core - - - - jakarta.validation - jakarta.validation-api - true - - - - org.apache.commons - commons-lang3 - - - - org.slf4j - slf4j-api - - - - com.eventstore - db-client-java - 5.2.0 - - - - io.grpc - grpc-api - 1.59.0 - - - - com.google.protobuf - protobuf-java - 3.22.2 - - - - com.google.protobuf - protobuf-java-util - 3.24.4 - - - - io.grpc - grpc-protobuf - 1.59.0 - - - - - - org.junit.jupiter - junit-jupiter - test - - - - org.assertj - assertj-core - test - - - - commons-io - commons-io - test - - - - nl.jqno.equalsverifier - equalsverifier - test - - - - ch.qos.logback - logback-classic - test - - - - org.hibernate.validator - hibernate-validator - test - - - - jakarta.json - jakarta.json-api - - - - org.eclipse - yasson - - - - org.glassfish.jaxb - jaxb-runtime - test - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - **/* - - - - org.fuin.esc.esgrpc - - - - - - - org.apache.maven.plugins - maven-jdeps-plugin - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - io.fabric8 - docker-maven-plugin - - - - - eventstore/eventstore:${eventstore.version} - - - bridge - - - 1113:1113 - 2113:2113 - - - TRUE - All - true - true - true - /tmp/log-eventstore - - - false - - - - - http://localhost:2113/web/index.html#/ - GET - - - - - - - - - - - - start-images - pre-integration-test - - start - - - - stop-images - post-integration-test - - stop - - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + 4.0.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + + + esc-esgrpc + jar + esc-esgrpc + Event store commons esgrpc adapter for Greg Young's EventStore. + + + https://github.com/fuinorg/event-store-commons/ + scm:git:git://github.com/fuinorg/event-store-commons.git + + scm:git:git@github.com:fuinorg/event-store-commons.git + + + + + GitHub Issues + https://github.com/fuinorg/event-store-commons/issues + + + + + + + + org.fuin.esc + esc-api + + + + org.fuin.esc + esc-spi + + + + jakarta.validation + jakarta.validation-api + + + + com.eventstore + db-client-java + 5.2.0 + + + + io.grpc + grpc-api + 1.59.0 + + + + jakarta.annotation + jakarta.annotation-api + + + + org.fuin.objects4j + objects4j-common + + + + + + org.fuin.esc + esc-jaxb + test + + + + org.fuin.esc + esc-jsonb + test + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.hibernate.validator + hibernate-validator + test + + + + jakarta.json + jakarta.json-api + test + + + + org.eclipse + yasson + test + + + + org.glassfish.jaxb + jaxb-runtime + test + + + + net.javacrumbs.json-unit + json-unit-fluent + test + + + + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 + test + + + + org.fuin + units4j + test + + + + jakarta.xml.bind + jakarta.xml.bind-api + test + + + + jakarta.json.bind + jakarta.json.bind-api + test + + + + org.fuin + utils4j + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + + + **/* + + + + org.fuin.esc.esgrpc + + + + + + + org.apache.maven.plugins + maven-jdeps-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + io.fabric8 + docker-maven-plugin + + + + + eventstore/eventstore:${eventstore.version} + + + bridge + + + 1113:1113 + 2113:2113 + + + TRUE + All + true + true + true + /tmp/log-eventstore + + + false + + + + + http://localhost:2113/web/index.html#/ + + GET + + + + + + + + + + + + start-images + pre-integration-test + + start + + + + stop-images + post-integration-test + + stop + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.glassfish.jaxb:jaxb-runtime + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + + + + + diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverter.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverter.java index ef47b7f3..579c09cc 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverter.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverter.java @@ -1,133 +1,137 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import java.nio.charset.Charset; - +import com.eventstore.dbclient.EventData; +import com.eventstore.dbclient.EventDataBuilder; +import jakarta.validation.constraints.NotNull; import org.fuin.esc.api.CommonEvent; -import org.fuin.esc.spi.Base64Data; import org.fuin.esc.api.Converter; import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.EscMeta; -import org.fuin.esc.spi.EscSpiUtils; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.IEscMeta; import org.fuin.esc.api.SerializedDataType; import org.fuin.esc.api.Serializer; import org.fuin.esc.api.SerializerRegistry; +import org.fuin.esc.spi.EscSpiUtils; import org.fuin.objects4j.common.Contract; -import com.eventstore.dbclient.EventData; -import com.eventstore.dbclient.EventDataBuilder; - -import jakarta.validation.constraints.NotNull; +import java.nio.charset.StandardCharsets; /** * Converts a {@link CommonEvent} into {@link EventData}. */ public final class CommonEvent2EventDataConverter implements Converter { - private static final EnhancedMimeType XML_UTF8 = EnhancedMimeType.create("application", "xml", - Charset.forName("utf-8")); - - private static final EnhancedMimeType JSON_UTF8 = EnhancedMimeType.create("application", "json", - Charset.forName("utf-8"));; - - private final SerializerRegistry serRegistry; - - private final EnhancedMimeType targetContentType; - - /** - * Constructor with all mandatory data. - * - * @param serRegistry Registry used to locate serializers. - * @param targetContentType Target content type (Allows only 'application/xml' - * or 'application/json' with 'utf-8' encoding). - */ - public CommonEvent2EventDataConverter(@NotNull final SerializerRegistry serRegistry, - final EnhancedMimeType targetContentType) { - super(); - Contract.requireArgNotNull("serRegistry", serRegistry); - Contract.requireArgNotNull("targetContentType", targetContentType); - if (!(targetContentType.matchEncoding(JSON_UTF8) || targetContentType.matchEncoding(XML_UTF8))) { - throw new IllegalArgumentException( - "Only 'application/xml' or 'application/json' with 'utf-8' encoding is allowed, but was: " - + targetContentType); - } - this.serRegistry = serRegistry; - this.targetContentType = targetContentType; - } - - /** - * Converts a common event into event data. - * - * @param commonEvent Event to convert. - * - * @return Converted event as event data. - */ - @Override - public final EventData convert(final CommonEvent commonEvent) { - - // User's data - final String dataType = commonEvent.getDataType().asBaseType(); - final SerializedDataType serUserDataType = new SerializedDataType(dataType); - final Serializer userDataSerializer = serRegistry.getSerializer(serUserDataType); - final byte[] serUserData = userDataSerializer.marshal(commonEvent.getData(), serUserDataType); - final byte[] serData; - if (userDataSerializer.getMimeType().matchEncoding(targetContentType)) { - serData = serUserData; - } else { - final Base64Data base64data = new Base64Data(serUserData); - final Serializer base64Serializer = serRegistry.getSerializer(Base64Data.SER_TYPE); - serData = base64Serializer.marshal(base64data, Base64Data.SER_TYPE); - } - - // EscMeta - final EscMeta escMeta = EscSpiUtils.createEscMeta(serRegistry, targetContentType, commonEvent); - final SerializedDataType escMetaType = new SerializedDataType(EscMeta.TYPE.asBaseType()); - final Serializer escMetaSerializer = getSerializer(escMetaType); - final byte[] escSerMeta = escMetaSerializer.marshal(escMeta, escMetaType); - - // Create event data - if (targetContentType.isJson()) { - return EventDataBuilder.json(commonEvent.getId().asBaseType(), dataType, serData) - .metadataAsBytes(escSerMeta).build(); - } - return EventDataBuilder.binary(commonEvent.getId().asBaseType(), dataType, serData) - .metadataAsBytes(escSerMeta).build(); - - } - - private Serializer getSerializer(final SerializedDataType serDataType) { - final Serializer serializer = serRegistry.getSerializer(serDataType); - if (!serializer.getMimeType().matchEncoding(targetContentType)) { - throw new IllegalArgumentException("Target content type is '" + targetContentType - + "', but serializer returned for " + serDataType + "' was: " + serializer.getMimeType()); - } - return serializer; - } - - @Override - public final Class getSourceType() { - return CommonEvent.class; - } - - @Override - public final Class getTargetType() { - return EventData.class; - } + private static final EnhancedMimeType XML_UTF8 = EnhancedMimeType.create("application", "xml", + StandardCharsets.UTF_8); + + private static final EnhancedMimeType JSON_UTF8 = EnhancedMimeType.create("application", "json", + StandardCharsets.UTF_8); + + private final SerializerRegistry serRegistry; + + private final IBaseTypeFactory baseTypeFactory; + + private final EnhancedMimeType targetContentType; + + /** + * Constructor with all mandatory data. + * + * @param serRegistry Registry used to locate serializers. + * @param baseTypeFactory Factory used to create basic types. + * @param targetContentType Target content type (Allows only 'application/xml' + * or 'application/json' with 'utf-8' encoding). + */ + public CommonEvent2EventDataConverter(@NotNull final SerializerRegistry serRegistry, + @NotNull final IBaseTypeFactory baseTypeFactory, + final EnhancedMimeType targetContentType) { + super(); + Contract.requireArgNotNull("serRegistry", serRegistry); + Contract.requireArgNotNull("baseTypeFactory", baseTypeFactory); + Contract.requireArgNotNull("targetContentType", targetContentType); + if (!(targetContentType.matchEncoding(JSON_UTF8) || targetContentType.matchEncoding(XML_UTF8))) { + throw new IllegalArgumentException( + "Only 'application/xml' or 'application/json' with 'utf-8' encoding is allowed, but was: " + + targetContentType); + } + this.serRegistry = serRegistry; + this.baseTypeFactory = baseTypeFactory; + this.targetContentType = targetContentType; + } + + /** + * Converts a common event into event data. + * + * @param commonEvent Event to convert. + * @return Converted event as event data. + */ + @Override + public EventData convert(final CommonEvent commonEvent) { + + // User's data + final String dataType = commonEvent.getDataType().asBaseType(); + final SerializedDataType serUserDataType = new SerializedDataType(dataType); + final Serializer userDataSerializer = serRegistry.getSerializer(serUserDataType); + final byte[] serUserData = userDataSerializer.marshal(commonEvent.getData(), serUserDataType); + final byte[] serData; + if (userDataSerializer.getMimeType().matchEncoding(targetContentType)) { + serData = serUserData; + } else { + final IBase64Data base64data = baseTypeFactory.createBase64Data(serUserData); + final Serializer base64Serializer = serRegistry.getSerializer(IBase64Data.SER_TYPE); + serData = base64Serializer.marshal(base64data, IBase64Data.SER_TYPE); + } + + // EscMeta + final IEscMeta escMeta = EscSpiUtils.createEscMeta(serRegistry, baseTypeFactory, targetContentType, commonEvent); + final SerializedDataType escMetaType = new SerializedDataType(IEscMeta.TYPE.asBaseType()); + final Serializer escMetaSerializer = getSerializer(escMetaType); + final byte[] escSerMeta = escMetaSerializer.marshal(escMeta, escMetaType); + + // Create event data + if (targetContentType.isJson()) { + return EventDataBuilder.json(commonEvent.getId().asBaseType(), dataType, serData) + .metadataAsBytes(escSerMeta).build(); + } + return EventDataBuilder.binary(commonEvent.getId().asBaseType(), dataType, serData) + .metadataAsBytes(escSerMeta).build(); + + } + + private Serializer getSerializer(final SerializedDataType serDataType) { + final Serializer serializer = serRegistry.getSerializer(serDataType); + if (!serializer.getMimeType().matchEncoding(targetContentType)) { + throw new IllegalArgumentException("Target content type is '" + targetContentType + + "', but serializer returned for " + serDataType + "' was: " + serializer.getMimeType()); + } + return serializer; + } + + @Override + public Class getSourceType() { + return CommonEvent.class; + } + + @Override + public Class getTargetType() { + return EventData.class; + } } diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/ESGrpcEventStore.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/ESGrpcEventStore.java index a2439f6a..7c36b7fa 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/ESGrpcEventStore.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/ESGrpcEventStore.java @@ -1,32 +1,43 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import static org.fuin.esc.api.ExpectedVersion.ANY; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ExecutionException; - +import com.eventstore.dbclient.AppendToStreamOptions; +import com.eventstore.dbclient.DeleteStreamOptions; +import com.eventstore.dbclient.EventData; +import com.eventstore.dbclient.EventStoreDBClient; +import com.eventstore.dbclient.ExpectedRevision; +import com.eventstore.dbclient.ReadResult; +import com.eventstore.dbclient.ReadStreamOptions; +import com.eventstore.dbclient.ResolvedEvent; +import com.eventstore.dbclient.WriteResult; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.EventNotFoundException; import org.fuin.esc.api.ExpectedVersion; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.SerDeserializerRegistry; +import org.fuin.esc.api.SerializerRegistry; import org.fuin.esc.api.StreamAlreadyExistsException; import org.fuin.esc.api.StreamDeletedException; import org.fuin.esc.api.StreamEventsSlice; @@ -37,511 +48,487 @@ import org.fuin.esc.api.TenantId; import org.fuin.esc.api.WrongExpectedVersionException; import org.fuin.esc.spi.AbstractReadableEventStore; -import org.fuin.esc.api.DeserializerRegistry; -import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.spi.EscSpiUtils; -import org.fuin.esc.api.SerDeserializerRegistry; -import org.fuin.esc.api.SerializerRegistry; import org.fuin.esc.spi.TenantStreamId; import org.fuin.objects4j.common.Contract; -import jakarta.annotation.Nullable; -import com.eventstore.dbclient.AppendToStreamOptions; -import com.eventstore.dbclient.DeleteStreamOptions; -import com.eventstore.dbclient.EventData; -import com.eventstore.dbclient.EventStoreDBClient; -import com.eventstore.dbclient.ExpectedRevision; -import com.eventstore.dbclient.ReadResult; -import com.eventstore.dbclient.ReadStreamOptions; -import com.eventstore.dbclient.ResolvedEvent; -import com.eventstore.dbclient.WriteResult; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ExecutionException; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import jakarta.validation.constraints.NotNull; +import static org.fuin.esc.api.ExpectedVersion.ANY; /** - * Implementation that connects to the event store - * (http://www.geteventstore.com) using the esjc - * (https://github.com/msemys/esjc) API. + * Implementation that connects to the event store (Eventstore) using the GRPC API. */ public final class ESGrpcEventStore extends AbstractReadableEventStore implements IESGrpcEventStore { - private final EventStoreDBClient es; - - private final CommonEvent2EventDataConverter ce2edConv; - - private final RecordedEvent2CommonEventConverter ed2ceConv; - - private final TenantId tenantId; - - private boolean open; - - /** - * Constructor without a tenant. - * - * @param es Delegate. - * @param serRegistry Registry used to locate serializers. - * @param desRegistry Registry used to locate deserializers. - * @param targetContentType Target content type (Allows only 'application/xml' - * or 'application/json' with 'utf-8' encoding). - * - * @deprecated Use the Builder in this class instead. - */ - @Deprecated - public ESGrpcEventStore(@NotNull final EventStoreDBClient es, @NotNull final SerializerRegistry serRegistry, - @NotNull final DeserializerRegistry desRegistry, @NotNull final EnhancedMimeType targetContentType) { - this(es, serRegistry, desRegistry, targetContentType, null); - } - - /** - * Private constructor with all data used by the builder. - * - * @param es Delegate. - * @param serRegistry Registry used to locate serializers. - * @param desRegistry Registry used to locate deserializers. - * @param targetContentType Target content type (Allows only 'application/xml' - * or 'application/json' with 'utf-8' encoding). - * @param tenantId Unique tenant identifier. - */ - private ESGrpcEventStore(@NotNull final EventStoreDBClient es, @NotNull final SerializerRegistry serRegistry, - @NotNull final DeserializerRegistry desRegistry, @NotNull final EnhancedMimeType targetContentType, - @Nullable final TenantId tenantId) { - super(); - Contract.requireArgNotNull("es", es); - Contract.requireArgNotNull("serRegistry", serRegistry); - Contract.requireArgNotNull("desRegistry", desRegistry); - Contract.requireArgNotNull("targetContentType", targetContentType); - this.es = es; - this.ce2edConv = new CommonEvent2EventDataConverter(serRegistry, targetContentType); - this.ed2ceConv = new RecordedEvent2CommonEventConverter(desRegistry); - this.tenantId = tenantId; - this.open = false; - } - - @Override - public final ESGrpcEventStore open() { - if (open) { - // Ignore - return this; - } - this.open = true; - return this; - } - - @Override - public final void close() { - if (!open) { - // Ignore - return; - } - this.open = false; - } - - @Override - public final boolean isSupportsCreateStream() { - return false; - } - - @Override - public final void createStream(final StreamId streamId) throws StreamAlreadyExistsException { - // Do nothing as the operation is not supported - } - - @Override - public final long appendToStream(final StreamId streamId, final CommonEvent... events) - throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException { - return appendToStream(streamId, -2, EscSpiUtils.asList(events)); - } - - @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, final CommonEvent... events) - throws StreamNotFoundException, StreamDeletedException, WrongExpectedVersionException, - StreamReadOnlyException { - return appendToStream(streamId, expectedVersion, EscSpiUtils.asList(events)); - } - - @Override - public long appendToStream(final StreamId streamId, final List events) - throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException { - return appendToStream(streamId, -2, events); - } - - @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, - final List commonEvents) - throws StreamDeletedException, WrongExpectedVersionException, StreamReadOnlyException { - - Contract.requireArgNotNull("streamId", streamId); - Contract.requireArgMin("expectedVersion", expectedVersion, ExpectedVersion.ANY.getNo()); - Contract.requireArgNotNull("commonEvents", commonEvents); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - - if (sid.isProjection()) { - throw new StreamReadOnlyException(sid); - } - - try { - final Iterator eventDataIt = asEventData(commonEvents).iterator(); - final WriteResult result = es.appendToStream(sid.asString(), - AppendToStreamOptions.get().expectedRevision(ExpectedRevision.fromRawLong(expectedVersion)), eventDataIt).get(); - return result.getNextExpectedRevision().toRawLong(); - } catch (final ExecutionException ex) { - if (ex.getCause() instanceof com.eventstore.dbclient.WrongExpectedVersionException) { - com.eventstore.dbclient.WrongExpectedVersionException cause = (com.eventstore.dbclient.WrongExpectedVersionException) ex - .getCause(); - throw new WrongExpectedVersionException(sid, expectedVersion, cause.getActualVersion().toRawLong()); - } - if (statusIsDeleted(ex)) { - throw new StreamDeletedException(sid); - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - throw new StreamNotFoundException(sid); - } - throw new RuntimeException("Error executing appendToStream(..)", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for appendToStream(..) result", ex); - } - - } - - @Override - public final void deleteStream(final StreamId streamId, final long expectedVersion, final boolean hardDelete) - throws StreamDeletedException, WrongExpectedVersionException { - - Contract.requireArgNotNull("streamId", streamId); - Contract.requireArgMin("expectedVersion", expectedVersion, ExpectedVersion.ANY.getNo()); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - - if (sid.isProjection()) { - throw new StreamReadOnlyException(sid); - } - - try { - final DeleteStreamOptions options = DeleteStreamOptions.get().expectedRevision(ExpectedRevision.fromRawLong(expectedVersion)); - if (hardDelete) { - es.tombstoneStream(sid.asString(), options).get(); - } else { - es.deleteStream(sid.asString(), options).get(); - } - } catch (final ExecutionException ex) { - if (ex.getCause() instanceof com.eventstore.dbclient.WrongExpectedVersionException) { - com.eventstore.dbclient.WrongExpectedVersionException cause = (com.eventstore.dbclient.WrongExpectedVersionException) ex - .getCause(); - throw new WrongExpectedVersionException(sid, expectedVersion, cause.getActualVersion().toRawLong()); - } - if (statusIsDeleted(ex)) { - throw new StreamDeletedException(sid); - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - throw new StreamNotFoundException(sid); - } - throw new RuntimeException("Error executing deleteStream(..)", ex); - } catch (final InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for deleteStream(..) result", ex); - } - - } - - @Override - public final void deleteStream(final StreamId streamId, final boolean hardDelete) - throws StreamNotFoundException, StreamDeletedException { - - deleteStream(streamId, ANY.getNo(), hardDelete); - - } - - @Override - public final StreamEventsSlice readEventsForward(final StreamId streamId, final long start, final int count) { - - Contract.requireArgNotNull("streamId", streamId); - Contract.requireArgMin("start", start, 0); - Contract.requireArgMin("count", count, 1); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - try { - - final ReadStreamOptions options = ReadStreamOptions.get().forwards().fromRevision(start).maxCount(count) - .resolveLinkTos(); - - final ReadResult readResult = es.readStream(sid.asString(), options).get(); - final List events = asCommonEvents(readResult.getEvents()); - final boolean endOfStream = count > events.size(); - return new StreamEventsSlice(start, events, start + events.size(), endOfStream); - } catch (ExecutionException ex) { - if (statusIsDeleted(ex)) { - throw new StreamDeletedException(sid); - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - throw new StreamNotFoundException(sid); - } - throw new RuntimeException("Error executing readEventsForward(..)", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for readEventsForward(..) result", ex); - } - - } - - @Override - public final StreamEventsSlice readEventsBackward(final StreamId streamId, final long start, final int count) { - - Contract.requireArgNotNull("streamId", streamId); - Contract.requireArgMin("start", start, 0); - Contract.requireArgMin("count", count, 1); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - try { - final ReadStreamOptions options = ReadStreamOptions.get().backwards().fromRevision(start).maxCount(count) - .resolveLinkTos(); - final ReadResult slice = es.readStream(sid.asString(), options).get(); - final List events = asCommonEvents(slice.getEvents()); - long nextEventNumber = start - events.size(); - final boolean endOfStream = (start - count < 0); - if (endOfStream) { - nextEventNumber = 0; - } - return new StreamEventsSlice(start, events, nextEventNumber, endOfStream); - } catch (ExecutionException ex) { - if (statusIsDeleted(ex)) { - throw new StreamDeletedException(sid); - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - throw new StreamNotFoundException(sid); - } - throw new RuntimeException("Error executing readEventsBackward(..)", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for readEventsBackward(..) result", ex); - } - - } - - @Override - public final CommonEvent readEvent(final StreamId streamId, final long eventNumber) { - final StreamEventsSlice slice = readEventsForward(streamId, eventNumber, 1); - if (slice.getEvents().isEmpty()) { - throw new EventNotFoundException(streamId, eventNumber); - } - return slice.getEvents().get(0); - } - - @Override - public final boolean streamExists(final StreamId streamId) { - - Contract.requireArgNotNull("streamId", streamId); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - try { - final ReadStreamOptions options = ReadStreamOptions.get().forwards().fromRevision(0).maxCount(1); - es.readStream(sid.asString(), options).get(); - return true; - } catch (ExecutionException ex) { - if (ex.getCause() instanceof StatusRuntimeException) { - return false; - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - return false; - } - throw new RuntimeException("Error executing streamExists(..)", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for streamExists(..) result", ex); - } - - } - - @Override - public final StreamState streamState(final StreamId streamId) { - - Contract.requireArgNotNull("streamId", streamId); - ensureOpen(); - - final TenantStreamId sid = new TenantStreamId(tenantId, streamId); - try { - es.readStream(sid.asString(), ReadStreamOptions.get().forwards().fromRevision(0)).get(); - return StreamState.ACTIVE; - } catch (ExecutionException ex) { - if (statusIsDeleted(ex)) { - return StreamState.HARD_DELETED; - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - return softDeleted(streamId); - } - throw new RuntimeException("Error executing streamState(..)", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error waiting for streamState(..) result", ex); - } - - } - - private StreamState softDeleted(final StreamId streamId) { - // Workaround for reading meta data because of: - // https://github.com/EventStore/EventStoreDB-Client-Java/issues/240 - try { - es.readStream("$$" + streamId.asString(), ReadStreamOptions.get().forwards().fromRevision(0)).get(); - throw new StreamNotFoundException(streamId); - } catch (ExecutionException ex) { - if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { - throw new StreamNotFoundException(streamId); - } - throw new RuntimeException("Error reading stream meta data", ex); - } catch (InterruptedException ex) { // NOSONAR - throw new RuntimeException("Error reading stream status", ex); - } - } - - private List asEventData(final List commonEvents) { - final List list = new ArrayList<>(commonEvents.size()); - for (final CommonEvent commonEvent : commonEvents) { - list.add(ce2edConv.convert(commonEvent)); - } - return list; - } - - private List asCommonEvents(final List resolvedEvents) { - final List list = new ArrayList<>(resolvedEvents.size()); - for (final ResolvedEvent resolvedEvent : resolvedEvents) { - list.add(asCommonEvent(resolvedEvent)); - } - return list; - } - - private CommonEvent asCommonEvent(final ResolvedEvent resolvedEvent) { - return ed2ceConv.convert(resolvedEvent.getEvent()); - } - - private void ensureOpen() { - if (!open) { - open(); - } - } - - private boolean statusIsDeleted(ExecutionException ex) { - if (ex.getCause() instanceof StatusRuntimeException) { - final StatusRuntimeException sre = (StatusRuntimeException) ex.getCause(); - return sre.getStatus().getCode().equals(Status.FAILED_PRECONDITION.getCode()) - && sre.getStatus().getDescription().contains("is deleted"); - } - if (ex.getCause() instanceof com.eventstore.dbclient.StreamDeletedException) { - return true; - } - return false; - } - - /** - * Builder used to create a new instance of the event store. - */ - public static final class Builder { - - private com.eventstore.dbclient.EventStoreDBClient eventStore; - - private SerializerRegistry serRegistry; - - private DeserializerRegistry desRegistry; - - private EnhancedMimeType targetContentType; - - private TenantId tenantId; - - /** - * Sets the event store to use internally. - * - * @param eventStore TCP/IP event store connection. - * - * @return Builder. - */ - public Builder eventStore(com.eventstore.dbclient.EventStoreDBClient eventStore) { - this.eventStore = eventStore; - return this; - } - - /** - * Sets the serializer registry. - * - * @param serRegistry Registry used to locate serializers. - * - * @return Builder. - */ - public Builder serRegistry(final SerializerRegistry serRegistry) { - this.serRegistry = serRegistry; - return this; - } - - /** - * Sets the deserializer registry. - * - * @param desRegistry Registry used to locate deserializers. - * - * @return Builder. - */ - public Builder desRegistry(final DeserializerRegistry desRegistry) { - this.desRegistry = desRegistry; - return this; - } - - /** - * Sets both types of registries in one call. - * - * @param registry Serializer/Deserializer registry to set. - * - * @return Builder. - */ - public Builder serDesRegistry(final SerDeserializerRegistry registry) { - this.serRegistry = registry; - this.desRegistry = registry; - return this; - } - - /** - * Sets the target content type. - * - * @param targetContentType Target content type (Allows only 'application/xml' - * or 'application/json' with 'utf-8' encoding). - * - * @return Builder. - */ - public Builder targetContentType(final EnhancedMimeType targetContentType) { - this.targetContentType = targetContentType; - return this; - } - - /** - * Sets the tenant identifier. - * - * @param tenantId Unique tenant identifier. - * - * @return Builder - */ - public Builder tenantId(final TenantId tenantId) { - this.tenantId = tenantId; - return this; - } - - private void verifyNotNull(final String name, final Object value) { - if (value == null) { - throw new IllegalStateException( - "It is mandatory to set the value of '" + name + "' before calling the 'build()' method"); - } - } - - /** - * Creates a new instance of the event store from the attributes set via the - * builder. - * - * @return New event store instance. - */ - public ESGrpcEventStore build() { - verifyNotNull("eventStore", eventStore); - verifyNotNull("serRegistry", serRegistry); - verifyNotNull("desRegistry", desRegistry); - verifyNotNull("targetContentType", targetContentType); - return new ESGrpcEventStore(eventStore, serRegistry, desRegistry, targetContentType, tenantId); - } - - } + private final EventStoreDBClient es; + + private final CommonEvent2EventDataConverter ce2edConv; + + private final RecordedEvent2CommonEventConverter ed2ceConv; + + private final TenantId tenantId; + + private boolean open; + + /** + * Private constructor with all data used by the builder. + * + * @param es Delegate. + * @param serRegistry Registry used to locate serializers. + * @param desRegistry Registry used to locate deserializers. + * @param baseTypeFactory Factory used to create basic types. + * @param targetContentType Target content type (Allows only 'application/xml' + * or 'application/json' with 'utf-8' encoding). + * @param tenantId Unique tenant identifier. + */ + private ESGrpcEventStore(@NotNull final EventStoreDBClient es, + @NotNull final SerializerRegistry serRegistry, + @NotNull final DeserializerRegistry desRegistry, + @NotNull final IBaseTypeFactory baseTypeFactory, + @NotNull final EnhancedMimeType targetContentType, + @Nullable final TenantId tenantId) { + super(); + Contract.requireArgNotNull("es", es); + Contract.requireArgNotNull("serRegistry", serRegistry); + Contract.requireArgNotNull("desRegistry", desRegistry); + Contract.requireArgNotNull("baseTypeFactory", baseTypeFactory); + Contract.requireArgNotNull("targetContentType", targetContentType); + this.es = es; + this.ce2edConv = new CommonEvent2EventDataConverter(serRegistry, baseTypeFactory, targetContentType); + this.ed2ceConv = new RecordedEvent2CommonEventConverter(desRegistry); + this.tenantId = tenantId; + this.open = false; + } + + @Override + public ESGrpcEventStore open() { + if (open) { + // Ignore + return this; + } + this.open = true; + return this; + } + + @Override + public void close() { + if (!open) { + // Ignore + return; + } + this.open = false; + } + + @Override + public boolean isSupportsCreateStream() { + return false; + } + + @Override + public void createStream(final StreamId streamId) throws StreamAlreadyExistsException { + // Do nothing as the operation is not supported + } + + @Override + public long appendToStream(final StreamId streamId, final CommonEvent... events) + throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException { + return appendToStream(streamId, -2, EscSpiUtils.asList(events)); + } + + @Override + public long appendToStream(final StreamId streamId, final long expectedVersion, final CommonEvent... events) + throws StreamNotFoundException, StreamDeletedException, WrongExpectedVersionException, + StreamReadOnlyException { + return appendToStream(streamId, expectedVersion, EscSpiUtils.asList(events)); + } + + @Override + public long appendToStream(final StreamId streamId, final List events) + throws StreamNotFoundException, StreamDeletedException, StreamReadOnlyException { + return appendToStream(streamId, -2, events); + } + + @Override + public long appendToStream(final StreamId streamId, final long expectedVersion, + final List commonEvents) + throws StreamDeletedException, WrongExpectedVersionException, StreamReadOnlyException { + + Contract.requireArgNotNull("streamId", streamId); + Contract.requireArgMin("expectedVersion", expectedVersion, ExpectedVersion.ANY.getNo()); + Contract.requireArgNotNull("commonEvents", commonEvents); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + + if (sid.isProjection()) { + throw new StreamReadOnlyException(sid); + } + + try { + final Iterator eventDataIt = asEventData(commonEvents).iterator(); + final WriteResult result = es.appendToStream(sid.asString(), + AppendToStreamOptions.get().expectedRevision(ExpectedRevision.fromRawLong(expectedVersion)), eventDataIt).get(); + return result.getNextExpectedRevision().toRawLong(); + } catch (final ExecutionException ex) { + if (ex.getCause() instanceof com.eventstore.dbclient.WrongExpectedVersionException cause) { + throw new WrongExpectedVersionException(sid, expectedVersion, cause.getActualVersion().toRawLong()); + } + if (statusIsDeleted(ex)) { + throw new StreamDeletedException(sid); + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + throw new StreamNotFoundException(sid); + } + throw new RuntimeException("Error executing appendToStream(..)", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for appendToStream(..) result", ex); + } + + } + + @Override + public void deleteStream(final StreamId streamId, final long expectedVersion, final boolean hardDelete) + throws StreamDeletedException, WrongExpectedVersionException { + + Contract.requireArgNotNull("streamId", streamId); + Contract.requireArgMin("expectedVersion", expectedVersion, ExpectedVersion.ANY.getNo()); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + + if (sid.isProjection()) { + throw new StreamReadOnlyException(sid); + } + + try { + final DeleteStreamOptions options = DeleteStreamOptions.get().expectedRevision(ExpectedRevision.fromRawLong(expectedVersion)); + if (hardDelete) { + es.tombstoneStream(sid.asString(), options).get(); + } else { + es.deleteStream(sid.asString(), options).get(); + } + } catch (final ExecutionException ex) { + if (ex.getCause() instanceof com.eventstore.dbclient.WrongExpectedVersionException cause) { + throw new WrongExpectedVersionException(sid, expectedVersion, cause.getActualVersion().toRawLong()); + } + if (statusIsDeleted(ex)) { + throw new StreamDeletedException(sid); + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + throw new StreamNotFoundException(sid); + } + throw new RuntimeException("Error executing deleteStream(..)", ex); + } catch (final InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for deleteStream(..) result", ex); + } + + } + + @Override + public void deleteStream(final StreamId streamId, final boolean hardDelete) + throws StreamNotFoundException, StreamDeletedException { + + deleteStream(streamId, ANY.getNo(), hardDelete); + + } + + @Override + public StreamEventsSlice readEventsForward(final StreamId streamId, final long start, final int count) { + + Contract.requireArgNotNull("streamId", streamId); + Contract.requireArgMin("start", start, 0); + Contract.requireArgMin("count", count, 1); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + try { + + final ReadStreamOptions options = ReadStreamOptions.get().forwards().fromRevision(start).maxCount(count) + .resolveLinkTos(); + + final ReadResult readResult = es.readStream(sid.asString(), options).get(); + final List events = asCommonEvents(readResult.getEvents()); + final boolean endOfStream = count > events.size(); + return new StreamEventsSlice(start, events, start + events.size(), endOfStream); + } catch (ExecutionException ex) { + if (statusIsDeleted(ex)) { + throw new StreamDeletedException(sid); + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + throw new StreamNotFoundException(sid); + } + throw new RuntimeException("Error executing readEventsForward(..)", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for readEventsForward(..) result", ex); + } + + } + + @Override + public StreamEventsSlice readEventsBackward(final StreamId streamId, final long start, final int count) { + + Contract.requireArgNotNull("streamId", streamId); + Contract.requireArgMin("start", start, 0); + Contract.requireArgMin("count", count, 1); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + try { + final ReadStreamOptions options = ReadStreamOptions.get().backwards().fromRevision(start).maxCount(count) + .resolveLinkTos(); + final ReadResult slice = es.readStream(sid.asString(), options).get(); + final List events = asCommonEvents(slice.getEvents()); + long nextEventNumber = start - events.size(); + final boolean endOfStream = (start - count < 0); + if (endOfStream) { + nextEventNumber = 0; + } + return new StreamEventsSlice(start, events, nextEventNumber, endOfStream); + } catch (ExecutionException ex) { + if (statusIsDeleted(ex)) { + throw new StreamDeletedException(sid); + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + throw new StreamNotFoundException(sid); + } + throw new RuntimeException("Error executing readEventsBackward(..)", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for readEventsBackward(..) result", ex); + } + + } + + @Override + public CommonEvent readEvent(final StreamId streamId, final long eventNumber) { + final StreamEventsSlice slice = readEventsForward(streamId, eventNumber, 1); + if (slice.getEvents().isEmpty()) { + throw new EventNotFoundException(streamId, eventNumber); + } + return slice.getEvents().get(0); + } + + @Override + public boolean streamExists(final StreamId streamId) { + + Contract.requireArgNotNull("streamId", streamId); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + try { + final ReadStreamOptions options = ReadStreamOptions.get().forwards().fromRevision(0).maxCount(1); + es.readStream(sid.asString(), options).get(); + return true; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof StatusRuntimeException) { + return false; + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + return false; + } + throw new RuntimeException("Error executing streamExists(..)", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for streamExists(..) result", ex); + } + + } + + @Override + public StreamState streamState(final StreamId streamId) { + + Contract.requireArgNotNull("streamId", streamId); + ensureOpen(); + + final TenantStreamId sid = new TenantStreamId(tenantId, streamId); + try { + es.readStream(sid.asString(), ReadStreamOptions.get().forwards().fromRevision(0)).get(); + return StreamState.ACTIVE; + } catch (ExecutionException ex) { + if (statusIsDeleted(ex)) { + return StreamState.HARD_DELETED; + } + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + return softDeleted(streamId); + } + throw new RuntimeException("Error executing streamState(..)", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error waiting for streamState(..) result", ex); + } + + } + + private StreamState softDeleted(final StreamId streamId) { + // Workaround for reading metadata because of: + // https://github.com/EventStore/EventStoreDB-Client-Java/issues/240 + try { + es.readStream("$$" + streamId.asString(), ReadStreamOptions.get().forwards().fromRevision(0)).get(); + throw new StreamNotFoundException(streamId); + } catch (ExecutionException ex) { + if (ex.getCause() instanceof com.eventstore.dbclient.StreamNotFoundException) { + throw new StreamNotFoundException(streamId); + } + throw new RuntimeException("Error reading stream meta data", ex); + } catch (InterruptedException ex) { // NOSONAR + throw new RuntimeException("Error reading stream status", ex); + } + } + + private List asEventData(final List commonEvents) { + final List list = new ArrayList<>(commonEvents.size()); + for (final CommonEvent commonEvent : commonEvents) { + list.add(ce2edConv.convert(commonEvent)); + } + return list; + } + + private List asCommonEvents(final List resolvedEvents) { + final List list = new ArrayList<>(resolvedEvents.size()); + for (final ResolvedEvent resolvedEvent : resolvedEvents) { + list.add(asCommonEvent(resolvedEvent)); + } + return list; + } + + private CommonEvent asCommonEvent(final ResolvedEvent resolvedEvent) { + return ed2ceConv.convert(resolvedEvent.getEvent()); + } + + private void ensureOpen() { + if (!open) { + open(); + } + } + + private boolean statusIsDeleted(ExecutionException ex) { + if (ex.getCause() instanceof StatusRuntimeException sre) { + return sre.getStatus().getCode().equals(Status.FAILED_PRECONDITION.getCode()) + && sre.getStatus().getDescription() != null + && sre.getStatus().getDescription().contains("is deleted"); + } + return ex.getCause() instanceof com.eventstore.dbclient.StreamDeletedException; + } + + /** + * Builder used to create a new instance of the event store. + */ + public static final class Builder { + + private com.eventstore.dbclient.EventStoreDBClient eventStore; + + private SerializerRegistry serRegistry; + + private DeserializerRegistry desRegistry; + + private IBaseTypeFactory baseTypeFactory; + + private EnhancedMimeType targetContentType; + + private TenantId tenantId; + + /** + * Sets the event store to use internally. + * + * @param eventStore TCP/IP event store connection. + * @return Builder. + */ + public Builder eventStore(com.eventstore.dbclient.EventStoreDBClient eventStore) { + this.eventStore = eventStore; + return this; + } + + /** + * Sets the serializer registry. + * + * @param serRegistry Registry used to locate serializers. + * @return Builder. + */ + public Builder serRegistry(final SerializerRegistry serRegistry) { + this.serRegistry = serRegistry; + return this; + } + + /** + * Sets the deserializer registry. + * + * @param desRegistry Registry used to locate deserializers. + * @return Builder. + */ + public Builder desRegistry(final DeserializerRegistry desRegistry) { + this.desRegistry = desRegistry; + return this; + } + + /** + * Sets both types of registries in one call. + * + * @param registry Serializer/Deserializer registry to set. + * @return Builder. + */ + public Builder serDesRegistry(final SerDeserializerRegistry registry) { + this.serRegistry = registry; + this.desRegistry = registry; + return this; + } + + /** + * Sets the base type factory. + * + * @param baseTypeFactory Fcatory used to create base types. + * @return Builder. + */ + public Builder desRegistry(final IBaseTypeFactory baseTypeFactory) { + this.baseTypeFactory = baseTypeFactory; + return this; + } + + + /** + * Sets the target content type. + * + * @param targetContentType Target content type (Allows only 'application/xml' + * or 'application/json' with 'utf-8' encoding). + * @return Builder. + */ + public Builder targetContentType(final EnhancedMimeType targetContentType) { + this.targetContentType = targetContentType; + return this; + } + + /** + * Sets the tenant identifier. + * + * @param tenantId Unique tenant identifier. + * @return Builder + */ + public Builder tenantId(final TenantId tenantId) { + this.tenantId = tenantId; + return this; + } + + private void verifyNotNull(final String name, final Object value) { + if (value == null) { + throw new IllegalStateException( + "It is mandatory to set the value of '" + name + "' before calling the 'build()' method"); + } + } + + /** + * Creates a new instance of the event store from the attributes set via the + * builder. + * + * @return New event store instance. + */ + public ESGrpcEventStore build() { + verifyNotNull("eventStore", eventStore); + verifyNotNull("serRegistry", serRegistry); + verifyNotNull("desRegistry", desRegistry); + verifyNotNull("baseTypeFactory", baseTypeFactory); + verifyNotNull("targetContentType", targetContentType); + return new ESGrpcEventStore(eventStore, serRegistry, desRegistry, baseTypeFactory, targetContentType, tenantId); + } + + } } diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStore.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStore.java index daaa0550..92ae2603 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStore.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStore.java @@ -5,8 +5,12 @@ import com.eventstore.dbclient.EventStoreDBProjectionManagementClient; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.*; +import org.fuin.esc.api.ProjectionAdminEventStore; +import org.fuin.esc.api.StreamAlreadyExistsException; +import org.fuin.esc.api.StreamId; +import org.fuin.esc.api.StreamNotFoundException; +import org.fuin.esc.api.TenantId; +import org.fuin.esc.api.TypeName; import org.fuin.esc.spi.ProjectionJavaScriptBuilder; import org.fuin.esc.spi.TenantStreamId; import org.fuin.objects4j.common.ConstraintViolationException; diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/IESGrpcEventStore.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/IESGrpcEventStore.java index 8b18b3fd..c67d6da6 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/IESGrpcEventStore.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/IESGrpcEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -20,8 +20,8 @@ import org.fuin.esc.api.EventStore; /** - * Interface for the implementation that connects to the http://www.geteventstore.com via TCP API. This allows dependency injections - * frameworks like CDI to use this interface rather than the (final) implementation. + * Interface for the implementation that connects to the Eventstore via TCP API. + * This allows dependency injections frameworks like CDI to use this interface rather than the (final) implementation. */ public interface IESGrpcEventStore extends EventStore { diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverter.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverter.java index c69e4124..f503e7ab 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverter.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverter.java @@ -1,135 +1,132 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import java.nio.charset.Charset; - +import com.eventstore.dbclient.RecordedEvent; +import jakarta.validation.constraints.NotNull; import org.fuin.esc.api.CommonEvent; -import org.fuin.esc.api.EventId; -import org.fuin.esc.api.SimpleCommonEvent; -import org.fuin.esc.api.TypeName; -import org.fuin.esc.spi.Base64Data; import org.fuin.esc.api.Converter; import org.fuin.esc.api.Deserializer; import org.fuin.esc.api.DeserializerRegistry; import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.EscMeta; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IEscMeta; import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.TypeName; import org.fuin.objects4j.common.Contract; -import com.eventstore.dbclient.RecordedEvent; - -import jakarta.validation.constraints.NotNull; +import java.nio.charset.StandardCharsets; /** * Converts a {@link RecordedEvent} into {@link CommonEvent}. */ public final class RecordedEvent2CommonEventConverter implements Converter { - private final DeserializerRegistry deserRegistry; - - /** - * Constructor with all mandatory data. - * - * @param deserRegistry Registry used to locate deserializers. - */ - public RecordedEvent2CommonEventConverter(@NotNull final DeserializerRegistry deserRegistry) { - super(); - Contract.requireArgNotNull("deserRegistry", deserRegistry); - this.deserRegistry = deserRegistry; - } - - /** - * Converts event data into a common event. - * - * @param eventData Data to convert. - * - * @return Converted data das event. - */ - @Override - public final CommonEvent convert(final RecordedEvent eventData) { - - final EnhancedMimeType escMetaMimeType = metaMimeType(eventData.getContentType().equals("application/json")); - final SerializedDataType escSerMetaType = new SerializedDataType(EscMeta.TYPE.asBaseType()); - final Deserializer escMetaDeserializer = deserRegistry.getDeserializer(escSerMetaType, escMetaMimeType); - final EscMeta escMeta = escMetaDeserializer.unmarshal(eventData.getUserMetadata(), escSerMetaType, - escMetaMimeType); - final EnhancedMimeType metaMimeType = escMeta.getMetaContentType(); - final String metaTransferEncoding; - if (escMeta.getMetaType() == null) { - metaTransferEncoding = null; - } else { - metaTransferEncoding = escMeta.getMetaContentType().getParameter("transfer-encoding"); - } - final EnhancedMimeType dataMimeType = escMeta.getDataContentType(); - final SerializedDataType serDataType = new SerializedDataType(escMeta.getDataType()); - final Deserializer dataDeserializer = deserRegistry.getDeserializer(serDataType, dataMimeType); - final String dataTransferEncoding = escMeta.getDataContentType().getParameter("transfer-encoding"); - final Object data = unmarshal(dataTransferEncoding, serDataType, dataDeserializer, dataMimeType, - eventData.getEventData(), metaMimeType, escMetaMimeType); - - final EventId eventId = new EventId(eventData.getEventId()); - final TypeName dataType = new TypeName(eventData.getEventType()); - if (escMeta.getMetaType() == null) { - return new SimpleCommonEvent(eventId, dataType, data); - } - final TypeName metaType = new TypeName(escMeta.getMetaType()); - final SerializedDataType serMetaType = new SerializedDataType(escMeta.getMetaType()); - final Deserializer metaDeserializer = deserRegistry.getDeserializer(serMetaType, metaMimeType); - final Object meta = unmarshal(metaTransferEncoding, serMetaType, metaDeserializer, metaMimeType, - escMeta.getMeta(), metaMimeType, escMetaMimeType); - return new SimpleCommonEvent(eventId, dataType, data, metaType, meta); - } - - private Object unmarshal(final String transferEncoding, final SerializedDataType dataType, - final Deserializer dataDeserializer, final EnhancedMimeType dataMimeType, final Object data, - final EnhancedMimeType metaMimeType, final EnhancedMimeType escMetaMimeType) { - - if (transferEncoding == null) { - return dataDeserializer.unmarshal(data, dataType, dataMimeType); - } - - if (data instanceof Base64Data) { - final Base64Data base64Data = (Base64Data) data; - return dataDeserializer.unmarshal(base64Data.getDecoded(), dataType, dataMimeType); - } - - // Currently only 'base64' is supported - final Deserializer base64Deserializer = deserRegistry.getDeserializer(Base64Data.SER_TYPE, escMetaMimeType); - final Base64Data base64Data = base64Deserializer.unmarshal(data, Base64Data.SER_TYPE, metaMimeType); - return dataDeserializer.unmarshal(base64Data.getDecoded(), dataType, dataMimeType); - } + private final DeserializerRegistry deserRegistry; + + /** + * Constructor with all mandatory data. + * + * @param deserRegistry Registry used to locate deserializers. + */ + public RecordedEvent2CommonEventConverter(@NotNull final DeserializerRegistry deserRegistry) { + super(); + Contract.requireArgNotNull("deserRegistry", deserRegistry); + this.deserRegistry = deserRegistry; + } + + /** + * Converts event data into a common event. + * + * @param eventData Data to convert. + * + * @return Converted data das event. + */ + @Override + public CommonEvent convert(final RecordedEvent eventData) { + + final EnhancedMimeType escMetaMimeType = metaMimeType(eventData.getContentType().equals("application/json")); + final SerializedDataType escSerMetaType = new SerializedDataType(IEscMeta.TYPE.asBaseType()); + final Deserializer escMetaDeserializer = deserRegistry.getDeserializer(escSerMetaType, escMetaMimeType); + final IEscMeta escMeta = escMetaDeserializer.unmarshal(eventData.getUserMetadata(), escSerMetaType, escMetaMimeType); + final EnhancedMimeType metaMimeType = escMeta.getMetaContentType(); + final String metaTransferEncoding; + if (escMeta.getMetaType() == null || escMeta.getMetaContentType() == null) { + metaTransferEncoding = null; + } else { + metaTransferEncoding = escMeta.getMetaContentType().getParameter("transfer-encoding"); + } + final EnhancedMimeType dataMimeType = escMeta.getDataContentType(); + final SerializedDataType serDataType = new SerializedDataType(escMeta.getDataType()); + final Deserializer dataDeserializer = deserRegistry.getDeserializer(serDataType, dataMimeType); + final String dataTransferEncoding = escMeta.getDataContentType().getParameter("transfer-encoding"); + final Object data = unmarshal(dataTransferEncoding, serDataType, dataDeserializer, dataMimeType, + eventData.getEventData(), metaMimeType, escMetaMimeType); + + final EventId eventId = new EventId(eventData.getEventId()); + final TypeName dataType = new TypeName(eventData.getEventType()); + if (escMeta.getMetaType() == null) { + return new SimpleCommonEvent(eventId, dataType, data); + } + final TypeName metaType = new TypeName(escMeta.getMetaType()); + final SerializedDataType serMetaType = new SerializedDataType(escMeta.getMetaType()); + final Deserializer metaDeserializer = deserRegistry.getDeserializer(serMetaType, metaMimeType); + final Object meta = unmarshal(metaTransferEncoding, serMetaType, metaDeserializer, metaMimeType, + escMeta.getMeta(), metaMimeType, escMetaMimeType); + return new SimpleCommonEvent(eventId, dataType, data, metaType, meta); + } + + private Object unmarshal(final String transferEncoding, final SerializedDataType dataType, + final Deserializer dataDeserializer, final EnhancedMimeType dataMimeType, final Object data, + final EnhancedMimeType metaMimeType, final EnhancedMimeType escMetaMimeType) { + + if (transferEncoding == null) { + return dataDeserializer.unmarshal(data, dataType, dataMimeType); + } + + if (data instanceof IBase64Data) { + final IBase64Data base64Data = (IBase64Data) data; + return dataDeserializer.unmarshal(base64Data.getDecoded(), dataType, dataMimeType); + } + + // Currently only 'base64' is supported + final Deserializer base64Deserializer = deserRegistry.getDeserializer(IBase64Data.SER_TYPE, escMetaMimeType); + final IBase64Data base64Data = base64Deserializer.unmarshal(data, IBase64Data.SER_TYPE, metaMimeType); + return dataDeserializer.unmarshal(base64Data.getDecoded(), dataType, dataMimeType); + } private EnhancedMimeType metaMimeType(final boolean json) { if (json) { - return EnhancedMimeType.create("application", "json", Charset.forName("utf-8")); + return EnhancedMimeType.create("application", "json", StandardCharsets.UTF_8); } - return EnhancedMimeType.create("application", "xml", Charset.forName("utf-8")); + return EnhancedMimeType.create("application", "xml", StandardCharsets.UTF_8); } - @Override - public final Class getSourceType() { - return RecordedEvent.class; - } + @Override + public Class getSourceType() { + return RecordedEvent.class; + } - @Override - public final Class getTargetType() { - return CommonEvent.class; - } + @Override + public Class getTargetType() { + return CommonEvent.class; + } } diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/AccountCreated.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/AccountCreated.java index 906a742b..0a0f8b56 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/AccountCreated.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/AccountCreated.java @@ -26,6 +26,6 @@ public void setLogin(String login) { public String toString() { return "AccountCreated [id=" + id + ", login=" + login + "]"; } - - + + } \ No newline at end of file diff --git a/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/App.java b/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/App.java index d4f3d8d6..f147cd3e 100644 --- a/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/App.java +++ b/esgrpc/src/main/java/org/fuin/esc/esgrpc/example/App.java @@ -1,9 +1,5 @@ package org.fuin.esc.esgrpc.example; -import java.io.IOException; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - import com.eventstore.dbclient.DeleteResult; import com.eventstore.dbclient.DeleteStreamOptions; import com.eventstore.dbclient.EventData; @@ -15,9 +11,16 @@ import com.eventstore.dbclient.ResolvedEvent; import com.eventstore.dbclient.WriteResult; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + public class App { - public static void main(String args[]) throws InterruptedException, ExecutionException, IOException { + private App() { + } + + public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { System.out.println("BEGIN"); @@ -54,4 +57,5 @@ public static void main(String args[]) throws InterruptedException, ExecutionExc System.out.println("END"); } + } \ No newline at end of file diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/ArchitectureTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/ArchitectureTest.java new file mode 100644 index 00000000..bb5b6279 --- /dev/null +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/ArchitectureTest.java @@ -0,0 +1,62 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.esgrpc; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; +import org.fuin.esc.spi.EscSpiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.annotation..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.slf4j..", + "com.eventstore.dbclient..", + "io.grpc.." + ); + + +} + diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/BaseTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/BaseTest.java new file mode 100644 index 00000000..f44d9b1d --- /dev/null +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/BaseTest.java @@ -0,0 +1,47 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.esgrpc; + +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; + +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { + + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .and().doNotHaveFullyQualifiedName("org.fuin.esc.esgrpc.example.AccountCreated") + .and().doNotHaveFullyQualifiedName("org.fuin.esc.esgrpc.example.App") + .should(haveACorrespondingClassEndingWith("Test")); + +} + diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverterTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverterTest.java index dc50efa6..1d838d2d 100644 --- a/esgrpc/src/test/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverterTest.java +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/CommonEvent2EventDataConverterTest.java @@ -1,83 +1,91 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import static org.assertj.core.api.Assertions.assertThat; - -import java.nio.charset.Charset; - -import jakarta.json.Json; - +import com.eventstore.dbclient.EventData; import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.EventId; import org.fuin.esc.api.SimpleCommonEvent; -import org.fuin.esc.api.TypeName; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.EscMeta; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.jsonb.BaseTypeFactory; +import org.fuin.esc.jsonb.EscMeta; +import org.fuin.esc.jsonb.JsonbDeSerializer; import org.junit.jupiter.api.Test; -import com.eventstore.dbclient.EventData; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for {@link CommonEvent2EventDataConverter} class. */ -// CHECKSTYLE:OFF Test code + public final class CommonEvent2EventDataConverterTest { + private static final EnhancedMimeType JSON_UTF8 = EnhancedMimeType.create("application", "json", StandardCharsets.UTF_8); + @Test - public final void testConvert() { + public final void testConvert() throws IOException { // PREPARE - final EnhancedMimeType targetContentType = EnhancedMimeType.create("application", "json", - Charset.forName("utf-8")); - final SimpleSerializerDeserializerRegistry serRegistry = new SimpleSerializerDeserializerRegistry(); - final JsonDeSerializer deserializer = new JsonDeSerializer(); - serRegistry.addSerializer(new SerializedDataType("MyData"), deserializer); - serRegistry.addSerializer(new SerializedDataType("MyMeta"), deserializer); - serRegistry.addSerializer(new SerializedDataType(EscMeta.TYPE.asBaseType()), deserializer); - - final EventId id = new EventId(); - final TypeName dataType = new TypeName("MyData"); - final Object data = Json.createObjectBuilder().add("id", 1).add("name", "Peter").build(); - final TypeName metaType = new TypeName("MyMeta"); - final Object meta = Json.createObjectBuilder().add("ip", "127.0.0.1").build(); - final CommonEvent commonEvent = new SimpleCommonEvent(id, dataType, data, metaType, meta); - - final CommonEvent2EventDataConverter testee = new CommonEvent2EventDataConverter(serRegistry, - targetContentType); - - // TEST - final EventData eventData = testee.convert(commonEvent); - - // VERIFY - assertThat(eventData.getEventId()).isEqualTo(commonEvent.getId().asBaseType()); - assertThat(eventData.getEventType()).isEqualTo(commonEvent.getDataType().asBaseType()); - assertThat(new String(eventData.getEventData(), deserializer.getMimeType().getEncoding())) - .isEqualTo("{\"id\":1,\"name\":\"Peter\"}"); - assertThat(new String(eventData.getUserMetadata(), deserializer.getMimeType().getEncoding())).isEqualTo( - "{\"data-type\":\"MyData\"," + "\"data-content-type\":\"application/json; encoding=UTF-8\"," - + "\"meta-type\":\"MyMeta\",\"meta-content-type\":\"application/json; encoding=UTF-8\"," - + "\"MyMeta\":{\"ip\":\"127.0.0.1\"}}"); + final SimpleSerializedDataTypeRegistry typeRegistry = createTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(EscMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyEvent.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + + final MyEvent myEvent = new MyEvent(UUID.fromString("52faeb52-3933-422e-a1f4-4393a6517678"), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter testee = new CommonEvent2EventDataConverter(registry, new BaseTypeFactory(), JSON_UTF8); + + // TEST + final EventData eventData = testee.convert(commonEvent); + + // VERIFY + assertThat(eventData.getEventId()).isEqualTo(commonEvent.getId().asBaseType()); + assertThat(eventData.getEventType()).isEqualTo(commonEvent.getDataType().asBaseType()); + assertThatJson(new String(eventData.getEventData(), StandardCharsets.UTF_8)).isEqualTo(""" + {"description":"Hello, JSON!","id":"52faeb52-3933-422e-a1f4-4393a6517678"}"""); + assertThatJson(new String(eventData.getUserMetadata(), StandardCharsets.UTF_8)).isEqualTo(""" + {"data-type":"MyEvent","data-content-type":"application/json; encoding=UTF-8","meta-type":"MyMeta","meta-content-type":"application/json; encoding=UTF-8","MyMeta":{"user":"michael"}}"""); + + } } + private static SimpleSerializedDataTypeRegistry createTypeRegistry() { + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(EscMeta.SER_TYPE, org.fuin.esc.jsonb.EscMeta.class); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + return typeRegistry; + } + } -// CHECKSTYLE:ON + diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/ESGrpcEventStoreTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/ESGrpcEventStoreTest.java new file mode 100644 index 00000000..64238dae --- /dev/null +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/ESGrpcEventStoreTest.java @@ -0,0 +1,13 @@ +package org.fuin.esc.esgrpc; + +import org.fuin.utils4j.TestOmitted; + +/** + * Test for the {@link ESGrpcEventStore} class. + */ +@TestOmitted("Tested in the 'test' project") +public class ESGrpcEventStoreTest { + + // No code by intention + +} diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreIT.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreIT.java index 9e233b48..041082df 100644 --- a/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreIT.java +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreIT.java @@ -3,6 +3,7 @@ import com.eventstore.dbclient.EventStoreDBClientSettings; import com.eventstore.dbclient.EventStoreDBConnectionString; import com.eventstore.dbclient.EventStoreDBProjectionManagementClient; +import com.tngtech.archunit.junit.ArchIgnore; import org.fuin.esc.api.ProjectionStreamId; import org.fuin.esc.api.TypeName; import org.junit.jupiter.api.BeforeAll; @@ -16,6 +17,7 @@ /** * Tests the {@link GrpcProjectionAdminEventStore} class. */ +@ArchIgnore class GrpcProjectionAdminEventStoreIT { private static EventStoreDBProjectionManagementClient client; diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreTest.java new file mode 100644 index 00000000..bf6c4338 --- /dev/null +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/GrpcProjectionAdminEventStoreTest.java @@ -0,0 +1,13 @@ +package org.fuin.esc.esgrpc; + +import org.fuin.utils4j.TestOmitted; + +/** + * Test for the {@link GrpcProjectionAdminEventStore} class. + */ +@TestOmitted("Tested in the 'test' project") +public class GrpcProjectionAdminEventStoreTest { + + // No code by intention + +} diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyEvent.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyEvent.java index 9f57bd94..2ac27819 100644 --- a/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyEvent.java +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyEvent.java @@ -1,54 +1,52 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import java.io.Serializable; -import java.nio.charset.Charset; -import java.util.UUID; - -import jakarta.json.Json; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.json.JsonObject; -import jakarta.json.JsonStructure; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; - -import org.fuin.esc.api.TypeName; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerDeserializer; import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.ToJsonCapable; +import org.fuin.esc.api.TypeName; import org.fuin.objects4j.common.Contract; +import java.io.Serializable; +import java.util.UUID; + /** * Something interesting happened. Equals and hash code are based on the UUID. */ +@ArchIgnore @XmlRootElement(name = "MyEvent") -public final class MyEvent implements Serializable, ToJsonCapable { +public final class MyEvent implements Serializable { private static final long serialVersionUID = 100L; - /** Unique name of the event. */ + /** + * Unique name of the event. + */ public static final TypeName TYPE = new TypeName("MyEvent"); - /** Unique name of the serialized event. */ + /** + * Unique name of the serialized event. + */ public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); private static final String ID = "id"; @@ -70,9 +68,8 @@ protected MyEvent() { /** * Constructor with random UUID. - * - * @param description - * The description. + * + * @param description The description. */ public MyEvent(@NotEmpty final String description) { super(); @@ -83,11 +80,9 @@ public MyEvent(@NotEmpty final String description) { /** * Constructor with all mandatory data. - * - * @param uuid - * The unique identifier of the event. - * @param description - * The description. + * + * @param uuid The unique identifier of the event. + * @param description The description. */ public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { super(); @@ -99,7 +94,7 @@ public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { /** * Returns the unique identifier. - * + * * @return UUID string. */ @NotNull @@ -109,7 +104,7 @@ public final String getId() { /** * Returns the description. - * + * * @return The description. */ @NotEmpty @@ -117,7 +112,6 @@ public final String getDescription() { return description; } - // CHECKSTYLE:OFF Generated code @Override public int hashCode() { @@ -149,12 +143,6 @@ public boolean equals(Object obj) { return true; } - // CHECKSTYLE:ON - - @Override - public JsonStructure toJson() { - return Json.createObjectBuilder().add(ID, id).add(DESCRIPTION, description).build(); - } @Override public final String toString() { @@ -163,10 +151,8 @@ public final String toString() { /** * Creates in instance from the given JSON object. - * - * @param jsonObj - * Object to read values from. - * + * + * @param jsonObj Object to read values from. * @return New instance. */ public static MyEvent create(final JsonObject jsonObj) { @@ -175,50 +161,4 @@ public static MyEvent create(final JsonObject jsonObj) { return new MyEvent(UUID.fromString(id), description); } - /** - * Serializes and deserializes a {@link MyEvent} object as JSON. The content - * type for serialization is always "application/json". - */ - public static class MyEventJsonDeSerializer implements SerDeserializer { - - private JsonDeSerializer jsonDeSer; - - /** - * Constructor with UTF-8 encoding. - */ - public MyEventJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public MyEventJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final MyEvent unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonObject jsonObj = jsonDeSer.unmarshal(data, type, mimeType); - return MyEvent.create(jsonObj); - } - - } - } diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyMeta.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyMeta.java index 3ddc393e..f9d5a006 100644 --- a/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyMeta.java +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/MyMeta.java @@ -1,51 +1,48 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import java.io.Serializable; -import java.nio.charset.Charset; - -import jakarta.json.Json; -import jakarta.json.JsonObject; -import jakarta.json.JsonStructure; +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.annotation.Nullable; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; - -import org.fuin.esc.api.TypeName; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerDeserializer; import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.ToJsonCapable; -import jakarta.annotation.Nullable; +import org.fuin.esc.api.TypeName; + +import java.io.Serializable; /** * Example meta data. . */ +@ArchIgnore @XmlRootElement(name = "MyMeta") -public final class MyMeta implements Serializable, ToJsonCapable { +public final class MyMeta implements Serializable { private static final long serialVersionUID = 100L; - /** Unique name of the meta type. */ + /** + * Unique name of the meta type. + */ public static final TypeName TYPE = new TypeName("MyMeta"); - /** Unique name of the serialized meta type. */ + /** + * Unique name of the serialized meta type. + */ public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); private static final String USER = "user"; @@ -62,9 +59,8 @@ protected MyMeta() { /** * Constructor with all mandatory data. - * - * @param user - * User ID. + * + * @param user User ID. */ public MyMeta(@Nullable final String user) { super(); @@ -73,14 +69,13 @@ public MyMeta(@Nullable final String user) { /** * Returns the user. - * + * * @return User ID. */ public final String getUser() { return user; } - // CHECKSTYLE:OFF Generated code @Override public int hashCode() { @@ -112,75 +107,4 @@ public boolean equals(Object obj) { return true; } - // CHECKSTYLE:ON - - @Override - public JsonStructure toJson() { - return Json.createObjectBuilder().add(USER, user).build(); - } - - @Override - public final String toString() { - return "My meta: " + user; - } - - /** - * Creates in instance from the given JSON object. - * - * @param jsonObj - * Object to read values from. - * - * @return New instance. - */ - public static MyMeta create(final JsonObject jsonObj) { - final String user = jsonObj.getString(USER); - return new MyMeta(user); - } - - /** - * Serializes and deserializes a {@link MyMeta} object as JSON. The content - * type for serialization is always "application/json". - */ - public static class MyMetaJsonDeSerializer implements SerDeserializer { - - private JsonDeSerializer jsonDeSer; - - /** - * Constructor with UTF-8 encoding. - */ - public MyMetaJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public MyMetaJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final MyMeta unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonObject jsonObj = jsonDeSer.unmarshal(data, type, mimeType); - return MyMeta.create(jsonObj); - } - - } - } diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverterTest.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverterTest.java index 40780f01..10798a2c 100644 --- a/esgrpc/src/test/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverterTest.java +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/RecordedEvent2CommonEventConverterTest.java @@ -1,358 +1,401 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.esgrpc; -import static org.assertj.core.api.Assertions.assertThat; +import com.eventstore.dbclient.EventData; +import com.eventstore.dbclient.Position; +import com.eventstore.dbclient.RecordedEvent; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.jaxb.XmlDeSerializer; +import org.fuin.esc.jsonb.EscMeta; +import org.fuin.esc.jsonb.JsonbDeSerializer; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.fuin.esc.api.CommonEvent; -import org.fuin.esc.api.EventId; -import org.fuin.esc.api.SimpleCommonEvent; -import org.fuin.esc.spi.Base64Data; -import org.fuin.esc.spi.Base64Data.Base64DataJsonDeSerializer; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.EscMeta; -import org.fuin.esc.spi.EscMetaJsonDeSerializer; -import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; -import org.fuin.esc.spi.XmlDeSerializer; -import org.junit.jupiter.api.Test; - -import com.eventstore.dbclient.EventData; -import com.eventstore.dbclient.Position; -import com.eventstore.dbclient.RecordedEvent; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for {@link RecordedEvent2CommonEventConverter} class. */ -// CHECKSTYLE:OFF Test code + public class RecordedEvent2CommonEventConverterTest { - private static final Class[] JAXB_CLASSES = new Class[] { EscMeta.class, MyEvent.class, MyMeta.class, - Base64Data.class }; - - /** - * Tests envelope JSON + meta JSON + data JSON - */ - @Test - public final void testConvertJsonJsonJson() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "json", Charset.forName("utf-8")); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new EscMetaJsonDeSerializer()); - registry.add(MyEvent.SER_TYPE, "application/json", new MyEvent.MyEventJsonDeSerializer()); - registry.add(MyMeta.SER_TYPE, "application/json", new MyMeta.MyMetaJsonDeSerializer()); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), - eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - /** - * Tests envelope JSON + meta JSON + data XML (non JSON) - */ - @Test - public final void testConvertJsonJsonOther() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "json", Charset.forName("utf-8")); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new EscMetaJsonDeSerializer()); - registry.add(Base64Data.SER_TYPE, envelope.getBaseType(), new Base64DataJsonDeSerializer()); - registry.add(MyMeta.SER_TYPE, "application/json", new MyMeta.MyMetaJsonDeSerializer()); - registry.add(MyEvent.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), - eventData.getEventData(), eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - /** - * Tests envelope JSON + meta JSON + data XML (non JSON) - */ - @Test - public final void testConvertJsonOtherOther() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "json", Charset.forName("utf-8")); - final int json = 1; - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new EscMetaJsonDeSerializer()); - registry.add(Base64Data.SER_TYPE, envelope.getBaseType(), new Base64DataJsonDeSerializer()); - registry.add(MyMeta.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyEvent.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), - eventData.getEventData(), eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - /** - * Tests envelope XML + meta XML + data XML - */ - @Test - public final void testConvertXmlXmlXml() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "xml", Charset.forName("utf-8")); - final int json = 0; - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyEvent.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyMeta.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), - eventData.getEventData(), eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - /** - * Tests envelope XML + meta XML + data JSON (non XML) - */ - @Test - public final void testConvertXmlXmlOther() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "xml", Charset.forName("utf-8")); - final int json = 0; - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); - registry.add(Base64Data.SER_TYPE, envelope.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyMeta.SER_TYPE, "application/xml", new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyEvent.SER_TYPE, "application/json", new MyEvent.MyEventJsonDeSerializer()); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), - eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - /** - * Tests envelope XML + meta JSON + data JSON (non XML) - */ - @Test - public final void testConvertXmlOtherOther() throws IOException { - - // PREPARE - final EnhancedMimeType envelope = EnhancedMimeType.create("application", "xml", Charset.forName("utf-8")); - final int json = 0; - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.add(EscMeta.SER_TYPE, envelope.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); - registry.add(Base64Data.SER_TYPE, envelope.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); - registry.add(MyMeta.SER_TYPE, "application/json", new MyMeta.MyMetaJsonDeSerializer()); - registry.add(MyEvent.SER_TYPE, "application/json", new MyEvent.MyEventJsonDeSerializer()); - - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); - final MyMeta myMeta = new MyMeta("michael"); - final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, - MyMeta.TYPE, myMeta); - - final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, envelope); - final EventData eventData = converter.convert(commonEvent); - - final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), - systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), - eventData.getUserMetadata()); - final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); - - // TEST - final CommonEvent result = testee.convert(recordedEvent); - - // VERIFY - assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); - - assertThat(result.getData()).isInstanceOf(MyEvent.class); - final MyEvent copyMyEvent = (MyEvent) result.getData(); - assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); - assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); - - assertThat(result.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta copyMyMeta = (MyMeta) result.getMeta(); - assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); - - } - - private static Map systemMetadata(String contentType, long created, boolean json, String type) { - final Map map = new HashMap<>(); - map.put("content-type", contentType); - map.put("created", "" + created); - map.put("is-json", "" + json); - map.put("type", type); - return map; - } - - private static RecordedEvent recordedEvent(String eventStreamId, long streamRevision, UUID eventId, - Position position, Map systemMetadata, byte[] eventData, byte[] userMetadata) { - - try { - final Constructor constructor = RecordedEvent.class.getDeclaredConstructor(String.class, - long.class, UUID.class, Position.class, Map.class, byte[].class, byte[].class); - constructor.setAccessible(true); - return constructor.newInstance(eventStreamId, streamRevision, eventId, position, systemMetadata, eventData, - userMetadata); - } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException - | IllegalArgumentException ex) { - throw new RuntimeException("Failed to create " + RecordedEvent.class.getSimpleName(), ex); - } - } + private static final Class[] JAXB_CLASSES = new Class[]{ + org.fuin.esc.jaxb.EscMeta.class, MyEvent.class, MyMeta.class, org.fuin.esc.jaxb.Base64Data.class + }; + + private static final EnhancedMimeType JSON_UTF8 = EnhancedMimeType.create("application", "json", StandardCharsets.UTF_8); + + private static final EnhancedMimeType XML_UTF8 = EnhancedMimeType.create("application", "xml", StandardCharsets.UTF_8); + + /** + * Tests envelope JSON + meta JSON + data JSON + */ + @Test + public final void testConvertJsonJsonJson() throws IOException { + + // PREPARE + final SimpleSerializedDataTypeRegistry typeRegistry = createJsonTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(EscMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyEvent.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jsonb.BaseTypeFactory(), JSON_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), + eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + } + + /** + * Tests envelope JSON + meta JSON + data XML (non JSON) + */ + @Test + public final void testConvertJsonJsonOther() throws IOException { + + + // PREPARE + final SimpleSerializedDataTypeRegistry typeRegistry = createJsonTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(org.fuin.esc.jsonb.EscMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(org.fuin.esc.jsonb.Base64Data.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyEvent.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jsonb.BaseTypeFactory(), JSON_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), + new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), + eventData.getEventData(), eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + } + + /** + * Tests envelope JSON + meta JSON + data XML (non JSON) + */ + @Test + public final void testConvertJsonOtherOther() throws IOException { + + // PREPARE + final SimpleSerializedDataTypeRegistry typeRegistry = createJsonTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(org.fuin.esc.jsonb.EscMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(org.fuin.esc.jsonb.Base64Data.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyEvent.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jsonb.BaseTypeFactory(), JSON_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), + eventData.getEventData(), eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + } + + /** + * Tests envelope XML + meta XML + data XML + */ + @Test + public final void testConvertXmlXmlXml() throws IOException { + + // PREPARE + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(org.fuin.esc.jaxb.EscMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyEvent.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jaxb.BaseTypeFactory(), XML_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, false, eventData.getEventType()), + eventData.getEventData(), eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + /** + * Tests envelope XML + meta XML + data JSON (non XML) + */ + @Test + public final void testConvertXmlXmlOther() throws IOException { + + // PREPARE + final SimpleSerializedDataTypeRegistry typeRegistry = createJaxbTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(org.fuin.esc.jaxb.EscMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(org.fuin.esc.jaxb.Base64Data.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyEvent.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, XML!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jaxb.BaseTypeFactory(), XML_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), + eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + } + + /** + * Tests envelope XML + meta JSON + data JSON (non XML) + */ + @Test + public final void testConvertXmlOtherOther() throws IOException { + + // PREPARE + final SimpleSerializedDataTypeRegistry typeRegistry = createJaxbTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(org.fuin.esc.jaxb.EscMeta.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(org.fuin.esc.jaxb.Base64Data.SER_TYPE, XML_UTF8.getBaseType(), new XmlDeSerializer(JAXB_CLASSES)); + registry.add(MyMeta.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + registry.add(MyEvent.SER_TYPE, JSON_UTF8.getBaseType(), jsonbDeSer); + + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("michael"); + final CommonEvent commonEvent = new SimpleCommonEvent(new EventId(myEvent.getId()), MyEvent.TYPE, myEvent, + MyMeta.TYPE, myMeta); + + final CommonEvent2EventDataConverter converter = new CommonEvent2EventDataConverter(registry, new org.fuin.esc.jaxb.BaseTypeFactory(), XML_UTF8); + final EventData eventData = converter.convert(commonEvent); + + final RecordedEvent recordedEvent = recordedEvent("mystream", 1, eventData.getEventId(), new Position(0, 0), + systemMetadata(eventData.getContentType(), 0, true, eventData.getEventType()), eventData.getEventData(), + eventData.getUserMetadata()); + final RecordedEvent2CommonEventConverter testee = new RecordedEvent2CommonEventConverter(registry); + + // TEST + final CommonEvent result = testee.convert(recordedEvent); + + // VERIFY + assertThat(result.getId()).isEqualTo(new EventId(myEvent.getId())); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE); + + assertThat(result.getData()).isInstanceOf(MyEvent.class); + final MyEvent copyMyEvent = (MyEvent) result.getData(); + assertThat(copyMyEvent.getId()).isEqualTo(myEvent.getId()); + assertThat(copyMyEvent.getDescription()).isEqualTo(myEvent.getDescription()); + + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta copyMyMeta = (MyMeta) result.getMeta(); + assertThat(copyMyMeta.getUser()).isEqualTo(myMeta.getUser()); + + } + + } + + private static Map systemMetadata(String contentType, long created, boolean json, String type) { + final Map map = new HashMap<>(); + map.put("content-type", contentType); + map.put("created", "" + created); + map.put("is-json", "" + json); + map.put("type", type); + return map; + } + + private static RecordedEvent recordedEvent(String eventStreamId, long streamRevision, UUID eventId, + Position position, Map systemMetadata, byte[] eventData, byte[] userMetadata) { + + try { + final Constructor constructor = RecordedEvent.class.getDeclaredConstructor(String.class, + long.class, UUID.class, Position.class, Map.class, byte[].class, byte[].class); + constructor.setAccessible(true); + return constructor.newInstance(eventStreamId, streamRevision, eventId, position, systemMetadata, eventData, + userMetadata); + } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException + | IllegalArgumentException ex) { + throw new RuntimeException("Failed to create " + RecordedEvent.class.getSimpleName(), ex); + } + } + + private static SimpleSerializedDataTypeRegistry createJsonTypeRegistry() { + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(org.fuin.esc.jsonb.EscMeta.SER_TYPE, org.fuin.esc.jsonb.EscMeta.class); + typeRegistry.add(org.fuin.esc.jsonb.Base64Data.SER_TYPE, org.fuin.esc.jsonb.Base64Data.class); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + return typeRegistry; + } + + private static SimpleSerializedDataTypeRegistry createJaxbTypeRegistry() { + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(org.fuin.esc.jaxb.EscMeta.SER_TYPE, org.fuin.esc.jaxb.EscMeta.class); + typeRegistry.add(org.fuin.esc.jaxb.Base64Data.SER_TYPE, org.fuin.esc.jaxb.Base64Data.class); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + return typeRegistry; + } } -// CHECKSTYLE:ON + diff --git a/esgrpc/src/test/java/org/fuin/esc/esgrpc/TestUtils.java b/esgrpc/src/test/java/org/fuin/esc/esgrpc/TestUtils.java new file mode 100644 index 00000000..debe5664 --- /dev/null +++ b/esgrpc/src/test/java/org/fuin/esc/esgrpc/TestUtils.java @@ -0,0 +1,67 @@ +package org.fuin.esc.esgrpc; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.validation.constraints.NotNull; +import org.eclipse.yasson.FieldAccessStrategy; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.jsonb.EscEvent; +import org.fuin.esc.jsonb.EscEvents; +import org.fuin.esc.jsonb.EscJsonbUtils; +import org.fuin.esc.jsonb.EscMeta; +import org.fuin.esc.jsonb.JsonbDeSerializer; +import org.fuin.objects4j.common.Contract; + +import java.nio.charset.StandardCharsets; + +/** + * Helper methods for the test package. + */ +@ArchIgnore +final class TestUtils { + + private TestUtils() { + } + + /** + * Creates a {@link JsonbDeSerializer} with default settings. + * + * @return New instance. + */ + public static JsonbDeSerializer createJsonbDeSerializer() { + return JsonbDeSerializer.builder() + .withSerializers(EscJsonbUtils.createEscJsonbSerializers()) + .withDeserializers(EscJsonbUtils.createEscJsonbDeserializers()) + .withPropertyVisibilityStrategy(new FieldAccessStrategy()) + .withEncoding(StandardCharsets.UTF_8) + .build(); + } + + /** + * Creates a registry that connects the type with the appropriate serializer and de-serializer. + * + * @param typeRegistry Type registry (Mapping from type name to class). + * @param jsonbDeSer JSON-B serializer/deserializer to use. + */ + public static void initSerDeserializerRegistry(@NotNull SerializedDataTypeRegistry typeRegistry, + @NotNull JsonbDeSerializer jsonbDeSer) { + + Contract.requireArgNotNull("typeRegistry", typeRegistry); + Contract.requireArgNotNull("jsonbDeSer", jsonbDeSer); + + SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + + // Base types always needed + registry.add(EscEvents.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscEvent.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscMeta.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + // User defined types + registry.add(MyEvent.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(MyMeta.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + jsonbDeSer.init(typeRegistry, registry, registry); + + } + +} diff --git a/jaxb/pom.xml b/jaxb/pom.xml new file mode 100644 index 00000000..1c3724dd --- /dev/null +++ b/jaxb/pom.xml @@ -0,0 +1,197 @@ + + + + 4.0.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + + + esc-jaxb + jar + JAX-B related classes + + + + + + + org.fuin.esc + esc-api + + + + org.fuin.objects4j + objects4j-common + + + + org.fuin + utils4j + + + + jakarta.xml.bind + jakarta.xml.bind-api + + + + com.google.code.findbugs + jsr305 + + + + jakarta.annotation + jakarta.annotation-api + + + + org.slf4j + slf4j-api + + + + jakarta.validation + jakarta.validation-api + + + + jakarta.activation + jakarta.activation-api + + + + + + org.fuin.esc + esc-spi + test + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.glassfish.jaxb + jaxb-runtime + test + + + + org.xmlunit + xmlunit-core + test + + + + commons-io + commons-io + test + + + + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 + test + + + + org.fuin + units4j + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + + + **/* + + + + org.fuin.esc.jaxb + + + + + + + org.apache.maven.plugins + maven-jdeps-plugin + + + + org.apache.maven.plugins + maven-dependency-plugin + + + jakarta.el:jakarta.el-api + org.glassfish:jakarta.el + org.hibernate.validator:hibernate-validator + org.glassfish.jaxb:jaxb-runtime + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + jakarta.activation:jakarta.activation-api + + + + + + + + + diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/Base64Data.java b/jaxb/src/main/java/org/fuin/esc/jaxb/Base64Data.java new file mode 100644 index 00000000..dff80d7c --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/Base64Data.java @@ -0,0 +1,95 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlTransient; +import jakarta.xml.bind.annotation.XmlValue; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IBase64Data; +import org.fuin.objects4j.common.Contract; + +import java.util.Base64; + +/** + * Contains some Base64 encoded data. + */ +@HasSerializedDataTypeConstant +@XmlRootElement(name = Base64Data.EL_ROOT_NAME) +public final class Base64Data implements IBase64Data { + + @XmlValue + private String base64Str; + + @XmlTransient + private byte[] binaryData; + + /** + * Default constructor for JAXB. + */ + protected Base64Data() { + super(); + } + + /** + * Constructor with Base64 encoded string. + * + * @param base64Str Base64 encoded data. + */ + public Base64Data(@NotNull final String base64Str) { + super(); + Contract.requireArgNotNull("base64Str", base64Str); + this.base64Str = base64Str; + this.binaryData = Base64.getDecoder().decode(base64Str); + } + + /** + * Constructor with binary data that will be Base64 encoded. + * + * @param binaryData Binary data. + */ + public Base64Data(@NotNull final byte[] binaryData) { + super(); + Contract.requireArgNotNull("binaryData", binaryData); + this.base64Str = Base64.getEncoder().encodeToString(binaryData); + this.binaryData = binaryData; + } + + /** + * Returns the Base64 encoded data. + * + * @return Base64 string. + */ + public String getEncoded() { + return base64Str; + } + + /** + * Returns the decoded data. + * + * @return Binary data. + */ + public byte[] getDecoded() { + if (binaryData == null) { + binaryData = Base64.getDecoder().decode(base64Str); + } + return binaryData; + } + +} diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/BaseTypeFactory.java b/jaxb/src/main/java/org/fuin/esc/jaxb/BaseTypeFactory.java new file mode 100644 index 00000000..ad376866 --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/BaseTypeFactory.java @@ -0,0 +1,29 @@ +package org.fuin.esc.jaxb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IEscMeta; + +/** + * Creates necessary implementations in the JAX-B module. + */ +public final class BaseTypeFactory implements IBaseTypeFactory { + + @Override + public IBase64Data createBase64Data(@NotNull byte[] binaryData) { + return new Base64Data(binaryData); + } + + @Override + public IEscMeta createEscMeta(@NotNull String dataType, + @NotNull EnhancedMimeType dataContentType, + @Nullable String metaType, + @Nullable EnhancedMimeType metaContentType, + @Nullable Object meta) { + return new EscMeta(dataType, dataContentType, metaType, metaContentType, meta); + } + +} diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/Data.java b/jaxb/src/main/java/org/fuin/esc/jaxb/Data.java new file mode 100644 index 00000000..fd8494b7 --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/Data.java @@ -0,0 +1,165 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlValue; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IData; +import org.fuin.objects4j.common.Contract; +import org.fuin.objects4j.common.ValueObject; +import org.fuin.utils4j.jaxb.CDataXmlAdapter; + +import javax.annotation.concurrent.Immutable; +import java.io.Serial; +import java.io.Serializable; + +/** + * Helper class that allows sending the data of an event as XML directly to the + * event store. Represents a block of data in a serialized form. This class + * might be useful for tests. It's not used in the 'esc-spi' code itself + */ +@Immutable +@XmlRootElement(name = Data.EL_ROOT_NAME) +public final class Data implements IData, ValueObject, Serializable { + + @Serial + private static final long serialVersionUID = 1000L; + + /** + * Unique type of the data. + */ + @NotNull + @XmlAttribute(name = EL_TYPE) + private String type; + + /** + * Internet Media Type that classifies the raw event data. + */ + @NotNull + @XmlAttribute(name = EL_MIME_TYPE) + private String mimeType; + + /** + * Raw event data in format defined by the mime type and encoding. + */ + @NotNull + @XmlValue + @XmlJavaTypeAdapter(CDataXmlAdapter.class) + private String content; + + /** + * Protected constructor for deserialization. + */ + protected Data() { //NOSONAR Ignore uninitialized fields + super(); + } + + /** + * Creates a data object. + * + * @param type Unique identifier for the type of data. + * @param mimeType Internet Media Type with encoding and version that classifies + * the data. + * @param content Content. + */ + public Data(@NotNull final String type, + @NotNull final EnhancedMimeType mimeType, + @NotNull final String content) { + super(); + + Contract.requireArgNotNull("type", type); + Contract.requireArgNotNull("mimeType", mimeType); + Contract.requireArgNotNull("content", content); + + this.type = type; + this.mimeType = mimeType.toString(); + this.content = content; + + } + + /** + * Returns the unique identifier for the type of data. + * + * @return Unique and never changing type name. + */ + @NotNull + public String getType() { + return type; + } + + /** + * Returns the Internet Media Type that classifies the data. + * + * @return Mime type. + */ + @NotNull + public EnhancedMimeType getMimeType() { + return EnhancedMimeType.create(mimeType); + } + + /** + * Returns the raw data block. + * + * @return Raw data. + */ + @NotNull + public String getContent() { + return content; + } + + /** + * Returns the information if the content is XML. + * + * @return TRUE if the mime type is 'application/xml' else FALSE. + */ + public boolean isXml() { + return getMimeType().getBaseType().equals("application/xml"); + } + + /** + * Returns the information if the content is JSON. + * + * @return TRUE if the mime type is 'application/json' else FALSE. + */ + public boolean isJson() { + return getMimeType().getBaseType().equals("application/json"); + } + + /** + * Returns the information if the content is TEXT. + * + * @return TRUE if the mime type is 'text/plain' else FALSE. + */ + public boolean isText() { + return getMimeType().getBaseType().equals("text/plain"); + } + + @Override + public String toString() { + return "Data{" + + "type='" + type + '\'' + + ", mimeType='" + mimeType + '\'' + + ", content='" + content + '\'' + + '}'; + } + +} diff --git a/spi/src/main/java/org/fuin/esc/spi/DataWrapper.java b/jaxb/src/main/java/org/fuin/esc/jaxb/DataWrapper.java similarity index 62% rename from spi/src/main/java/org/fuin/esc/spi/DataWrapper.java rename to jaxb/src/main/java/org/fuin/esc/jaxb/DataWrapper.java index f7348f9b..d0aafb5a 100644 --- a/spi/src/main/java/org/fuin/esc/spi/DataWrapper.java +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/DataWrapper.java @@ -1,37 +1,33 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; -import jakarta.json.JsonStructure; import jakarta.validation.constraints.NotNull; import jakarta.xml.bind.annotation.XmlAnyElement; import jakarta.xml.bind.annotation.XmlRootElement; -import org.fuin.esc.api.ToJsonCapable; +import org.fuin.esc.api.IDataWrapper; import org.fuin.objects4j.common.Contract; /** * A structure that wraps another object of different types. */ -@XmlRootElement(name = DataWrapper.EL_ROOT) -public final class DataWrapper implements ToJsonCapable { - - /** Unique name of the type. */ - protected static final String EL_ROOT = "Wrapper"; +@XmlRootElement(name = IDataWrapper.EL_ROOT) +public final class DataWrapper implements IDataWrapper { @XmlAnyElement(lax = true) private Object obj; @@ -45,7 +41,7 @@ protected DataWrapper() { /** * Constructor with mandatory data. - * + * * @param obj * Object to wrap. */ @@ -57,23 +53,12 @@ public DataWrapper(@NotNull final Object obj) { /** * Returns the wrapped object. - * + * * @return Inner object. */ @NotNull - public final Object getObj() { + public Object getObj() { return obj; } - @Override - public final JsonStructure toJson() { - if (obj instanceof ToJsonCapable) { - return ((ToJsonCapable) obj).toJson(); - } else if (obj instanceof JsonStructure) { - return (JsonStructure) obj; - } - throw new IllegalStateException("Wrapped object is not an instance of '" + ToJsonCapable.class.getSimpleName() - + "' or 'JsonStructure': " + obj + " [" + obj.getClass().getName() + "]"); - } - } diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvent.java b/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvent.java new file mode 100644 index 00000000..527db7f4 --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvent.java @@ -0,0 +1,135 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.esc.api.IEscEvent; +import org.fuin.objects4j.common.Contract; + +import java.util.UUID; + +/** + * An event structure. + */ +@HasSerializedDataTypeConstant +@XmlRootElement(name = EscEvent.EL_ROOT_NAME) +public final class EscEvent implements IEscEvent { + + /** + * Unique name of the type. + */ + public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); + + /** + * Unique name of the serialized type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @XmlElement(name = EL_EVENT_ID) + private String eventId; + + @XmlElement(name = EL_EVENT_TYPE) + private String eventType; + + @XmlElement(name = EL_DATA) + private DataWrapper data; + + @XmlElement(name = EL_META_DATA) + private DataWrapper meta; + + /** + * Default constructor for JAXB. + */ + protected EscEvent() { + super(); + } + + /** + * Constructor with mandatory data. + * + * @param eventId Unique event identifier. + * @param eventType Unique type name of the event. + * @param data The data. + */ + public EscEvent(@NotNull final UUID eventId, @NotNull final String eventType, @NotNull final DataWrapper data) { + this(eventId, eventType, data, null); + } + + /** + * Constructor with all data. + * + * @param eventId Unique event identifier. + * @param eventType Unique type name of the event. + * @param data The data. + * @param meta The meta data if available. + */ + public EscEvent(@NotNull final UUID eventId, @NotNull final String eventType, @NotNull final DataWrapper data, + @Nullable final DataWrapper meta) { + super(); + Contract.requireArgNotNull("eventId", eventId); + Contract.requireArgNotNull("eventType", eventType); + Contract.requireArgNotNull("data", data); + this.eventId = eventId.toString(); + this.eventType = eventType; + this.data = data; + this.meta = meta; + } + + /** + * Returns the unique event identifier. + * + * @return Event ID. + */ + public String getEventId() { + return eventId; + } + + /** + * Returns the unique type name of the event. + * + * @return Event type. + */ + public String getEventType() { + return eventType; + } + + /** + * Returns the data. + * + * @return Data. + */ + public DataWrapper getData() { + return data; + } + + /** + * Returns the metadata. + * + * @return Metadata. + */ + public DataWrapper getMeta() { + return meta; + } + +} diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvents.java b/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvents.java new file mode 100644 index 00000000..a74d3086 --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/EscEvents.java @@ -0,0 +1,90 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.esc.api.IEscEvent; +import org.fuin.esc.api.IEscEvents; +import org.fuin.objects4j.common.Contract; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * A list of events. + */ +@HasSerializedDataTypeConstant +@XmlRootElement(name = EscEvents.EL_ROOT_NAME) +public final class EscEvents implements IEscEvents { + + /** + * Unique name of the type. + */ + public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); + + /** + * Unique name of the serialized type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @XmlElement(name = EL_EVENT) + private List list; + + /** + * Default constructor for JAXB. + */ + protected EscEvents() { + super(); + } + + /** + * Constructor with array. + * + * @param events Event array. + */ + public EscEvents(@NotNull final EscEvent... events) { + this(Arrays.asList(events)); + } + + /** + * Constructor with list. + * + * @param events Event list. + */ + public EscEvents(@NotNull final List events) { + super(); + Contract.requireArgNotNull("events", events); + this.list = events; + } + + /** + * Returns an immutable event list. + * + * @return Unmodifiable list of events. + */ + public List getList() { + return Collections.unmodifiableList(list); + } + +} diff --git a/jaxb/src/main/java/org/fuin/esc/jaxb/EscMeta.java b/jaxb/src/main/java/org/fuin/esc/jaxb/EscMeta.java new file mode 100644 index 00000000..2e5c6841 --- /dev/null +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/EscMeta.java @@ -0,0 +1,158 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlAnyElement; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlTransient; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IEscMeta; +import org.fuin.objects4j.common.Contract; + +/** + * A structure that contains the user's metadata and the system's meta information. + */ +@HasSerializedDataTypeConstant +@XmlRootElement(name = EscMeta.EL_ROOT_NAME) +public final class EscMeta implements IEscMeta { + + @XmlElement(name = EL_DATA_TYPE) + private String dataType; + + @XmlElement(name = EL_DATA_CONTENT_TYPE) + private String dataContentTypeStr; + + @XmlElement(name = EL_META_TYPE) + private String metaType; + + @XmlElement(name = EL_META_CONTENT_TYPE) + private String metaContentTypeStr; + + @XmlAnyElement(lax = true) + private Object meta; + + @XmlTransient + private EnhancedMimeType dataContentType; + + @XmlTransient + private EnhancedMimeType metaContentType; + + /** + * Default constructor for JAXB. + */ + protected EscMeta() { + super(); + } + + /** + * Constructor with all mandatory data. + * + * @param dataType Type of the data. + * @param dataContentType Content type of the data. + */ + public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType) { + this(dataType, dataContentType, null, null, null); + } + + /** + * Constructor with all data. + * + * @param dataType Type of the data. + * @param dataContentType Type of the data. + * @param metaType Unique name of the meta data type if available. + * @param metaContentType Type of the meta data if meta data is available. + * @param meta Meta data object if available. + */ + public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType, @Nullable final String metaType, + @Nullable final EnhancedMimeType metaContentType, @Nullable final Object meta) { + super(); + Contract.requireArgNotNull("dataType", dataType); + Contract.requireArgNotNull("dataContentType", dataContentType); + + this.dataType = dataType; + this.dataContentType = dataContentType; + this.dataContentTypeStr = dataContentType.toString(); + this.metaType = metaType; + this.metaContentType = metaContentType; + if (metaContentType != null) { + this.metaContentTypeStr = metaContentType.toString(); + } + this.meta = meta; + } + + /** + * Returns the unique name of the data type. + * + * @return Data type. + */ + @Nullable + public String getDataType() { + return dataType; + } + + /** + * Returns the type of the data. + * + * @return Data type. + */ + @NotNull + public EnhancedMimeType getDataContentType() { + if (dataContentType == null) { + dataContentType = EnhancedMimeType.create(dataContentTypeStr); + } + return dataContentType; + } + + /** + * Returns the unique name of the meta data type if available. + * + * @return Meta type. + */ + @Nullable + public String getMetaType() { + return metaType; + } + + /** + * Returns the type of the metadata, if available. + * + * @return Meta type. + */ + @Nullable + public EnhancedMimeType getMetaContentType() { + if ((metaContentType == null) && (metaContentTypeStr != null)) { + metaContentType = EnhancedMimeType.create(metaContentTypeStr); + } + return metaContentType; + } + + /** + * Returns the meta data object. + * + * @return Meta data object. + */ + @NotNull + public Object getMeta() { + return meta; + } + +} diff --git a/spi/src/main/java/org/fuin/esc/spi/XmlDeSerializer.java b/jaxb/src/main/java/org/fuin/esc/jaxb/XmlDeSerializer.java similarity index 57% rename from spi/src/main/java/org/fuin/esc/spi/XmlDeSerializer.java rename to jaxb/src/main/java/org/fuin/esc/jaxb/XmlDeSerializer.java index 405a9ec0..307c39ce 100644 --- a/spi/src/main/java/org/fuin/esc/spi/XmlDeSerializer.java +++ b/jaxb/src/main/java/org/fuin/esc/jaxb/XmlDeSerializer.java @@ -1,181 +1,179 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.xml.bind.*; -import jakarta.xml.bind.annotation.adapters.XmlAdapter; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.SerDeserializer; -import org.fuin.esc.api.SerializedDataType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Node; - -import java.io.*; -import java.nio.charset.Charset; - -/** - * Serializes and deserializes an object from/to XML using JAXB. The content type for serialization is always - * "application/xml". This implementation supports {@link Node} and byte[] for unmarshalling - * content. - */ -public final class XmlDeSerializer implements SerDeserializer { - - private static final Logger LOG = LoggerFactory.getLogger(XmlDeSerializer.class); - - private final EnhancedMimeType mimeType; - - private final Marshaller marshaller; - - private final Unmarshaller unmarshaller; - - /** - * Constructor that creates a JAXB context internally and uses UTF-8 encoding. - * - * @param classesToBeBound - * Classes to use for the JAXB context. - */ - public XmlDeSerializer(final Class... classesToBeBound) { - this(Charset.forName("utf-8"), true, classesToBeBound); - } - - /** - * Constructor that creates a JAXB context internally and uses UTF-8 encoding. - * - * @param jaxbFragment - * Generate the XML fragment or not. - * @param classesToBeBound - * Classes to use for the JAXB context. - */ - public XmlDeSerializer(final boolean jaxbFragment, final Class... classesToBeBound) { - this(Charset.forName("utf-8"), jaxbFragment, classesToBeBound); - } - - /** - * Constructor that creates a JAXB context internally. - * - * @param encoding - * Encoding to use. - * @param classesToBeBound - * Classes to use for the JAXB context. - */ - public XmlDeSerializer(final Charset encoding, final Class... classesToBeBound) { - this(encoding, null, true, classesToBeBound); - } - - /** - * Constructor that creates a JAXB context internally. - * - * @param encoding - * Encoding to use. - * @param jaxbFragment - * Generate the XML fragment or not. - * @param classesToBeBound - * Classes to use for the JAXB context. - */ - public XmlDeSerializer(final Charset encoding, final boolean jaxbFragment, - final Class... classesToBeBound) { - this(encoding, null, true, classesToBeBound); - } - - /** - * Constructor with JAXB context classes. - * - * @param encoding - * Encoding to use. - * @param adapters - * Adapters to associate with the JAXB context or null. - * @param jaxbFragment - * Generate the XML fragment or not. - * @param classesToBeBound - * Classes to use for the JAXB context. - */ - public XmlDeSerializer(final Charset encoding, final XmlAdapter[] adapters, - final boolean jaxbFragment, final Class... classesToBeBound) { - super(); - this.mimeType = EnhancedMimeType.create("application", "xml", encoding); - try { - final JAXBContext ctx = JAXBContext.newInstance(classesToBeBound); - marshaller = ctx.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, jaxbFragment); - unmarshaller = ctx.createUnmarshaller(); - if ((adapters == null) || (adapters.length == 0)) { - LOG.debug("No adapters set"); - } else { - for (XmlAdapter adapter : adapters) { - LOG.debug("Set adapter : " + adapter); - marshaller.setAdapter(adapter); - unmarshaller.setAdapter(adapter); - } - } - unmarshaller.setEventHandler(new ValidationEventHandler() { - @Override - public boolean handleEvent(final ValidationEvent event) { - if (event.getSeverity() > 0) { - if (event.getLinkedException() == null) { - throw new RuntimeException("Error unmarshalling the data: " + event.getMessage()); - } - throw new RuntimeException("Error unmarshalling " + "the data", event - .getLinkedException()); - } - return true; - } - }); - } catch (final JAXBException ex) { - throw new RuntimeException("Error initializing JAXB helper classes", ex); - } - } - - @Override - public final EnhancedMimeType getMimeType() { - return mimeType; - } - - @Override - public final byte[] marshal(final Object obj, final SerializedDataType type) { - try { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - final Writer writer = new OutputStreamWriter(bos, mimeType.getEncoding()); - marshaller.marshal(obj, writer); - return bos.toByteArray(); - } catch (final JAXBException ex) { - throw new RuntimeException("Error serializing data", ex); - } - } - - @SuppressWarnings("unchecked") - @Override - public final T unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - try { - - if (data instanceof byte[]) { - final Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) data), - mimeType.getEncoding()); - return (T) unmarshaller.unmarshal(reader); - } - if (data instanceof Node) { - return (T) unmarshaller.unmarshal((Node) data); - } - return (T) data; - - } catch (final JAXBException ex) { - throw new RuntimeException("Error de-serializing data", ex); - } - } - -} +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.*; +import jakarta.xml.bind.annotation.adapters.XmlAdapter; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SerDeserializer; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.objects4j.common.Contract; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Node; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * Serializes and deserializes an object from/to XML using JAXB. The content type for serialization is always + * "application/xml". This implementation supports {@link Node} and byte[] for unmarshalling + * content. + */ +public final class XmlDeSerializer implements SerDeserializer { + + private static final Logger LOG = LoggerFactory.getLogger(XmlDeSerializer.class); + + @NotNull + private final EnhancedMimeType mimeType; + + @NotNull + private final Marshaller marshaller; + + @NotNull + private final Unmarshaller unmarshaller; + + /** + * Constructor that creates a JAXB context internally and uses UTF-8 encoding. + * + * @param classesToBeBound Classes to use for the JAXB context. + */ + public XmlDeSerializer(@NotNull final Class... classesToBeBound) { + this(StandardCharsets.UTF_8, true, classesToBeBound); + } + + /** + * Constructor that creates a JAXB context internally and uses UTF-8 encoding. + * + * @param jaxbFragment Generate the XML fragment or not. + * @param classesToBeBound Classes to use for the JAXB context. + */ + public XmlDeSerializer(final boolean jaxbFragment, + @NotNull final Class... classesToBeBound) { + this(StandardCharsets.UTF_8, jaxbFragment, classesToBeBound); + } + + /** + * Constructor that creates a JAXB context internally. + * + * @param encoding Encoding to use. + * @param classesToBeBound Classes to use for the JAXB context. + */ + public XmlDeSerializer(@NotNull final Charset encoding, + @NotNull final Class... classesToBeBound) { + this(encoding, null, true, classesToBeBound); + } + + /** + * Constructor that creates a JAXB context internally. + * + * @param encoding Encoding to use. + * @param jaxbFragment Generate the XML fragment or not. + * @param classesToBeBound Classes to use for the JAXB context. + */ + public XmlDeSerializer(@NotNull final Charset encoding, + final boolean jaxbFragment, + @NotNull final Class... classesToBeBound) { + this(encoding, null, jaxbFragment, classesToBeBound); + } + + /** + * Constructor with JAXB context classes. + * + * @param encoding Encoding to use. + * @param adapters Adapters to associate with the JAXB context or null. + * @param jaxbFragment Generate the XML fragment or not. + * @param classesToBeBound Classes to use for the JAXB context. + */ + public XmlDeSerializer(@NotNull final Charset encoding, + @Nullable final XmlAdapter[] adapters, + final boolean jaxbFragment, + @NotNull final Class... classesToBeBound) { + super(); + this.mimeType = EnhancedMimeType.create("application", "xml", encoding); + try { + final JAXBContext ctx = JAXBContext.newInstance(classesToBeBound); + marshaller = ctx.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, jaxbFragment); + unmarshaller = ctx.createUnmarshaller(); + if ((adapters == null) || (adapters.length == 0)) { + LOG.debug("No adapters set"); + } else { + for (XmlAdapter adapter : adapters) { + LOG.debug("Set adapter : {}", adapter); + marshaller.setAdapter(adapter); + unmarshaller.setAdapter(adapter); + } + } + unmarshaller.setEventHandler(event -> { + if (event.getSeverity() > 0) { + if (event.getLinkedException() == null) { + throw new RuntimeException("Error unmarshalling the data: " + event.getMessage()); + } + throw new RuntimeException("Error unmarshalling " + "the data", event + .getLinkedException()); + } + return true; + }); + } catch (final JAXBException ex) { + throw new RuntimeException("Error initializing JAXB helper classes", ex); + } + } + + @Override + public EnhancedMimeType getMimeType() { + return mimeType; + } + + @Override + public byte[] marshal(@NotNull final Object obj, @NotNull final SerializedDataType type) { + Contract.requireArgNotNull("obj", obj); + Contract.requireArgNotNull("type", type); + try { + final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); + final Writer writer = new OutputStreamWriter(bos, mimeType.getEncoding()); + marshaller.marshal(obj, writer); + return bos.toByteArray(); + } catch (final JAXBException ex) { + throw new RuntimeException("Error serializing data", ex); + } + } + + @SuppressWarnings("unchecked") + @Override + public T unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { + try { + + if (data instanceof byte[]) { + final Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) data), mimeType.getEncoding()); + return (T) unmarshaller.unmarshal(reader); + } + if (data instanceof Node) { + return (T) unmarshaller.unmarshal((Node) data); + } + return (T) data; + + } catch (final JAXBException ex) { + throw new RuntimeException("Error de-serializing data", ex); + } + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/AbstractXmlTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/AbstractXmlTest.java similarity index 91% rename from spi/src/test/java/org/fuin/esc/spi/AbstractXmlTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/AbstractXmlTest.java index 85a028fa..31612049 100644 --- a/spi/src/test/java/org/fuin/esc/spi/AbstractXmlTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/AbstractXmlTest.java @@ -1,21 +1,21 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; @@ -31,13 +31,12 @@ /** * Base class for XML marshal/unmarshal tests. */ -// CHECKSTYLE:OFF Test public abstract class AbstractXmlTest { /** * Marshals the given data. A null data argument returns * null. Handles CDATA sections correctly. T - * + * * @param data * Data to serialize or null. * @param adapters @@ -46,14 +45,14 @@ public abstract class AbstractXmlTest { * @param classesToBeBound * List of java classes to be recognized by the * {@link JAXBContext}. - * + * * @return XML data or null. - * + * * @param * Type of the data. */ protected static String marshalToStr(final T data, final XmlAdapter[] adapters, - final Class... classesToBeBound) { + final Class... classesToBeBound) { final StringWriter writer = new StringWriter(); @@ -71,4 +70,4 @@ protected static String marshalToStr(final T data, final XmlAdapter[] } } -// CHECKSTYLE:ON + diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/ArchitectureTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/ArchitectureTest.java new file mode 100644 index 00000000..f0365b03 --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/ArchitectureTest.java @@ -0,0 +1,65 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.jaxb; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; +import org.fuin.esc.spi.EscSpiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.activation..", + "jakarta.annotation..", + "jakarta.validation..", + "jakarta.xml.bind..", + "javax.annotation.concurrent..", + "org.apache.commons.lang3..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.fuin.utils4j..", + "org.slf4j..", + "org.w3c.dom.." + ); + + +} + diff --git a/spi/src/test/java/org/fuin/esc/spi/Base64DataTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/Base64DataTest.java similarity index 89% rename from spi/src/test/java/org/fuin/esc/spi/Base64DataTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/Base64DataTest.java index 99a3d76a..a31a768b 100644 --- a/spi/src/test/java/org/fuin/esc/spi/Base64DataTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/Base64DataTest.java @@ -1,21 +1,21 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import org.junit.jupiter.api.Test; @@ -54,7 +54,7 @@ public final void testUnmarshal() throws Exception { assertThat(testee).isNotNull(); assertThat(testee.getEncoded()).isEqualTo("SGVsbG8gd29ybGQh"); assertThat(testee.getDecoded()).isEqualTo( - new byte[] { 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33 }); + new byte[]{72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33}); } diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTest.java new file mode 100644 index 00000000..2a30550f --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTest.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.jaxb; + +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; + +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { + + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); + +} + diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTypeFactoryTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTypeFactoryTest.java new file mode 100644 index 00000000..3c76d66e --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/BaseTypeFactoryTest.java @@ -0,0 +1,29 @@ +package org.fuin.esc.jaxb; + +import jakarta.activation.MimeTypeParseException; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBaseTypeFactory; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for the {@link BaseTypeFactory} class. + */ +public class BaseTypeFactoryTest { + + @Test + void testCreate() throws MimeTypeParseException { + final IBaseTypeFactory testee = new BaseTypeFactory(); + assertThat(testee.createBase64Data("Hello".getBytes(StandardCharsets.UTF_8))).isInstanceOf(Base64Data.class); + assertThat(testee.createEscMeta( + "EventX", + new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"), + "MetaY", + new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"), + "Meta")).isInstanceOf(EscMeta.class); + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/BookAddedEvent.java b/jaxb/src/test/java/org/fuin/esc/jaxb/BookAddedEvent.java similarity index 89% rename from spi/src/test/java/org/fuin/esc/spi/BookAddedEvent.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/BookAddedEvent.java index 41b6aacc..be851c84 100644 --- a/spi/src/test/java/org/fuin/esc/spi/BookAddedEvent.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/BookAddedEvent.java @@ -1,6 +1,6 @@ -// CHECKSTYLE:OFF -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.fuin.esc.api.SerializedDataType; @@ -9,13 +9,18 @@ /** * Example event. */ +@ArchIgnore @XmlRootElement(name = "book-added-event") public class BookAddedEvent { - /** Never changing unique event type name. */ + /** + * Never changing unique event type name. + */ public static final TypeName TYPE = new TypeName("BookAddedEvent"); - - /** Unique name of the serialized type. */ + + /** + * Unique name of the serialized type. + */ public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); @XmlElement @@ -33,11 +38,9 @@ protected BookAddedEvent() { /** * Constructor with name and author. - * - * @param name - * Name. - * @param author - * Author. + * + * @param name Name. + * @param author Author. */ public BookAddedEvent(final String name, final String author) { super(); @@ -103,4 +106,4 @@ public final String toString() { } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/DataTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/DataTest.java similarity index 73% rename from spi/src/test/java/org/fuin/esc/spi/DataTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/DataTest.java index 167f4ecb..5d2c9b7e 100644 --- a/spi/src/test/java/org/fuin/esc/spi/DataTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/DataTest.java @@ -1,29 +1,26 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.JsonObject; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.annotation.adapters.XmlAdapter; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.fuin.esc.api.EnhancedMimeType; import org.fuin.utils4j.jaxb.JaxbUtils; @@ -33,15 +30,17 @@ import org.xmlunit.builder.DiffBuilder; import org.xmlunit.diff.Diff; +import java.util.Base64; + import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.Utils4J.deserialize; import static org.fuin.utils4j.Utils4J.serialize; +import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; /** * Tests the {@link Data} class. */ -// CHECKSTYLE:OFF Test public class DataTest extends AbstractXmlTest { private static final String TYPE = "MyEvent"; @@ -125,9 +124,8 @@ public final void testIcon() throws Exception { // PREPARE final String type = "Icon"; final EnhancedMimeType mimeType = EnhancedMimeType.create("image/png"); - final byte[] png = IOUtils - .toByteArray(getClass().getResourceAsStream("/ok.png")); - final String content = Base64.encodeBase64String(png); + final byte[] png = IOUtils.toByteArray(getClass().getResourceAsStream("/ok.png")); + final String content = Base64.getEncoder().encodeToString(png); final Data original = new Data(type, mimeType, content); // TEST @@ -146,8 +144,7 @@ public final void testIcon() throws Exception { public void testUnmarshalXmlContent() throws JAXBException { // TEST - final BookAddedEvent event = testee.unmarshalContent( - JAXBContext.newInstance(BookAddedEvent.class)); + final BookAddedEvent event = unmarshal(JAXBContext.newInstance(BookAddedEvent.class), testee.getContent(), null); // VERIFY assertThat(event).isNotNull(); @@ -156,32 +153,16 @@ public void testUnmarshalXmlContent() throws JAXBException { } - @Test - public void testUnmarshalJsonContent() throws MimeTypeParseException { - - // PREPARE - final Data data = new Data("BookAddedEvent", - new EnhancedMimeType("application/json; encoding=utf-8"), - "{\"name\":\"Shining\",\"author\":\"Stephen King\"}"); - - // TEST - final JsonObject event = data.unmarshalContent(null); - - // VERIFY - assertThat(event.getString("name")).isEqualTo("Shining"); - assertThat(event.getString("author")).isEqualTo("Stephen King"); - - } - @Test public void testValueOfXml() throws MimeTypeParseException { // PREPARE - final BookAddedEvent event = new BookAddedEvent("Shining", - "Stephen King"); + final BookAddedEvent event = new BookAddedEvent("Shining", "Stephen King"); // TEST - final Data data = Data.valueOf("BookAddedEvent", event); + + final String dataXml = marshal(event, event.getClass()); + final Data data = new Data("BookAddedEvent", EnhancedMimeType.create("application/xml; encoding=utf-8"), dataXml); // VERIFY assertThat(data.getType()).isEqualTo("BookAddedEvent"); @@ -194,30 +175,9 @@ public void testValueOfXml() throws MimeTypeParseException { } - @Test - public void testValueOfJson() throws MimeTypeParseException { - - // PREPARE - final JsonObject event = Json.createObjectBuilder() - .add("name", "Shining").add("author", "Stephen King").build(); - - // TEST - final Data data = Data.valueOf("BookAddedEvent", event); - - // VERIFY - assertThat(data.getType()).isEqualTo("BookAddedEvent"); - assertThat(data.getMimeType()).isEqualTo( - new EnhancedMimeType("application/json; encoding=utf-8")); - assertThat(data.getContent()).isEqualTo( - "{\"name\":\"Shining\",\"author\":\"Stephen King\"}"); - assertThat(data.isXml()).isFalse(); - assertThat(data.isJson()).isTrue(); - - } - private XmlAdapter[] createXmlAdapter() { - return new XmlAdapter[] {}; + return new XmlAdapter[]{}; } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/DataWrapperTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/DataWrapperTest.java similarity index 89% rename from spi/src/test/java/org/fuin/esc/spi/DataWrapperTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/DataWrapperTest.java index 568ae2bd..bd11dbb7 100644 --- a/spi/src/test/java/org/fuin/esc/spi/DataWrapperTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/DataWrapperTest.java @@ -1,21 +1,21 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import org.junit.jupiter.api.Test; @@ -50,7 +50,7 @@ public final void testUnmarshal() throws Exception { // TEST final DataWrapper testee = unmarshal(XML_PREFIX - + "SGVsbG8gd29ybGQh", DataWrapper.class, + + "SGVsbG8gd29ybGQh", DataWrapper.class, Base64Data.class); // VERIFY diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/EscEventTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/EscEventTest.java new file mode 100644 index 00000000..e6600fbe --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/EscEventTest.java @@ -0,0 +1,86 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.diff.Diff; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; +import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; + +/** + * Test for {@link EscEvent} class. + */ +public class EscEventTest { + + @Test + public final void testMarshalUnmarshalJaxb() throws Exception { + + // PREPARE + final String expectedXml = """ + + 68616d90-cf72-4c2a-b913-32bf6e6506ed + MyEvent + + + 68616d90-cf72-4c2a-b913-32bf6e6506ed + Hello, XML! + + + + + MyEvent + application/xml; version=1; encoding=utf-8 + MyMeta + application/xml; version=1; encoding=utf-8 + + abc + + + + + """; + + // TEST + final EscEvent testee = unmarshal(expectedXml, EscEvent.class, EscMeta.class, MyMeta.class, MyEvent.class, Base64Data.class); + + // VERIFY + assertThat(testee).isNotNull(); + assertThat(testee.getEventId()).isEqualTo("68616d90-cf72-4c2a-b913-32bf6e6506ed"); + assertThat(testee.getEventType()).isEqualTo("MyEvent"); + assertThat(testee.getData()).isNotNull(); + assertThat(testee.getData().getObj()).isInstanceOf(MyEvent.class); + assertThat(testee.getMeta()).isNotNull(); + assertThat(testee.getMeta().getObj()).isNotNull(); + assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); + + // TEST + final String xml = marshal(testee, EscEvent.class, EscMeta.class, MyMeta.class, MyEvent.class, Base64Data.class); + + // VERIFY + final Diff documentDiff = DiffBuilder.compare(expectedXml).withTest(xml).ignoreWhitespace().build(); + assertThat(documentDiff.hasDifferences()).describedAs(documentDiff.toString()).isFalse(); + + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/EscEventsTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/EscEventsTest.java similarity index 50% rename from spi/src/test/java/org/fuin/esc/spi/EscEventsTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/EscEventsTest.java index e1a3feea..2ba0f734 100644 --- a/spi/src/test/java/org/fuin/esc/spi/EscEventsTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/EscEventsTest.java @@ -1,27 +1,25 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import jakarta.activation.MimeTypeParseException; -import jakarta.json.bind.Jsonb; import org.apache.commons.io.IOUtils; -import org.eclipse.yasson.FieldAccessStrategy; -import org.fuin.esc.api.*; +import org.fuin.esc.api.EnhancedMimeType; import org.junit.jupiter.api.Test; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.diff.Diff; @@ -31,7 +29,6 @@ import java.util.Map; import java.util.UUID; -import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; @@ -39,14 +36,56 @@ /** * Test for {@link EscEvents} class. */ -// CHECKSTYLE:OFF Test public class EscEventsTest { @Test public final void testMarshalUnmarshalJaxb() throws Exception { // PREPARE - final String expectedXml = IOUtils.toString(this.getClass().getResourceAsStream("/esc-events.xml"), StandardCharsets.UTF_8); + final String expectedXml = """ + + + + 68616d90-cf72-4c2a-b913-32bf6e6506ed + MyEvent + + + eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9 + + + + + MyEvent + application/json; version=1; encoding=utf-8;transfer-encoding=base64 + + MyMeta + application/xml; version=1; encoding=utf-8 + + abc + + + + + + c198a02e-126e-4fbb-910c-918abf39a4a6 + MyEvent + + + + + + MyEvent + application/xml; version=1; encoding=utf-8 + MyMeta + application/xml; version=1; encoding=utf-8 + + abc + + + + + + """; // TEST final EscEvents testee = unmarshal(expectedXml, EscEvents.class, MyMeta.class, MyEvent.class, Base64Data.class); @@ -67,69 +106,6 @@ public final void testMarshalUnmarshalJaxb() throws Exception { } - @Test - public void testMarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-events.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final EscEvents events = new EscEvents(createEvent1(), createEvent2()); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(StandardCharsets.UTF_8) - .build(); - jsonbDeSer.init(typeRegistry); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final String currentJson = jsonb.toJson(events); - - // VERIFY - assertThatJson(currentJson).isEqualTo(expectedJson); - - } - - } - - @Test - public final void testUnmarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-events.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withDeserializers(EscSpiUtils.createEscJsonbDeserializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(StandardCharsets.UTF_8) - .build(); - initSerDeserializerRegistry(typeRegistry, jsonbDeSer); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final EscEvents testee = jsonb.fromJson(expectedJson, EscEvents.class); - - // VERIFY - assertThat(testee.getList()).hasSize(2); - assertThat(testee.getList().get(0).getEventId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); - assertThat(testee.getList().get(1).getEventId()).isEqualTo("68616d90-cf72-4c2a-b913-32bf6e6506ed"); - - } - - } - private EscEvent createEvent1() throws MimeTypeParseException { final UUID eventId = UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"); final MyEvent myEvent = new MyEvent(UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"), "Hello, JSON!"); @@ -157,31 +133,4 @@ private EscEvent createEvent2() throws MimeTypeParseException { return new EscEvent(eventId, MyEvent.TYPE.asBaseType(), new DataWrapper(data), new DataWrapper(escMeta)); } - /** - * Creates a registry that connects the type with the appropriate serializer and de-serializer. - * - * @param typeRegistry - * Type registry (Mapping from type name to class). - * @param jsonbDeSer - * JSON-B serializer/deserializer to use. - */ - private static void initSerDeserializerRegistry(SerializedDataTypeRegistry typeRegistry, - JsonbDeSerializer jsonbDeSer) { - - SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - - // Base types always needed - registry.add(EscEvents.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscEvent.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscMeta.SER_TYPE, "application/json", jsonbDeSer); - - // User defined types - registry.add(MyMeta.SER_TYPE, "application/json", jsonbDeSer); - registry.add(MyEvent.SER_TYPE, "application/json", jsonbDeSer); - - jsonbDeSer.init(typeRegistry, registry, registry); - - } - } -// CHECKSTYLE:ON diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/EscMetaTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/EscMetaTest.java new file mode 100644 index 00000000..63b317af --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/EscMetaTest.java @@ -0,0 +1,62 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.diff.Diff; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; +import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; + +/** + * Test for {@link EscMeta} class. + */ +public class EscMetaTest { + + @Test + public final void testMarshalUnmarshalJaxb() throws Exception { + + // PREPARE + final String expectedXml = """ + + MyEvent + application/xml; version=1; encoding=utf-8 + MyMeta + application/xml; version=1; encoding=utf-8 + + abc + + + """; + + // TEST + final EscMeta testee = unmarshal(expectedXml, EscMeta.class, MyMeta.class, Base64Data.class); + final String actualXml = marshal(testee, EscMeta.class, MyMeta.class, Base64Data.class); + + // VERIFY + final Diff documentDiff = DiffBuilder.compare(expectedXml).withTest(actualXml).ignoreWhitespace().build(); + assertThat(documentDiff.hasDifferences()).describedAs(documentDiff.toString()).isFalse(); + + } + +} diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/EscSpiUtilsTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/EscSpiUtilsTest.java new file mode 100644 index 00000000..334c5946 --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/EscSpiUtilsTest.java @@ -0,0 +1,205 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import jakarta.activation.MimeTypeParseException; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.Deserializer; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.Serializer; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.spi.EscSpiUtils; +import org.fuin.esc.api.IEscMeta; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the {@link EscSpiUtils} class together with {@link EscMeta} implementation of this module. + */ +public class EscSpiUtilsTest { + + @Test + public void testCreateEscMetaTargetXmlDataXmlMetaNull() { + + // PREPARE + final String description = "Whatever"; + final UUID uuid = UUID.randomUUID(); + final MyEvent myEvent = new MyEvent(uuid, description); + final EventId eventId = new EventId(); + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), + EnhancedMimeType.create("application/xml; encoding=UTF-8"), commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; encoding=UTF-8")); + assertThat(result.getMetaType()).isNull(); + assertThat(result.getMetaContentType()).isNull(); + assertThat(result.getMeta()).isNull(); + + } + + @Test + public void testCreateEscMetaTargetJsonDataXmlMetaNull() { + + // PREPARE + final String description = "Whatever"; + final UUID uuid = UUID.randomUUID(); + final MyEvent myEvent = new MyEvent(uuid, description); + final EventId eventId = new EventId(); + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), + EnhancedMimeType.create("application/json"), commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); + assertThat(result.getMetaType()).isNull(); + assertThat(result.getMetaContentType()).isNull(); + assertThat(result.getMeta()).isNull(); + + } + + @Test + public void testCreateEscMetaTargetXmlDataXmlMetaXml() { + + // PREPARE + final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Whatever"); + final EventId eventId = new EventId(); + final MyMeta myMeta = new MyMeta("peter"); + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); + registry.addSerializer(MyMeta.SER_TYPE, new XmlDeSerializer(MyMeta.class)); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, + myMeta); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), + EnhancedMimeType.create("application/xml; encoding=UTF-8"), commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; encoding=UTF-8")); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); + assertThat(result.getMetaContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; encoding=UTF-8")); + assertThat(result.getMeta()).isEqualTo(myMeta); + + } + + @Test + public void testCreateEscMetaTargetJsonDataXmlMetaXml() { + + // PREPARE + final String description = "Whatever"; + final UUID uuid = UUID.randomUUID(); + final MyEvent myEvent = new MyEvent(uuid, description); + final EventId eventId = new EventId(); + final MyMeta myMeta = new MyMeta("peter"); + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); + registry.addSerializer(MyMeta.SER_TYPE, new XmlDeSerializer(MyMeta.class)); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, + myMeta); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), + EnhancedMimeType.create("application/json"), commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); + assertThat(result.getMetaContentType()).isEqualTo( + EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); + assertThat(result.getMeta()).isInstanceOf(Base64Data.class); + final Base64Data base64Meta = (Base64Data) result.getMeta(); + assertThat(new String(base64Meta.getDecoded(), StandardCharsets.UTF_8)).isEqualTo( + "peter"); + + } + + private EnhancedMimeType mimeType(String str) { + try { + return new EnhancedMimeType(str); + } catch (final MimeTypeParseException ex) { + throw new RuntimeException(ex); + } + } + + private Serializer dummySerializer(final String baseType) { + return new Serializer() { + @Override + public byte[] marshal(T obj, SerializedDataType type) { + if (obj == null) { + return null; + } + return obj.toString().getBytes(); + } + + @Override + public EnhancedMimeType getMimeType() { + return mimeType(baseType); + } + }; + } + + private Deserializer dummyDeserializer() { + return new Deserializer() { + @SuppressWarnings("unchecked") + @Override + public T unmarshal(Object data, SerializedDataType type, EnhancedMimeType mimeType) { + if (data instanceof byte[]) { + return (T) new String((byte[]) data); + } + throw new IllegalArgumentException("Unknown input type: " + data); + } + }; + } + + private List asList(CommonEvent... events) { + return new ArrayList<>(Arrays.asList(events)); + } + +} diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/MyEvent.java b/jaxb/src/test/java/org/fuin/esc/jaxb/MyEvent.java new file mode 100644 index 00000000..dc0e6ba6 --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/MyEvent.java @@ -0,0 +1,144 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.io.Serializable; +import java.util.UUID; + +/** + * Something interesting happened. Equals and hash code are based on the UUID. + */ +@ArchIgnore +@XmlRootElement(name = "MyEvent") +public final class MyEvent implements Serializable { + + private static final long serialVersionUID = 100L; + + /** Unique name of the event. */ + public static final TypeName TYPE = new TypeName("MyEvent"); + + /** Unique name of the serialized event. */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @XmlElement(name = "id") + private String id; + + @XmlElement(name = "description") + private String description; + + /** + * Protected default constructor for JAXB. + */ + protected MyEvent() { + super(); + } + + /** + * Constructor with random UUID. + * + * @param description + * The description. + */ + public MyEvent(@NotEmpty final String description) { + super(); + Contract.requireArgNotEmpty("description", description); + this.id = UUID.randomUUID().toString(); + this.description = description; + } + + /** + * Constructor with all mandatory data. + * + * @param uuid + * The unique identifier of the event. + * @param description + * The description. + */ + public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { + super(); + Contract.requireArgNotNull("uuid", uuid); + Contract.requireArgNotEmpty("description", description); + this.id = uuid.toString(); + this.description = description; + } + + /** + * Returns the unique identifier. + * + * @return UUID string. + */ + @NotNull + public final String getId() { + return id; + } + + /** + * Returns the description. + * + * @return The description. + */ + @NotEmpty + public final String getDescription() { + return description; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyEvent other = (MyEvent) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + @Override + public final String toString() { + return "My event: " + description; + } + +} diff --git a/jaxb/src/test/java/org/fuin/esc/jaxb/MyMeta.java b/jaxb/src/test/java/org/fuin/esc/jaxb/MyMeta.java new file mode 100644 index 00000000..5f9e2792 --- /dev/null +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/MyMeta.java @@ -0,0 +1,114 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jaxb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.annotation.Nullable; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; + +import java.io.Serializable; + +/** + * Example meta data. . + */ +@ArchIgnore +@XmlRootElement(name = "MyMeta") +public final class MyMeta implements Serializable { + + private static final long serialVersionUID = 100L; + + /** + * Unique name of the meta type. + */ + public static final TypeName TYPE = new TypeName("MyMeta"); + + /** + * Unique name of the serialized meta type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @XmlElement(name = "user") + private String user; + + /** + * Protected default constructor for JAXB. + */ + protected MyMeta() { + super(); + } + + /** + * Constructor with all mandatory data. + * + * @param user User ID. + */ + public MyMeta(@Nullable final String user) { + super(); + this.user = user; + } + + /** + * Returns the user. + * + * @return User ID. + */ + public final String getUser() { + return user; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((user == null) ? 0 : user.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyMeta other = (MyMeta) obj; + if (user == null) { + if (other.user != null) { + return false; + } + } else if (!user.equals(other.user)) { + return false; + } + return true; + } + + + @Override + public final String toString() { + return "My meta: " + user; + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/XmlDeSerializerTest.java b/jaxb/src/test/java/org/fuin/esc/jaxb/XmlDeSerializerTest.java similarity index 63% rename from spi/src/test/java/org/fuin/esc/spi/XmlDeSerializerTest.java rename to jaxb/src/test/java/org/fuin/esc/jaxb/XmlDeSerializerTest.java index c166dc98..3554cd49 100644 --- a/spi/src/test/java/org/fuin/esc/spi/XmlDeSerializerTest.java +++ b/jaxb/src/test/java/org/fuin/esc/jaxb/XmlDeSerializerTest.java @@ -1,27 +1,39 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.jaxb; import org.fuin.utils4j.TestOmitted; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -// CHECKSTYLE:OFF Test code -@TestOmitted("Class will be moved later to utility library") -public class XmlDeSerializerTest { //NOSONAR +import static org.junit.jupiter.api.Assertions.fail; + + +/** + * Test for the {@link XmlDeSerializer}. + */ +class XmlDeSerializerTest { + + @Disabled("TODO Implement!") + @Test + void testX() { + fail("Implement!"); + } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/resources/ok.png b/jaxb/src/test/resources/ok.png similarity index 100% rename from spi/src/test/resources/ok.png rename to jaxb/src/test/resources/ok.png diff --git a/jpa/META-INF/persistence.xml b/jpa/META-INF/persistence.xml index fd657fef..4645936d 100644 --- a/jpa/META-INF/persistence.xml +++ b/jpa/META-INF/persistence.xml @@ -1,5 +1,7 @@ - - - + + + diff --git a/jpa/README.md b/jpa/README.md index 671422a2..06ba0905 100644 --- a/jpa/README.md +++ b/jpa/README.md @@ -1,44 +1,58 @@ # esc-jpa + Java Persistence API (JPA) based implementation of the event store commons api. ## Entity types -There are two different scenarios: -1. Streams that require one or more discriminator columns +There are two different scenarios: + +1. Streams that require one or more discriminator columns 2. Streams without the need for a discriminator column -An example for streams with discriminator columns is the below mentioned "Vendor" aggregate. There is only one +An example for streams with discriminator columns is the below-mentioned "Vendor" aggregate. There is only one stream entity (table) and one event entity (table) for **all** vendors. The vendor's ID is used as discriminator column to distinguish events for the different vendors. -The discriminator is coded in the [stream identifier](https://github.com/fuinorg/event-store-commons/blob/master/api/src/main/java/org/fuin/esc/api/StreamId.java). An example of an identifier with discriminator column is +The discriminator is coded in +the [stream identifier](https://github.com/fuinorg/event-store-commons/blob/master/api/src/main/java/org/fuin/esc/api/StreamId.java). +An example of an identifier with discriminator column is the [AggregateStreamId](src/test/java/org/fuin/esc/jpa/examples/AggregateStreamId.java) and another one for an -identifier without a discriminator is the [SimpleStreamId](https://github.com/fuinorg/event-store-commons/blob/master/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java). +identifier without a discriminator is +the [SimpleStreamId](https://github.com/fuinorg/event-store-commons/blob/master/api/src/main/java/org/fuin/esc/api/SimpleStreamId.java). The good new is: There is no need to create any entities if you don't need a discriminator column. There are already two predefined entites [NoParamsEvent](src/main/java/org/fuin/esc/jpa/NoParamsEvent.java) and [NoParamsStream](src/main/java/org/fuin/esc/jpa/NoParamsStream.java) that will be used automatically in this case. -For streams that require discriminator columns you have to create two entity classes ("XyzEvent" + "XyzStream") named as described below. +For streams that require discriminator columns you have to create two entity classes ("XyzEvent" + "XyzStream") named as +described below. ## Custom naming of tables and entities -You can use [JpaStreamId](src/main/java/org/fuin/esc/jpa/JpaStreamId.java) to define the names of your stream entities and classes. -There are two predfined classes [SimpleJpaStreamId](src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java) and -[ProjectionJpaStreamId](src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java) that already implement this interface. +You can use [JpaStreamId](src/main/java/org/fuin/esc/jpa/JpaStreamId.java) to define the names of your stream entities +and classes. +There are two predfined classes [SimpleJpaStreamId](src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java) and +[ProjectionJpaStreamId](src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java) that already implement this +interface. ## Default naming conventions + If you don't define an explicit stream name using a [JpaStreamId](src/main/java/org/fuin/esc/jpa/JpaStreamId.java), -a strict default naming convention applies. **You have to name your tables and identifiers exactly as described below otherwise it will not work**. +a strict default naming convention applies. **You have to name your tables and identifiers exactly as described below +otherwise it will not work**. ### StreamId + Use a camel case stream identifier name that ends *not* on 'Stream', 'Streams', 'Event' or 'Events'. + ```java StreamId streamId = new AggregateStreamId("YourSelectedName", discriminatorValue); ``` ### Event entity + Table name is the same as the stream identifier plus '_EVENTS' and uses an 'underscore' for replacing camel case parts. Class name is the same as the stream identifier plus 'Event' (Note that there is no 's' at the end!). + ```java @Table(name = "YOUR_SELECTED_NAME_EVENTS") @Entity @@ -47,9 +61,12 @@ public class YourSelectedNameEvent extends JpaStreamEvent { } ``` -### Stream entity -Table name is the same as the stream identifier plus '_STREAMS' and uses an 'underscore' for replacing camel case parts. +### Stream entity + +Table name is the same as the stream identifier plus '_STREAMS' and uses an 'underscore' for replacing camel case +parts. Class name is the same as the stream identifier plus 'Stream' (Note that there is no 's' at the end!). + ```java @Table(name = "YOUR_SELECTED_NAME_STREAMS") @Entity @@ -59,9 +76,10 @@ public class YourSelectedNameStream extends JpaStream { ``` ## Example JPA entity structure -The UML diagram shows how events of an example "Vendor" aggregate are stored in the database. -A [VendorStream](src/test/java/org/fuin/esc/jpa/examples/VendorStream.java) has information about the stream itself -and [VendorEvent](src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java) has a reference to the event table. + +The UML diagram shows how events of an example "Vendor" aggregate are stored in the database. +A [VendorStream](src/test/java/org/fuin/esc/jpa/examples/VendorStream.java) has information about the stream itself +and [VendorEvent](src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java) has a reference to the event table. The [JpaEvent](src/main/java/org/fuin/esc/jpa/JpaEvent.java) table contains the real event data. ![JPA Entities](https://raw.github.com/fuinorg/event-store-commons/master/jpa/src/main/doc/esc-jpa-example.png) diff --git a/jpa/pom.xml b/jpa/pom.xml index 01753ff9..31548d7b 100644 --- a/jpa/pom.xml +++ b/jpa/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 @@ -58,22 +58,51 @@ - org.apache.commons - commons-lang3 + org.slf4j + slf4j-api - org.slf4j - slf4j-api + com.google.code.findbugs + jsr305 + + + + org.fuin.objects4j + objects4j-common - io.github.threeten-jaxb - threeten-jaxb-core + jakarta.annotation + jakarta.annotation-api + + org.fuin.esc + esc-jaxb + test + + + + org.fuin.esc + esc-jsonb + test + + + + org.glassfish.jaxb + jaxb-runtime + test + + + + org.eclipse + yasson + test + + org.junit.jupiter junit-jupiter @@ -86,11 +115,6 @@ test - - io.smallrye - jandex - - nl.jqno.equalsverifier equalsverifier @@ -109,26 +133,50 @@ - org.hibernate - hibernate-core-jakarta + org.hibernate + hibernate-core-jakarta test - org.hsqldb + org.hsqldb hsqldb test - org.eclipse - yasson + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 test - org.glassfish - jakarta.el + org.fuin + units4j + test + + + + jakarta.json.bind + jakarta.json.bind-api + test + + + + jakarta.xml.bind + jakarta.xml.bind-api + test + + + + org.fuin + utils4j test @@ -173,6 +221,30 @@ maven-jdeps-plugin + + org.apache.maven.plugins + maven-dependency-plugin + + + jakarta.el:jakarta.el-api + org.glassfish:jakarta.el + org.hibernate.validator:hibernate-validator + org.glassfish.jaxb:jaxb-runtime + ch.qos.logback:logback-classic + org.hibernate:hibernate-core-jakarta + org.hibernate.orm:hibernate-core + org.eclipse:yasson + org.hsqldb:hsqldb + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + + diff --git a/jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java b/jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java index 25caa5ad..154a0f5e 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -23,8 +23,21 @@ import jakarta.persistence.TypedQuery; import jakarta.persistence.metamodel.EntityType; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.*; -import org.fuin.esc.spi.*; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.EventNotFoundException; +import org.fuin.esc.api.ReadableEventStore; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializerRegistry; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.StreamDeletedException; +import org.fuin.esc.api.StreamEventsSlice; +import org.fuin.esc.api.StreamId; +import org.fuin.esc.api.StreamNotFoundException; +import org.fuin.esc.api.StreamState; +import org.fuin.esc.spi.AbstractReadableEventStore; +import org.fuin.esc.spi.EscSpiUtils; +import org.fuin.esc.spi.SerializedData; import org.fuin.objects4j.common.ConstraintViolationException; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.core.KeyValue; @@ -59,7 +72,7 @@ public abstract class AbstractJpaEventStore extends AbstractReadableEventStore i /** * Constructor with all mandatory data. - * + * * @param em * Entity manager. * @param serRegistry @@ -68,7 +81,7 @@ public abstract class AbstractJpaEventStore extends AbstractReadableEventStore i * Registry used to locate deserializers. */ public AbstractJpaEventStore(@NotNull final EntityManager em, - @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { + @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { super(); Contract.requireArgNotNull("em", em); Contract.requireArgNotNull("serRegistry", serRegistry); @@ -81,7 +94,7 @@ public AbstractJpaEventStore(@NotNull final EntityManager em, /** * Returns the entity manager. - * + * * @return Entity manager. */ protected final EntityManager getEm() { @@ -90,7 +103,7 @@ protected final EntityManager getEm() { /** * Returns a registry of serializers. - * + * * @return Registry with known serializers. */ @NotNull @@ -100,7 +113,7 @@ protected final SerializerRegistry getSerializerRegistry() { /** * Returns a registry of deserializers. - * + * * @return Registry with known deserializers. */ @NotNull @@ -155,7 +168,7 @@ public final CommonEvent readEvent(final StreamId streamId, final long eventNumb @SuppressWarnings("unchecked") @Override public final StreamEventsSlice readEventsForward(final StreamId streamId, final long start, - final int count) { + final int count) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("start", start, 0); @@ -170,7 +183,7 @@ public final StreamEventsSlice readEventsForward(final StreamId streamId, final } if (!projection.isEnabled()) { // The projection does exist, but is not ready yet - return new StreamEventsSlice(start, new ArrayList(), start, true); + return new StreamEventsSlice(start, new ArrayList<>(), start, true); } } else { final JpaStream stream = findStream(streamId); @@ -204,7 +217,7 @@ public final StreamEventsSlice readEventsForward(final StreamId streamId, final @SuppressWarnings("unchecked") @Override public final StreamEventsSlice readEventsBackward(final StreamId streamId, final long start, - final int count) { + final int count) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("start", start, 0); @@ -266,7 +279,7 @@ public final boolean streamExists(final StreamId streamId) { final TypedQuery query = getEm().createQuery(sql, JpaStream.class); setJpqlParameters(query, streamId); final List streams = query.getResultList(); - if (streams.size() == 0) { + if (streams.isEmpty()) { return false; } if (streams.size() == 1) { @@ -292,7 +305,7 @@ public final StreamState streamState(final StreamId streamId) { /** * Verifies if a stream entity exists or throws an * {@link StreamNotFoundException} otherwise. - * + * * @param streamId * Stream to test. */ @@ -304,10 +317,10 @@ protected final void verifyStreamEntityExists(final StreamId streamId) { /** * Returns if a stream entity exists. - * + * * @param streamId * Stream to test. - * + * * @return TRUE if the entity is known, else FALSE. */ protected final boolean streamEntityExists(final StreamId streamId) { @@ -315,11 +328,11 @@ protected final boolean streamEntityExists(final StreamId streamId) { } /** - * Returns if an entity with agiven name exists. - * + * Returns if an entity with a given name exists. + * * @param entityName * Entity to test. - * + * * @return TRUE if the entity is known, else FALSE. */ protected final boolean entityExists(final String entityName) { @@ -335,12 +348,12 @@ protected final boolean entityExists(final String entityName) { /** * Tries to find a serializer for the given type of object and converts it * into a storable data block. - * + * * @param type * Type of event. * @param data * Event of the given type. - * + * * @return Event ready to persist. */ protected final SerializedData serialize(final SerializedDataType type, final Object data) { @@ -349,12 +362,12 @@ protected final SerializedData serialize(final SerializedDataType type, final Ob /** * Tries to find a deserializer for the given data block. - * + * * @param data * Persisted data. - * + * * @return Unmarshalled event. - * + * * @param * Expected type of event. */ @@ -364,10 +377,10 @@ protected final T deserialize(final SerializedData data) { /** * Creates the JPQL to select the stream itself. - * + * * @param streamId * Unique stream identifier. - * + * * @return JPQL that selects the stream with the given identifier. */ protected final String createJpqlStreamSelect(final StreamId streamId) { @@ -377,7 +390,7 @@ protected final String createJpqlStreamSelect(final StreamId streamId) { } final List params = new ArrayList<>(streamId.getParameters()); - if (params.size() == 0) { + if (params.isEmpty()) { // NoParamsStream params.add(new KeyValue("streamName", streamId.getName())); } @@ -395,10 +408,10 @@ protected final String createJpqlStreamSelect(final StreamId streamId) { /** * Reads the stream with the given identifier from the DB and returns it. - * + * * @param streamId * Stream to load. - * + * * @return Stream. */ @NotNull @@ -411,7 +424,7 @@ protected final JpaStream findStream(@NotNull final StreamId streamId) { final TypedQuery query = getEm().createQuery(sql, JpaStream.class); setJpqlParameters(query, streamId); final List streams = query.getResultList(); - if (streams.size() == 0) { + if (streams.isEmpty()) { throw new StreamNotFoundException(streamId); } final JpaStream stream = streams.get(0); @@ -427,7 +440,7 @@ protected final JpaStream findStream(@NotNull final StreamId streamId) { /** * Sets parameters in a query. - * + * * @param query * Query to set parameters for. * @param streamId @@ -435,27 +448,24 @@ protected final JpaStream findStream(@NotNull final StreamId streamId) { */ protected final void setJpqlParameters(final Query query, final StreamId streamId) { final List params = new ArrayList<>(streamId.getParameters()); - if (params.size() == 0) { + if (params.isEmpty()) { params.add(new KeyValue("streamName", streamId.getName())); } - for (int i = 0; i < params.size(); i++) { - final KeyValue param = params.get(i); + for (final KeyValue param : params) { query.setParameter(param.getKey(), param.getValue()); } } /** * Sets parameters in a query. - * + * * @param query * Query to set parameters for. - * @param streamId - * Unique stream identifier that has the parameter values. - * @param additionalConditions + * @param conditions * Parameters to add in addition to the ones from the stream * identifier. */ - private final void setNativeSqlParameters(final Query query, final List conditions) { + private void setNativeSqlParameters(final Query query, final List conditions) { for (final NativeSqlCondition condition : conditions) { query.setParameter(condition.getColumn(), condition.getValue()); } @@ -464,17 +474,17 @@ private final void setNativeSqlParameters(final Query query, final List conditions) { + private String createNativeSqlEventSelect(final StreamId streamId, + final List conditions) { final StringBuilder sb = new StringBuilder("SELECT " + JPA_EVENT_PREFIX + ".* FROM " + JpaEvent.TABLE_NAME + " " + JPA_EVENT_PREFIX + ", " + nativeEventsTableName(streamId) + " " @@ -499,14 +509,14 @@ private String createOrderBy(final StreamId streamId, final boolean asc) { } private List createNativeSqlConditions(final StreamId streamId, - final NativeSqlCondition... additionalConditions) { + final NativeSqlCondition... additionalConditions) { final List conditions; if (additionalConditions == null) { conditions = new ArrayList<>(); } else { conditions = new ArrayList<>(Arrays.asList(additionalConditions)); } - if (streamId.getParameters().size() == 0) { + if (streamId.getParameters().isEmpty()) { conditions.add(new NativeSqlCondition(JPA_STREAM_EVENT_PREFIX, NoParamsEvent.COLUMN_STREAM_NAME, "=", streamId.getName())); } else { diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaData.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaData.java index 11a6b775..b02e0f4f 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaData.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaData.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,14 +21,13 @@ import jakarta.persistence.Embeddable; import jakarta.persistence.Lob; import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlInlineBinaryData; -import org.fuin.esc.api.TypeName; import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.TypeName; import org.fuin.esc.spi.SerializedData; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.common.ValueObject; +import javax.annotation.concurrent.Immutable; import java.io.Serializable; import java.util.Arrays; @@ -54,7 +53,6 @@ public class JpaData implements ValueObject, Serializable { /** Raw event data in format defined by the mime type and encoding. */ @Lob @Column(name = "DATA_RAW", nullable = false) - @XmlInlineBinaryData private byte[] raw; /** @@ -66,7 +64,7 @@ protected JpaData() { //NOSONAR Ignore uninitialized fields /** * Creates a data object. - * + * * @param typeName * Unique identifier for the type of data. * @param mimeType @@ -75,7 +73,7 @@ protected JpaData() { //NOSONAR Ignore uninitialized fields * Raw data block. */ public JpaData(@NotNull final TypeName typeName, - @NotNull final EnhancedMimeType mimeType, @NotNull final byte[] raw) { + @NotNull final EnhancedMimeType mimeType, @NotNull final byte[] raw) { super(); Contract.requireArgNotNull("type", typeName); @@ -91,7 +89,7 @@ public JpaData(@NotNull final TypeName typeName, * Copies a given SPI data object. Caution: To avoid performance problems * this will just copy the reference to the by array, means it does not copy * the bytes in the array itself. - * + * * @param data * Data to copy. */ @@ -105,7 +103,7 @@ public JpaData(@NotNull final SerializedData data) { /** * Returns the unique identifier for the type of data. - * + * * @return Unique and never changing type name. */ @NotNull @@ -115,7 +113,7 @@ public final TypeName getTypeName() { /** * Returns the Internet Media Type that classifies the data. - * + * * @return Mime type. */ @NotNull @@ -125,7 +123,7 @@ public final EnhancedMimeType getMimeType() { /** * Returns the raw data block. - * + * * @return Raw data. */ @NotNull @@ -133,7 +131,6 @@ public final byte[] getRaw() { return raw; } - // CHECKSTYLE:OFF Generated code @Override public final int hashCode() { final int prime = 31; @@ -151,9 +148,8 @@ public final boolean equals(Object obj) { return true; if (obj == null) return false; - if (!(obj instanceof JpaData)) + if (!(obj instanceof JpaData other)) return false; - JpaData other = (JpaData) obj; if (mimeType == null) { if (other.mimeType != null) return false; @@ -162,13 +158,9 @@ public final boolean equals(Object obj) { if (!Arrays.equals(raw, other.raw)) return false; if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; + return other.type == null; + } else return type.equals(other.type); } - // CHECKSTYLE:ON } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaEvent.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaEvent.java index fdb86869..c916266c 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaEvent.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaEvent.java @@ -1,27 +1,35 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa; -import io.github.threetenjaxb.core.ZonedDateTimeXmlAdapter; import jakarta.annotation.Nullable; -import jakarta.persistence.*; +import jakarta.persistence.AttributeOverride; +import jakarta.persistence.AttributeOverrides; +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.PrePersist; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.fuin.esc.api.EventId; import java.time.ZonedDateTime; @@ -52,7 +60,6 @@ public class JpaEvent { @Column(name = COLUMN_EVENT_ID, length = 36, nullable = false, columnDefinition = "VARCHAR(36)") private String eventId; - @XmlJavaTypeAdapter(ZonedDateTimeXmlAdapter.class) @Column(name = "created", nullable = false) private ZonedDateTime created; @@ -61,9 +68,9 @@ public class JpaEvent { private JpaData data; @Embedded - @AttributeOverrides({ @AttributeOverride(name = "type", column = @Column(name = "META_TYPE")), + @AttributeOverrides({@AttributeOverride(name = "type", column = @Column(name = "META_TYPE")), @AttributeOverride(name = "mimeType", column = @Column(name = "META_MIME_TYPE")), - @AttributeOverride(name = "raw", column = @Column(name = "META_RAW")) }) + @AttributeOverride(name = "raw", column = @Column(name = "META_RAW"))}) private JpaData meta; /** @@ -74,8 +81,8 @@ protected JpaEvent() { //NOSONAR Ignore uninitialized fields } /** - * Constructor without meta data. - * + * Constructor without metadata. + * * @param eventId * Unique identifier of the event. Generated on the client and * used to achieve idempotence when trying to append the same @@ -89,7 +96,7 @@ public JpaEvent(@NotNull final EventId eventId, @NotNull final JpaData data) { /** * Constructor with all data. - * + * * @param eventId * Unique identifier of the event. Generated on the client and * used to achieve idempotence when trying to append the same @@ -100,7 +107,7 @@ public JpaEvent(@NotNull final EventId eventId, @NotNull final JpaData data) { * Meta data (Optional). */ public JpaEvent(@NotNull final EventId eventId, @NotNull final JpaData data, - @Nullable final JpaData meta) { + @Nullable final JpaData meta) { super(); this.eventId = eventId.asBaseType().toString(); this.data = data; @@ -109,7 +116,7 @@ public JpaEvent(@NotNull final EventId eventId, @NotNull final JpaData data, /** * Returns the unique identifier of the entry. - * + * * @return Unique entry ID. */ public Long getId() { @@ -120,7 +127,7 @@ public Long getId() { * Returns the unique identifier of the event. Generated on the client and * used to achieve idempotence when trying to append the same event multiple * times. - * + * * @return Unique event ID. */ @NotNull @@ -130,7 +137,7 @@ public EventId getEventId() { /** * Returns the time when the event was created. - * + * * @return Date, time and zone of event's creation. */ @NotNull @@ -140,7 +147,7 @@ public ZonedDateTime getCreated() { /** * Returns the data of the event. - * + * * @return The event. */ @NotNull @@ -149,9 +156,9 @@ public JpaData getData() { } /** - * Returns the meta data of the event (Optional). - * - * @return The event's meta data or NULL. + * Returns the metadata of the event (Optional). + * + * @return The event's metadata or NULL. */ public JpaData getMeta() { return meta; diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaEventStore.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaEventStore.java index 99f29e4a..c3697c27 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaEventStore.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,8 +21,21 @@ import jakarta.persistence.LockModeType; import jakarta.persistence.TypedQuery; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.*; -import org.fuin.esc.spi.*; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.EventStore; +import org.fuin.esc.api.ExpectedVersion; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializerRegistry; +import org.fuin.esc.api.StreamAlreadyExistsException; +import org.fuin.esc.api.StreamDeletedException; +import org.fuin.esc.api.StreamEventsSlice; +import org.fuin.esc.api.StreamId; +import org.fuin.esc.api.StreamReadOnlyException; +import org.fuin.esc.api.StreamState; +import org.fuin.esc.api.WrongExpectedVersionException; +import org.fuin.esc.spi.EscSpiUtils; +import org.fuin.esc.spi.SerializedData; import org.fuin.objects4j.common.Contract; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,11 +51,11 @@ public final class JpaEventStore extends AbstractJpaEventStore implements EventS private static final Logger LOG = LoggerFactory.getLogger(JpaEventStore.class); - private JpaIdStreamFactory streamFactory; + private final JpaIdStreamFactory streamFactory; /** * Constructor with all mandatory data. - * + * * @param em * Entity manager. * @param streamFactory @@ -53,41 +66,41 @@ public final class JpaEventStore extends AbstractJpaEventStore implements EventS * Registry used to locate deserializers. */ public JpaEventStore(@NotNull final EntityManager em, @NotNull final JpaIdStreamFactory streamFactory, - @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { + @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { super(em, serRegistry, desRegistry); Contract.requireArgNotNull("streamFactory", streamFactory); this.streamFactory = streamFactory; } @Override - public final void createStream(final StreamId streamId) throws StreamAlreadyExistsException { + public void createStream(final StreamId streamId) throws StreamAlreadyExistsException { // Do nothing as the operation is not supported } @Override - public final boolean isSupportsCreateStream() { + public boolean isSupportsCreateStream() { return false; } - + @Override - public final long appendToStream(final StreamId streamId, final CommonEvent... events) { + public long appendToStream(final StreamId streamId, final CommonEvent... events) { return appendToStream(streamId, ANY.getNo(), EscSpiUtils.asList(events)); } @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, - final CommonEvent... events) { + public long appendToStream(final StreamId streamId, final long expectedVersion, + final CommonEvent... events) { return appendToStream(streamId, expectedVersion, EscSpiUtils.asList(events)); } @Override - public final long appendToStream(final StreamId streamId, final List events) { + public long appendToStream(final StreamId streamId, final List events) { return appendToStream(streamId, ANY.getNo(), events); } @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, - final List toAppend) { + public long appendToStream(final StreamId streamId, final long expectedVersion, + final List toAppend) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("expectedVersion", expectedVersion, ExpectedVersion.ANY.getNo()); @@ -97,7 +110,7 @@ public final long appendToStream(final StreamId streamId, final long expectedVer if (streamId.isProjection()) { throw new StreamReadOnlyException(streamId); } - + JpaStream stream = findAndLockJpaStream(streamId); if (stream == null) { LOG.debug("Stream '{}' not found, creating it", streamId); @@ -132,12 +145,12 @@ public final long appendToStream(final StreamId streamId, final long expectedVer } @Override - public final void deleteStream(final StreamId streamId, final boolean hardDelete) { + public void deleteStream(final StreamId streamId, final boolean hardDelete) { deleteStream(streamId, ANY.getNo(), hardDelete); } @Override - public final void deleteStream(final StreamId streamId, final long expected, final boolean hardDelete) { + public void deleteStream(final StreamId streamId, final long expected, final boolean hardDelete) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("expected", expected, ExpectedVersion.ANY.getNo()); @@ -146,7 +159,7 @@ public final void deleteStream(final StreamId streamId, final long expected, fin if (streamId.isProjection()) { throw new StreamReadOnlyException(streamId); } - + final JpaStream stream = findAndLockJpaStream(streamId); if (stream == null) { // Stream never existed @@ -187,7 +200,7 @@ private JpaStream findAndLockJpaStream(final StreamId streamId) { setJpqlParameters(query, streamId); query.setLockMode(LockModeType.PESSIMISTIC_WRITE); final List streams = query.getResultList(); - if (streams.size() == 0) { + if (streams.isEmpty()) { return null; } if (streams.size() == 1) { diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaIdStreamFactory.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaIdStreamFactory.java index 3220d92b..6b8a0bed 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaIdStreamFactory.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaIdStreamFactory.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -27,22 +27,22 @@ public interface JpaIdStreamFactory { /** * Checks if the factory can create a stream based on a given stream * identifier. - * + * * @param streamId * Identifier to create a stream for. - * + * * @return TRUE if a stream can be created using the identifier. */ - public boolean containsType(StreamId streamId); + boolean containsType(StreamId streamId); /** * Creates a new stream instance (without persisting it). - * + * * @param streamId * Stream identifier to create an instance for. - * + * * @return New object. */ - public JpaStream createStream(StreamId streamId); + JpaStream createStream(StreamId streamId); } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaProjection.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaProjection.java index e749e22a..d437ea06 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaProjection.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaProjection.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -48,7 +48,7 @@ protected JpaProjection() { //NOSONAR Ignore uninitialized fields /** * Constructor with all mandatory data. - * + * * @param name * Unique name for the projection. */ @@ -60,7 +60,7 @@ public JpaProjection(@NotNull final String name) { /** * Constructor with all data. - * + * * @param name * Unique name for the projection. * @param enabled @@ -75,14 +75,13 @@ public JpaProjection(@NotNull final String name, final boolean enabled) { /** * Returns the information if the query is enabled. - * + * * @return FALSE if the query is being created, else TRUE. */ public boolean isEnabled() { return enabled; } - // CHECKSTYLE:OFF Generated code @Override public int hashCode() { final int prime = 31; @@ -97,18 +96,13 @@ public boolean equals(final Object obj) { return true; if (obj == null) return false; - if (!(obj instanceof JpaProjection)) + if (!(obj instanceof JpaProjection other)) return false; - JpaProjection other = (JpaProjection) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; + return other.name == null; + } else return name.equals(other.name); } - // CHECKSTYLE:ON @Override public String toString() { diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaStream.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaStream.java index 23d0d1a9..4b3f82b1 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaStream.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaStream.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -37,7 +37,7 @@ public abstract class JpaStream { /** * Returns the state of the stream. - * + * * @return State. */ public StreamState getState() { @@ -46,7 +46,7 @@ public StreamState getState() { /** * Returns the information if the stream was deleted. - * + * * @return TRUE if soft or hard deleted. */ public boolean isDeleted() { @@ -55,7 +55,7 @@ public boolean isDeleted() { /** * Marks the stream as deleted. - * + * * @param hardDelete * Hard or soft deletion. */ @@ -69,7 +69,7 @@ public void delete(final boolean hardDelete) { /** * Returns the current version of the stream. - * + * * @return Version. */ public long getVersion() { @@ -78,7 +78,7 @@ public long getVersion() { /** * Increments the version of the stream by one. - * + * * @return New version. */ public long incVersion() { @@ -92,7 +92,7 @@ public long incVersion() { * The unique identifier of the stream to create an event for. * @param eventEntry * Event entry to convert into a JPA variant. - * + * * @return JPA entity. */ public abstract JpaStreamEvent createEvent(@NotNull StreamId streamId, @NotNull JpaEvent eventEntry); diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamEvent.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamEvent.java index 128382f6..22edf564 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamEvent.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamEvent.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,11 +31,11 @@ public abstract class JpaStreamEvent { /** SQL EVENT ID column name. */ public static final String COLUMN_EVENTS_ID = "events_id"; - - /** Column event number - Defined in sub classes as part of the composite identifier. */ + + /** Column event number - Defined in subclasses as part of the composite identifier. */ public static final String COLUMN_EVENT_NUMBER = "event_number"; - - + + @NotNull @ManyToOne(optional = false) @JoinColumn(name = COLUMN_EVENTS_ID, nullable = false, updatable = false) @@ -50,7 +50,7 @@ protected JpaStreamEvent() { //NOSONAR Ignore uninitialized fields /** * Constructs a stream event. - * + * * @param event * Event to be connected with this event stream. */ @@ -62,7 +62,7 @@ public JpaStreamEvent(@NotNull final JpaEvent event) { /** * Returns the actual event. - * + * * @return Event connected with this stream */ @NotNull diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamId.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamId.java index 011e1a5f..397c74ea 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamId.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -26,16 +26,16 @@ public interface JpaStreamId extends StreamId { /** * Returns the name of the entity class. - * + * * @return Name of the entity that has the {@link jakarta.persistence.Table} JPA annotation. */ - public String getEntityName(); + String getEntityName(); /** * Returns the name of the database table to use for the stream. - * + * * @return Name that is configured in the {@link jakarta.persistence.Table} JPA annotation. */ - public String getNativeTableName(); + String getNativeTableName(); } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/JpaUtils.java b/jpa/src/main/java/org/fuin/esc/jpa/JpaUtils.java index cf233ae1..b1de1c4a 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/JpaUtils.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/JpaUtils.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,10 +31,10 @@ private JpaUtils() { /** * Returns the name of the stream entity for a given stream. - * + * * @param streamId * Identifier of the stream to return a stream entity name for. - * + * * @return Name of the entity (simple class name). */ public static String streamEntityName(final StreamId streamId) { @@ -47,40 +47,39 @@ public static String streamEntityName(final StreamId streamId) { if (streamId.isProjection()) { return streamId.getName(); } - if (streamId.getParameters().size() == 0) { + if (streamId.getParameters().isEmpty()) { return NoParamsStream.class.getSimpleName(); } return streamId.getName() + "Stream"; } - + /** * Returns a native database events table name. - * + * * @param streamId Unique stream identifier. - * + * * @return Name that is configured in the {@link jakarta.persistence.Table} JPA annotation. */ public static String nativeEventsTableName(final StreamId streamId) { // User defined ID - if (streamId instanceof JpaStreamId) { - final JpaStreamId jpaId = (JpaStreamId) streamId; + if (streamId instanceof JpaStreamId jpaId) { return jpaId.getNativeTableName(); } // Default ID if (streamId.isProjection()) { return camel2Underscore(streamId.getName()); } - if (streamId.getParameters().size() == 0) { + if (streamId.getParameters().isEmpty()) { return NoParamsEvent.NO_PARAMS_EVENTS_TABLE; } return camel2Underscore(streamId.getName()) + "_events"; } - + /** * Converts the given camel case name into a name with underscores. - * + * * @param name Name to convert. - * + * * @return Camel case replaced with underscores. */ public static String camel2Underscore(@Nullable final String name) { @@ -90,6 +89,5 @@ public static String camel2Underscore(@Nullable final String name) { return name.replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase(); } - - + } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/NativeSqlCondition.java b/jpa/src/main/java/org/fuin/esc/jpa/NativeSqlCondition.java index 6685fea5..a34e2e0d 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/NativeSqlCondition.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/NativeSqlCondition.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -34,7 +34,7 @@ public final class NativeSqlCondition { /** * Constructor with all mandatory data. - * + * * @param column * Name of the DB column. * @param operator @@ -48,7 +48,7 @@ public NativeSqlCondition(final String column, final String operator, final Obje /** * Constructor with all possible data. - * + * * @param table * Optional table prefix. * @param column @@ -59,7 +59,7 @@ public NativeSqlCondition(final String column, final String operator, final Obje * Value of the attribute. */ public NativeSqlCondition(final String table, final String column, final String operator, - final Object value) { + final Object value) { Contract.requireArgNotNull("column", column); Contract.requireArgNotNull("operator", operator); Contract.requireArgNotNull("value", value); @@ -68,49 +68,49 @@ public NativeSqlCondition(final String table, final String column, final String this.operator = operator; this.value = value; } - + /** * Returns the table name. - * + * * @return Optional table name or prefix. */ - public final String getTable() { + public String getTable() { return table; } /** * Returns the name of the table column. - * + * * @return Column name. */ - public final String getColumn() { + public String getColumn() { return column; } -/** + /** * Returns the operator for comparing the value. - * + * * @return Operator like '=' or '<'. */ - public final String getOperator() { + public String getOperator() { return operator; } /** * Returns the value to compare with. - * + * * @return Value. */ - public final Object getValue() { + public Object getValue() { return value; } /** * Returns the 'where' condition with a parameter. - * + * * @return Native SQL 'where' with column name as parameter. */ - public final String asWhereConditionWithParam() { + public String asWhereConditionWithParam() { if (table == null) { return column + operator + ":" + column; } @@ -118,7 +118,7 @@ public final String asWhereConditionWithParam() { } @Override - public final String toString() { + public String toString() { if (table == null) { return column + operator + column; } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEvent.java b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEvent.java index ceb94a9b..3bf13a3e 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEvent.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEvent.java @@ -1,23 +1,27 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.IdClass; +import jakarta.persistence.Table; import jakarta.validation.constraints.NotNull; import org.fuin.esc.api.StreamId; import org.fuin.objects4j.common.Contract; @@ -55,7 +59,7 @@ protected NoParamsEvent() { //NOSONAR Ignore uninitialized fields /** * Constructor with all mandatory data. - * + * * @param streamId * Unique identifier of the stream. * @param version @@ -64,7 +68,7 @@ protected NoParamsEvent() { //NOSONAR Ignore uninitialized fields * Event to store. */ public NoParamsEvent(@NotNull final StreamId streamId, @NotNull final Long version, - @NotNull final JpaEvent jpaEvent) { + @NotNull final JpaEvent jpaEvent) { super(jpaEvent); Contract.requireArgNotNull("streamId", streamId); Contract.requireArgNotNull("version", version); @@ -74,7 +78,7 @@ public NoParamsEvent(@NotNull final StreamId streamId, @NotNull final Long versi /** * Returns the name of the stream. - * + * * @return Unique identifier name of the stream. */ public String getStreamName() { @@ -83,14 +87,13 @@ public String getStreamName() { /** * Returns the number of the stream. - * + * * @return Number that is unique in combination with the name. */ public Long getEventNumber() { return eventNumber; } - // CHECKSTYLE:OFF Generated code @Override public int hashCode() { @@ -121,16 +124,10 @@ public boolean equals(Object obj) { return false; } if (eventNumber == null) { - if (other.eventNumber != null) { - return false; - } - } else if (!eventNumber.equals(other.eventNumber)) { - return false; - } - return true; + return other.eventNumber == null; + } else return eventNumber.equals(other.eventNumber); } - // CHECKSTYLE:ON @Override public String toString() { diff --git a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEventPrimaryKey.java b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEventPrimaryKey.java index 75eed2e4..7e76d6a7 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEventPrimaryKey.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsEventPrimaryKey.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -43,7 +43,7 @@ public NoParamsEventPrimaryKey() { /** * Constructor with all required data. - * + * * @param streamId * Unique stream identifier. * @param eventNumber @@ -59,27 +59,26 @@ public NoParamsEventPrimaryKey(@NotNull final StreamId streamId, @NotNull final /** * Returns the name of the stream. - * + * * @return Unique stream identifier name. */ @NotNull - public final String getStreamName() { + public String getStreamName() { return streamName; } /** * Returns the number of the event within the stream. - * + * * @return Order of the event in the stream. */ @NotNull - public final Long getEventNumber() { + public Long getEventNumber() { return eventNumber; } - // CHECKSTYLE:OFF Generated code @Override - public final int hashCode() { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((streamName == null) ? 0 : streamName.hashCode()); @@ -88,7 +87,7 @@ public final int hashCode() { } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) @@ -102,17 +101,13 @@ public final boolean equals(final Object obj) { } else if (!streamName.equals(other.streamName)) return false; if (eventNumber == null) { - if (other.eventNumber != null) - return false; - } else if (!eventNumber.equals(other.eventNumber)) - return false; - return true; + return other.eventNumber == null; + } else return eventNumber.equals(other.eventNumber); } - // CHECKSTYLE:ON @Override - public final String toString() { + public String toString() { return streamName + "-" + eventNumber; } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsStream.java b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsStream.java index 581cd547..bf2e1cc7 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/NoParamsStream.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/NoParamsStream.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -46,7 +46,7 @@ protected NoParamsStream() { //NOSONAR Ignore uninitialized fields /** * Constructor with mandatory data. - * + * * @param streamId * Unique stream identifier. */ diff --git a/jpa/src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java b/jpa/src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java index 6b4ce93b..6958444b 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/ProjectionJpaStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,9 +19,9 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.KeyValue; +import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; @@ -34,12 +34,12 @@ public final class ProjectionJpaStreamId implements JpaStreamId { private static final long serialVersionUID = 1L; private final String entityName; - + private final String nativeTableName; /** * Constructor with mandatory data. - * + * * @param entityName * Unique entity name (Simple JPA entity class name). * @param nativeTableName @@ -53,47 +53,47 @@ public ProjectionJpaStreamId(@NotNull final String entityName, @NotNull final St } @Override - public final String getName() { + public String getName() { return entityName; } @Override - public final boolean isProjection() { + public boolean isProjection() { return true; } @Override - public final String getEntityName() { + public String getEntityName() { return entityName; } @Override - public final String getNativeTableName() { + public String getNativeTableName() { return nativeTableName; } - + @Override - public final T getSingleParamValue() { + public T getSingleParamValue() { throw new UnsupportedOperationException(getClass().getSimpleName() + " has no parameters"); } @Override - public final List getParameters() { + public List getParameters() { return Collections.emptyList(); } @Override - public final String asString() { + public String asString() { return entityName; } @Override - public final int hashCode() { + public int hashCode() { return entityName.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -108,7 +108,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return entityName; } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/ReadableJpaEventStore.java b/jpa/src/main/java/org/fuin/esc/jpa/ReadableJpaEventStore.java index 19618cf2..7917b1aa 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/ReadableJpaEventStore.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/ReadableJpaEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,7 +29,7 @@ public final class ReadableJpaEventStore extends AbstractJpaEventStore { /** * Constructor with all mandatory data. - * + * * @param em * Entity manager. * @param serRegistry @@ -38,7 +38,7 @@ public final class ReadableJpaEventStore extends AbstractJpaEventStore { * Registry used to locate deserializers. */ public ReadableJpaEventStore(@NotNull final EntityManager em, - @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { + @NotNull final SerializerRegistry serRegistry, @NotNull final DeserializerRegistry desRegistry) { super(em, serRegistry, desRegistry); } diff --git a/jpa/src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java b/jpa/src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java index dece151b..e94061d2 100644 --- a/jpa/src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java +++ b/jpa/src/main/java/org/fuin/esc/jpa/SimpleJpaStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,9 +19,9 @@ import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; import org.fuin.objects4j.core.KeyValue; +import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; @@ -34,12 +34,12 @@ public final class SimpleJpaStreamId implements JpaStreamId { private static final long serialVersionUID = 1L; private final String entityName; - + private final String nativeTableName; /** * Constructor with mandatory data. - * + * * @param entityName * Unique entity name (Simple JPA entity class name). * @param nativeTableName @@ -53,47 +53,47 @@ public SimpleJpaStreamId(@NotNull final String entityName, @NotNull final String } @Override - public final String getName() { + public String getName() { return entityName; } @Override - public final boolean isProjection() { + public boolean isProjection() { return false; } @Override - public final String getEntityName() { + public String getEntityName() { return entityName; } @Override - public final String getNativeTableName() { + public String getNativeTableName() { return nativeTableName; } - + @Override - public final T getSingleParamValue() { + public T getSingleParamValue() { throw new UnsupportedOperationException(getClass().getSimpleName() + " has no parameters"); } @Override - public final List getParameters() { + public List getParameters() { return Collections.emptyList(); } @Override - public final String asString() { + public String asString() { return entityName; } @Override - public final int hashCode() { + public int hashCode() { return entityName.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -108,7 +108,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return entityName; } diff --git a/jpa/src/test/java/org/fuin/esc/jpa/ArchitectureTest.java b/jpa/src/test/java/org/fuin/esc/jpa/ArchitectureTest.java new file mode 100644 index 00000000..0703de67 --- /dev/null +++ b/jpa/src/test/java/org/fuin/esc/jpa/ArchitectureTest.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.jpa; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; +import org.fuin.esc.spi.EscSpiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.annotation..", + "jakarta.persistence..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.slf4j.." + ); + + +} + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/BaseTest.java b/jpa/src/test/java/org/fuin/esc/jpa/BaseTest.java index be4abaac..7f8fc80e 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/BaseTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/BaseTest.java @@ -1,44 +1,45 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. + * along with this library. If not, see . */ package org.fuin.esc.jpa; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; -/** - * General tests for all classes. - */ -// CHECKSTYLE:OFF Test code -public class BaseTest { +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; - @Disabled("Implement with ArchUnit!") - @Test - public final void testCoverage() { - // Make sure all classes have a test - // TODO Implement! - } +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { + + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); - @Disabled("Implement with ArchUnit!") - @Test - public final void testNullability() { - // Make sure all public/protected methods have either @Nullable or @NotNull - // TODO Implement! - } - } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/JpaDataTest.java b/jpa/src/test/java/org/fuin/esc/jpa/JpaDataTest.java index 2d2fbaaf..dfca36fe 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/JpaDataTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/JpaDataTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -25,7 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class JpaDataTest extends AbstractPersistenceTest { @Test @@ -40,7 +40,7 @@ public void testGetter() { // PREPARE final TypeName typeName = new TypeName("AnyName"); final EnhancedMimeType mimeType = EnhancedMimeType.create("application", "xml"); - final byte[] raw = new byte[] { 1, 2, 3}; + final byte[] raw = new byte[]{1, 2, 3}; final JpaData testee = new JpaData(typeName, mimeType, raw); // TEST @@ -51,4 +51,4 @@ public void testGetter() { } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/JpaEventStoreTest.java b/jpa/src/test/java/org/fuin/esc/jpa/JpaEventStoreTest.java index 370b8f7c..bd2f7270 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/JpaEventStoreTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/JpaEventStoreTest.java @@ -1,39 +1,59 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import org.fuin.esc.api.*; +import jakarta.json.bind.annotation.JsonbProperty; +import jakarta.json.bind.config.PropertyVisibilityStrategy; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.EventStore; +import org.fuin.esc.api.ExpectedVersion; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.api.SimpleStreamId; +import org.fuin.esc.api.StreamEventsSlice; +import org.fuin.esc.api.StreamId; +import org.fuin.esc.api.StreamState; +import org.fuin.esc.api.TypeName; +import org.fuin.esc.jaxb.XmlDeSerializer; import org.fuin.esc.jpa.examples.AggregateStreamId; import org.fuin.esc.jpa.examples.VendorCreatedEvent; import org.fuin.esc.jpa.examples.VendorStream; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; -import org.fuin.esc.spi.XmlDeSerializer; +import org.fuin.esc.jsonb.EscEvent; +import org.fuin.esc.jsonb.EscEvents; +import org.fuin.esc.jsonb.EscJsonbUtils; +import org.fuin.esc.jsonb.EscMeta; +import org.fuin.esc.jsonb.JsonbDeSerializer; +import org.fuin.objects4j.common.Contract; import org.junit.jupiter.api.Test; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class JpaEventStoreTest extends AbstractPersistenceTest { @Test @@ -46,7 +66,7 @@ public void testAppendSingleSuccess() throws Exception { final SerializedDataType serDataType = new SerializedDataType(VendorCreatedEvent.TYPE); registry.add(serDataType, xmlDeSer.getMimeType().getBaseType(), xmlDeSer); - final JpaEventStore testee = new JpaEventStore(getEm(), new JpaIdStreamFactory() { + try (final JpaEventStore testee = new JpaEventStore(getEm(), new JpaIdStreamFactory() { @Override public JpaStream createStream(final StreamId streamId) { final String vendorId = streamId.getSingleParamValue(); @@ -57,9 +77,9 @@ public JpaStream createStream(final StreamId streamId) { public boolean containsType(final StreamId streamId) { return true; } - }, registry, registry); - testee.open(); - try { + }, registry, registry)) { + testee.open(); + final String vendorId = UUID.randomUUID().toString(); final VendorCreatedEvent vendorCreatedEvent = new VendorCreatedEvent(vendorId); final AggregateStreamId streamId = new AggregateStreamId("Vendor", "vendorId", vendorId); @@ -70,8 +90,6 @@ public boolean containsType(final StreamId streamId) { // TEST execute(testee, streamId, eventData, eventId); - } finally { - testee.close(); } } @@ -80,54 +98,53 @@ public boolean containsType(final StreamId streamId) { public void testNoParamsStreams() throws Exception { // PREPARE - final String EVENT_A = "EventA"; - final String EVENT_B = "EventB"; - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - final JsonDeSerializer jsonDeSer = new JsonDeSerializer(); - - final SerializedDataType serDataTypeA = new SerializedDataType(EVENT_A); - registry.add(serDataTypeA, "application/json", jsonDeSer); - final JsonObject eventA = Json.createObjectBuilder().add("a", "John Doe").build(); - final SimpleStreamId streamA = new SimpleStreamId("StreamA"); - final EventId eventIdA = new EventId("84fe8213-ac1b-4cda-8321-703c2e448052"); - final TypeName typeA = new TypeName(EVENT_A); - final CommonEvent commonEventA = new SimpleCommonEvent(eventIdA, typeA, eventA); - - final SerializedDataType serDataTypeB = new SerializedDataType(EVENT_B); - registry.add(serDataTypeB, "application/json", jsonDeSer); - final JsonObject eventB = Json.createObjectBuilder().add("b", "Jane Doe").build(); - final SimpleStreamId streamB = new SimpleStreamId("StreamB"); - final EventId eventIdB = new EventId("23962a5e-da10-402f-8560-340745b09b2c"); - final TypeName typeB = new TypeName(EVENT_B); - final CommonEvent commonEventB = new SimpleCommonEvent(eventIdB, typeB, eventB); - - final JpaEventStore testee = new JpaEventStore(getEm(), new JpaIdStreamFactory() { - @Override - public JpaStream createStream(final StreamId streamId) { - return new NoParamsStream(streamId); - } - @Override - public boolean containsType(final StreamId streamId) { - return true; - } - }, registry, registry); - testee.open(); - try { + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(EventA.SER_TYPE, EventA.class); + typeRegistry.add(EventB.SER_TYPE, EventB.class); - // TEST - execute(testee, streamA, commonEventA, eventIdA); - execute(testee, streamB, commonEventB, eventIdB); + try (final JsonbDeSerializer jsonbDeSer = createJsonbDeSerializer()) { + initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(EventA.SER_TYPE, "application/json", jsonbDeSer); + registry.add(EventB.SER_TYPE, "application/json", jsonbDeSer); + + final EventA eventA = new EventA("John Doe"); + final SimpleStreamId streamA = new SimpleStreamId("StreamA"); + final EventId eventIdA = new EventId("84fe8213-ac1b-4cda-8321-703c2e448052"); + final CommonEvent commonEventA = new SimpleCommonEvent(eventIdA, EventA.TYPE, eventA); + + final EventB eventB = new EventB("Jane Doe"); + final SimpleStreamId streamB = new SimpleStreamId("StreamB"); + final EventId eventIdB = new EventId("23962a5e-da10-402f-8560-340745b09b2c"); + final CommonEvent commonEventB = new SimpleCommonEvent(eventIdB, EventB.TYPE, eventB); - } finally { - testee.close(); + try (final JpaEventStore testee = new JpaEventStore(getEm(), new JpaIdStreamFactory() { + @Override + public JpaStream createStream(final StreamId streamId) { + return new NoParamsStream(streamId); + } + + @Override + public boolean containsType(final StreamId streamId) { + return true; + } + }, registry, registry)) { + testee.open(); + + // TEST + execute(testee, streamA, commonEventA, eventIdA); + execute(testee, streamB, commonEventB, eventIdB); + + } } } private static void execute(final EventStore eventStore, final StreamId streamId, - final CommonEvent commonEvent, final EventId eventId) throws Exception { + final CommonEvent commonEvent, final EventId eventId) throws Exception { beginTransaction(); try { @@ -158,5 +175,93 @@ private static void execute(final EventStore eventStore, final StreamId streamId } } + + public static class EventA { + + public static final String EVENT = "EventA"; + + public static final TypeName TYPE = new TypeName(EVENT); + + public static final SerializedDataType SER_TYPE = new SerializedDataType(EVENT); + + @JsonbProperty + private String a; + + protected EventA() { + } + + public EventA(String a) { + this.a = a; + } + + } + + public static class EventB { + + public static final String EVENT = "EventB"; + + public static final TypeName TYPE = new TypeName(EVENT); + + public static final SerializedDataType SER_TYPE = new SerializedDataType(EVENT); + + @JsonbProperty + private String b; + + protected EventB() { + } + + public EventB(String b) { + this.b = b; + } + + } + + public static class FieldAccessStrategy implements PropertyVisibilityStrategy { + + public boolean isVisible(Field field) { + return true; + } + + public boolean isVisible(Method method) { + return false; + } + } + + private static JsonbDeSerializer createJsonbDeSerializer() { + return JsonbDeSerializer.builder() + .withSerializers(EscJsonbUtils.createEscJsonbSerializers()) + .withDeserializers(EscJsonbUtils.createEscJsonbDeserializers()) + .withPropertyVisibilityStrategy(new FieldAccessStrategy()) + .withEncoding(StandardCharsets.UTF_8) + .build(); + } + + /** + * Creates a registry that connects the type with the appropriate serializer and de-serializer. + * + * @param typeRegistry Type registry (Mapping from type name to class). + * @param jsonbDeSer JSON-B serializer/deserializer to use. + */ + public static void initSerDeserializerRegistry(@NotNull SerializedDataTypeRegistry typeRegistry, + @NotNull JsonbDeSerializer jsonbDeSer) { + + Contract.requireArgNotNull("typeRegistry", typeRegistry); + Contract.requireArgNotNull("jsonbDeSer", jsonbDeSer); + + SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + + // Base types always needed + registry.add(EscEvents.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscEvent.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscMeta.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + // User defined types + registry.add(EventA.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EventB.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + jsonbDeSer.init(typeRegistry, registry, registry); + + } + } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/JpaEventTest.java b/jpa/src/test/java/org/fuin/esc/jpa/JpaEventTest.java index 460579d4..133e5c7c 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/JpaEventTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/JpaEventTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,11 +24,12 @@ import org.junit.jupiter.api.Test; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class JpaEventTest extends AbstractPersistenceTest { @Test @@ -70,12 +71,11 @@ public void testPersist() { } private JpaEvent create(final EventId eventId, final TypeName type, final int version, final String xml) { - final Charset encoding = Charset.forName("utf-8"); + final Charset encoding = StandardCharsets.UTF_8; final EnhancedMimeType mimeType = EnhancedMimeType.create("application", "xml", encoding, "" + version, new HashMap()); - final JpaEvent eventEntry = new JpaEvent(eventId, new JpaData(type, mimeType, xml.getBytes(encoding))); - return eventEntry; + return new JpaEvent(eventId, new JpaData(type, mimeType, xml.getBytes(encoding))); } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/JpaProjectionTest.java b/jpa/src/test/java/org/fuin/esc/jpa/JpaProjectionTest.java index 886c5c02..9feb14e8 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/JpaProjectionTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/JpaProjectionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -26,7 +26,6 @@ /** * Tests the {@link JpaProjection} class. */ -// CHECKSTYLE:OFF Test public class JpaProjectionTest { @Test @@ -68,4 +67,4 @@ public void testConstructorName() { } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/JpaUtilsTest.java b/jpa/src/test/java/org/fuin/esc/jpa/JpaUtilsTest.java index 08eaa85d..6bb2f1c4 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/JpaUtilsTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/JpaUtilsTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class JpaUtilsTest { - + @Test public void testCamelCaseToUnderscore() { @@ -77,7 +77,7 @@ public void testNativeEventsTableNameProjection() { assertThat(result).isEqualTo("my_own"); } - + @Test public void testNativeEventsTableNameWithArgs() { @@ -108,7 +108,7 @@ public void testNativeEventsTableNameNoArgs() { assertThat(result).isEqualTo(NoParamsEvent.NO_PARAMS_EVENTS_TABLE); } - + @Test public void testStreamEntityNameJpaStreamId() { @@ -139,7 +139,7 @@ public void testStreamEntityNameProjection() { assertThat(result).isEqualTo(entityName); } - + @Test public void testStreamEntityNameWithArgs() { @@ -169,6 +169,6 @@ public void testStreamEntityNameNoArgs() { assertThat(result).isEqualTo(NoParamsStream.class.getSimpleName()); } - + } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/NativeSqlConditionTest.java b/jpa/src/test/java/org/fuin/esc/jpa/NativeSqlConditionTest.java index d31ce9d7..8767493e 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/NativeSqlConditionTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/NativeSqlConditionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class NativeSqlConditionTest { @Test @@ -55,4 +55,4 @@ public void testAsWhereConditionWithParam() { } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventPrimaryKeyTest.java b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventPrimaryKeyTest.java index 2dd071ab..e91dc13b 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventPrimaryKeyTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventPrimaryKeyTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -25,7 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class NoParamsEventPrimaryKeyTest { @Test @@ -48,4 +48,4 @@ public void testGetter() { } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventTest.java b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventTest.java index befac98f..6d451a83 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsEventTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -26,33 +26,33 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class NoParamsEventTest { - @Test - public void testEqualsHashCode() { - EqualsVerifier.forClass(NoParamsEvent.class) - .withIgnoredAnnotations(Entity.class, Id.class, Embeddable.class, MappedSuperclass.class, - Transient.class) - .suppress(Warning.NONFINAL_FIELDS, Warning.STRICT_INHERITANCE, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); - } + @Test + public void testEqualsHashCode() { + EqualsVerifier.forClass(NoParamsEvent.class) + .withIgnoredAnnotations(Entity.class, Id.class, Embeddable.class, MappedSuperclass.class, + Transient.class) + .suppress(Warning.NONFINAL_FIELDS, Warning.STRICT_INHERITANCE, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); + } - @Test - public void testGetter() { + @Test + public void testGetter() { - // PREPARE - final StreamId streamId = new SimpleStreamId("Abc"); - final Long eventNumber = 3L; - final JpaEvent eventEntry = new JpaEvent(); - final NoParamsEvent testee = new NoParamsEvent(streamId, eventNumber, eventEntry); + // PREPARE + final StreamId streamId = new SimpleStreamId("Abc"); + final Long eventNumber = 3L; + final JpaEvent eventEntry = new JpaEvent(); + final NoParamsEvent testee = new NoParamsEvent(streamId, eventNumber, eventEntry); - // TEST - assertThat(testee.getStreamName()).isEqualTo(streamId.getName()); - assertThat(testee.getEventNumber()).isEqualTo(eventNumber); - assertThat(testee.getEvent()).isEqualTo(eventEntry); + // TEST + assertThat(testee.getStreamName()).isEqualTo(streamId.getName()); + assertThat(testee.getEventNumber()).isEqualTo(eventNumber); + assertThat(testee.getEvent()).isEqualTo(eventEntry); - } + } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsStreamTest.java b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsStreamTest.java index 358d9c3c..3c33835e 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/NoParamsStreamTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/NoParamsStreamTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,41 +24,41 @@ import static org.assertj.core.api.Assertions.assertThat; -// CHECKSTYLE:OFF + public final class NoParamsStreamTest { - + @Test public void testCreate() { // PREPARE final StreamId streamId = new SimpleStreamId("AnyName"); - + // TEST final NoParamsStream testee = new NoParamsStream(streamId); - + // VERIFY assertThat(testee.toString()).isEqualTo(streamId.toString()); assertThat(testee.getState()).isEqualTo(StreamState.ACTIVE); assertThat(testee.getVersion()).isEqualTo(-1); assertThat(testee.isDeleted()).isFalse(); - + } - + @Test public void testSoftDelete() { // PREPARE final StreamId streamId = new SimpleStreamId("AnyName"); final NoParamsStream testee = new NoParamsStream(streamId); - + // TEST testee.delete(false); - + // VERIFY assertThat(testee.getState()).isEqualTo(StreamState.SOFT_DELETED); assertThat(testee.isDeleted()).isTrue(); - + } @Test @@ -67,14 +67,14 @@ public void testHardDelete() { // PREPARE final StreamId streamId = new SimpleStreamId("AnyName"); final NoParamsStream testee = new NoParamsStream(streamId); - + // TEST testee.delete(true); - + // VERIFY assertThat(testee.getState()).isEqualTo(StreamState.HARD_DELETED); assertThat(testee.isDeleted()).isTrue(); - + } @Test @@ -83,14 +83,14 @@ public void testIncVersion() { // PREPARE final StreamId streamId = new SimpleStreamId("AnyName"); final NoParamsStream testee = new NoParamsStream(streamId); - + // TEST & VERIFY assertThat(testee.incVersion()).isEqualTo(0); assertThat(testee.getVersion()).isEqualTo(0); - + assertThat(testee.incVersion()).isEqualTo(1); assertThat(testee.getVersion()).isEqualTo(1); - + } @Test @@ -101,16 +101,16 @@ public void testCreateEvent() { final NoParamsStream testee = new NoParamsStream(streamId); final JpaEvent eventEntry = new JpaEvent(); final long version = testee.getVersion(); - + // TEST final JpaStreamEvent result = testee.createEvent(streamId, eventEntry); - + // VERIFY assertThat(result).isNotNull(); assertThat(result.getEvent()).isSameAs(eventEntry); assertThat(testee.getVersion()).isEqualTo(version + 1); - + } - + } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/ProjectionJpaStreamIdTest.java b/jpa/src/test/java/org/fuin/esc/jpa/ProjectionJpaStreamIdTest.java index e6d1d49e..daf042f2 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/ProjectionJpaStreamIdTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/ProjectionJpaStreamIdTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,7 +29,6 @@ /** * Tests the {@link ProjectionJpaStreamId} class. */ -// CHECKSTYLE:OFF Test public class ProjectionJpaStreamIdTest { private static final String NAME = "MyProjection"; @@ -70,4 +69,4 @@ public void testGetSingleParamValue() { }).isInstanceOf(UnsupportedOperationException.class); } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/ReadableJpaEventStoreTest.java b/jpa/src/test/java/org/fuin/esc/jpa/ReadableJpaEventStoreTest.java index db466345..56211309 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/ReadableJpaEventStoreTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/ReadableJpaEventStoreTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -19,9 +19,8 @@ import org.fuin.utils4j.TestOmitted; -// CHECKSTYLE:OFF Test @TestOmitted("Tested with JpaEventStoreTest and 'esc-test' project") public class ReadableJpaEventStoreTest { //NOSONAR } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/SimpleJpaStreamIdTest.java b/jpa/src/test/java/org/fuin/esc/jpa/SimpleJpaStreamIdTest.java index 5004c552..da17a449 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/SimpleJpaStreamIdTest.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/SimpleJpaStreamIdTest.java @@ -1,17 +1,17 @@ /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -29,7 +29,6 @@ /** * Tests the {@link SimpleJpaStreamId} class. */ -// CHECKSTYLE:OFF Test public class SimpleJpaStreamIdTest { private static final String NAME = "MyStream1"; @@ -69,4 +68,4 @@ public void testGetSingleParamValue() { }).isInstanceOf(UnsupportedOperationException.class); } } -// CHECKSTYLE:ON + diff --git a/jpa/src/test/java/org/fuin/esc/jpa/examples/AggregateStreamId.java b/jpa/src/test/java/org/fuin/esc/jpa/examples/AggregateStreamId.java index e456d66d..73620ce5 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/examples/AggregateStreamId.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/examples/AggregateStreamId.java @@ -1,26 +1,30 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa.examples; +import com.tngtech.archunit.junit.ArchIgnore; import org.fuin.esc.api.StreamId; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; + import org.fuin.objects4j.core.KeyValue; +import java.io.Serial; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -28,22 +32,24 @@ /** * Unique name of an aggregate stream. */ +@ArchIgnore @Immutable public final class AggregateStreamId implements StreamId { + @Serial private static final long serialVersionUID = 1000L; - private String type; + private final String type; - private String paramName; + private final String paramName; - private String aggregateId; + private final String aggregateId; private transient List params; /** * Constructor with type and id. - * + * * @param type * Aggregate type. * @param paramName diff --git a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorCreatedEvent.java b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorCreatedEvent.java index 7e499337..952ab350 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorCreatedEvent.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorCreatedEvent.java @@ -1,29 +1,31 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa.examples; -import jakarta.validation.constraints.NotNull; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.validation.constraints.NotNull; /** * A vendor entity was created. */ +@ArchIgnore @XmlRootElement(name = "vendor-created-event") public final class VendorCreatedEvent { @@ -42,7 +44,7 @@ protected VendorCreatedEvent() { /** * Constructor with all mandatory data. - * + * * @param vendorId * Vendor ID. */ @@ -53,7 +55,7 @@ public VendorCreatedEvent(@NotNull final String vendorId) { /** * Returns the vendor ID. - * + * * @return Unique vendor identifier. */ @NotNull diff --git a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java index 421f3814..b530771c 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEvent.java @@ -1,22 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa.examples; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import org.fuin.esc.jpa.JpaEvent; @@ -26,6 +27,7 @@ /** * Database table for an event of the vendor aggregate. */ +@ArchIgnore @Table(name = "VENDOR_EVENTS") @Entity @IdClass(VendorEventPrimaryKey.class) @@ -50,7 +52,7 @@ protected VendorEvent() { /** * Constructor with all mandatory data. - * + * * @param vendorId * Unique vendor identifier. * @param version @@ -59,7 +61,7 @@ protected VendorEvent() { * Event entry to connect. */ public VendorEvent(@NotNull final String vendorId, - @NotNull final Long version, final JpaEvent eventEntry) { + @NotNull final Long version, final JpaEvent eventEntry) { super(eventEntry); Contract.requireArgNotNull("vendorId", vendorId); Contract.requireArgNotNull("version", version); @@ -69,7 +71,7 @@ public VendorEvent(@NotNull final String vendorId, /** * Returns the unique vendor identifier. - * + * * @return Vendor identifier. */ public final String getVendorId() { @@ -78,14 +80,13 @@ public final String getVendorId() { /** * Returns the number of the stream. - * + * * @return Number that is unique in combination with the name. */ public final Long getEventNumber() { return eventNumber; } - // CHECKSTYLE:OFF Generated code @Override public final int hashCode() { final int prime = 31; @@ -119,7 +120,6 @@ public final boolean equals(final Object obj) { return true; } - // CHECKSTYLE:ON @Override public final String toString() { diff --git a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEventPrimaryKey.java b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEventPrimaryKey.java index 50ac801a..c940622e 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEventPrimaryKey.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorEventPrimaryKey.java @@ -1,22 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa.examples; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.validation.constraints.NotNull; import org.fuin.objects4j.common.Contract; @@ -25,6 +26,7 @@ /** * Primary key for the vendor event table. */ +@ArchIgnore public class VendorEventPrimaryKey implements Serializable { private static final long serialVersionUID = 1000L; @@ -43,14 +45,14 @@ public VendorEventPrimaryKey() { /** * Constructor with all required data. - * + * * @param vendorId * Unique name. * @param eventNumber * Number of the event within the stream. */ public VendorEventPrimaryKey(@NotNull final String vendorId, - @NotNull final Long eventNumber) { + @NotNull final Long eventNumber) { super(); Contract.requireArgNotNull("vendorId", vendorId); Contract.requireArgNotNull("nueventNumbermber", eventNumber); @@ -60,7 +62,7 @@ public VendorEventPrimaryKey(@NotNull final String vendorId, /** * Returns the vendor ID. - * + * * @return Unique vendor identifier. */ @NotNull @@ -70,7 +72,7 @@ public final String getVendorId() { /** * Returns the number of the event within the stream. - * + * * @return Order of the event in the stream. */ @NotNull @@ -78,7 +80,6 @@ public final Long getEventNumber() { return eventNumber; } - // CHECKSTYLE:OFF Generated code @Override public final int hashCode() { final int prime = 31; @@ -112,7 +113,6 @@ public final boolean equals(final Object obj) { return true; } - // CHECKSTYLE:ON @Override public final String toString() { diff --git a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorStream.java b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorStream.java index 6fd47000..482861f9 100644 --- a/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorStream.java +++ b/jpa/src/test/java/org/fuin/esc/jpa/examples/VendorStream.java @@ -1,22 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.jpa.examples; +import com.tngtech.archunit.junit.ArchIgnore; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -33,6 +34,7 @@ */ @Table(name = "VENDOR_STREAMS") @Entity +@ArchIgnore public class VendorStream extends JpaStream { @Id @@ -49,7 +51,7 @@ protected VendorStream() { /** * Constructor with mandatory data. - * + * * @param vendorId * Unique vendor identifier. */ @@ -61,7 +63,7 @@ public VendorStream(@NotNull final String vendorId) { /** * Returns the unique vendor identifier as string. - * + * * @return Vendor identifier. */ public final String getVendorId() { diff --git a/jpa/src/test/resources/META-INF/persistence.xml b/jpa/src/test/resources/META-INF/persistence.xml index 55cdd5b4..a7c76cce 100644 --- a/jpa/src/test/resources/META-INF/persistence.xml +++ b/jpa/src/test/resources/META-INF/persistence.xml @@ -1,53 +1,53 @@ - - - - org.hibernate.jpa.HibernatePersistenceProvider - - org.fuin.esc.jpa.JpaEvent - org.fuin.esc.jpa.JpaStream - org.fuin.esc.jpa.JpaProjection - org.fuin.esc.jpa.JpaData - org.fuin.esc.jpa.NoParamsEvent - org.fuin.esc.jpa.NoParamsStream - org.fuin.esc.jpa.examples.VendorEvent - org.fuin.esc.jpa.examples.VendorStream - - true - - - - - - - - - - - - - - - - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd" + version="3.0"> + + + + org.hibernate.jpa.HibernatePersistenceProvider + + org.fuin.esc.jpa.JpaEvent + org.fuin.esc.jpa.JpaStream + org.fuin.esc.jpa.JpaProjection + org.fuin.esc.jpa.JpaData + org.fuin.esc.jpa.NoParamsEvent + org.fuin.esc.jpa.NoParamsStream + org.fuin.esc.jpa.examples.VendorEvent + org.fuin.esc.jpa.examples.VendorStream + + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jsonb/pom.xml b/jsonb/pom.xml new file mode 100644 index 00000000..4a7d7ea2 --- /dev/null +++ b/jsonb/pom.xml @@ -0,0 +1,206 @@ + + + + 4.0.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + + + esc-jsonb + jar + JSON-B related classes + + + + + + + org.fuin.esc + esc-api + + + + org.fuin.objects4j + objects4j-common + + + + jakarta.json + jakarta.json-api + + + + jakarta.json.bind + jakarta.json.bind-api + + + + com.google.code.findbugs + jsr305 + + + + jakarta.annotation + jakarta.annotation-api + + + + jakarta.validation + jakarta.validation-api + + + + jakarta.activation + jakarta.activation-api + + + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.eclipse + yasson + test + + + + org.glassfish + jakarta.el + test + + + + net.javacrumbs.json-unit + json-unit-fluent + test + + + + com.google.code.gson + gson + test + + + + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 + test + + + + org.fuin + units4j + test + + + + org.fuin.esc + esc-spi + test + + + + org.fuin + utils4j + test + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + + + **/* + + + + org.fuin.esc.jsonb + + + + + + + org.apache.maven.plugins + maven-jdeps-plugin + + + + org.apache.maven.plugins + maven-dependency-plugin + + + jakarta.el:jakarta.el-api + org.glassfish:jakarta.el + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.json + com.google.code.gson:gson + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + jakarta.activation:jakarta.activation-api + + + + + + + + + diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/Base64Data.java b/jsonb/src/main/java/org/fuin/esc/jsonb/Base64Data.java new file mode 100644 index 00000000..3dd5c73b --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/Base64Data.java @@ -0,0 +1,89 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IBase64Data; +import org.fuin.objects4j.common.Contract; + +import java.util.Base64; + +/** + * Contains some Base64 encoded data. + */ +@HasSerializedDataTypeConstant +public final class Base64Data implements IBase64Data { + + private String base64Str; + + private byte[] binaryData; + + /** + * Default constructor for JAXB. + */ + protected Base64Data() { + super(); + } + + /** + * Constructor with Base64 encoded string. + * + * @param base64Str Base64 encoded data. + */ + public Base64Data(@NotNull final String base64Str) { + super(); + Contract.requireArgNotNull("base64Str", base64Str); + this.base64Str = base64Str; + this.binaryData = Base64.getDecoder().decode(base64Str); + } + + /** + * Constructor with binary data that will be Base64 encoded. + * + * @param binaryData Binary data. + */ + public Base64Data(@NotNull final byte[] binaryData) { + super(); + Contract.requireArgNotNull("binaryData", binaryData); + this.base64Str = Base64.getEncoder().encodeToString(binaryData); + this.binaryData = binaryData; + } + + /** + * Returns the Base64 encoded data. + * + * @return Base64 string. + */ + public String getEncoded() { + return base64Str; + } + + /** + * Returns the decoded data. + * + * @return Binary data. + */ + public byte[] getDecoded() { + if (binaryData == null) { + binaryData = Base64.getDecoder().decode(base64Str); + } + return binaryData; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/BaseTypeFactory.java b/jsonb/src/main/java/org/fuin/esc/jsonb/BaseTypeFactory.java new file mode 100644 index 00000000..ad6f5aaf --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/BaseTypeFactory.java @@ -0,0 +1,29 @@ +package org.fuin.esc.jsonb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.IEscMeta; + +/** + * Creates necessary implementations in the JAX-B module. + */ +public final class BaseTypeFactory implements IBaseTypeFactory { + + @Override + public IBase64Data createBase64Data(@NotNull byte[] binaryData) { + return new Base64Data(binaryData); + } + + @Override + public IEscMeta createEscMeta(@NotNull String dataType, + @NotNull EnhancedMimeType dataContentType, + @Nullable String metaType, + @Nullable EnhancedMimeType metaContentType, + @Nullable Object meta) { + return new EscMeta(dataType, dataContentType, metaType, metaContentType, meta); + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/Data.java b/jsonb/src/main/java/org/fuin/esc/jsonb/Data.java new file mode 100644 index 00000000..888318ee --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/Data.java @@ -0,0 +1,128 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IData; +import org.fuin.objects4j.common.Contract; +import org.fuin.objects4j.common.ValueObject; + +import javax.annotation.concurrent.Immutable; +import java.io.Serial; +import java.io.Serializable; + +/** + * Helper class that allows sending the data of an event as XML directly to the + * event store. Represents a block of data in a serialized form. This class + * might be useful for tests. It's not used in the 'esc-spi' code itself + */ +@Immutable +public final class Data implements IData, ValueObject, Serializable { + + @Serial + private static final long serialVersionUID = 1000L; + + /** + * Unique type of the data. + */ + @NotNull + private String type; + + /** + * Internet Media Type that classifies the raw event data. + */ + @NotNull + private String mimeType; + + /** + * Raw event data in format defined by the mime type and encoding. + */ + @NotNull + private String content; + + /** + * Protected constructor for deserialization. + */ + protected Data() { //NOSONAR Ignore uninitialized fields + super(); + } + + /** + * Creates a data object. + * + * @param type Unique identifier for the type of data. + * @param mimeType Internet Media Type with encoding and version that classifies + * the data. + * @param content Content. + */ + public Data(@NotNull final String type, + @NotNull final EnhancedMimeType mimeType, + @NotNull final String content) { + super(); + + Contract.requireArgNotNull("type", type); + Contract.requireArgNotNull("mimeType", mimeType); + Contract.requireArgNotNull("content", content); + + this.type = type; + this.mimeType = mimeType.toString(); + this.content = content; + + } + + /** + * Returns the unique identifier for the type of data. + * + * @return Unique and never changing type name. + */ + @NotNull + public String getType() { + return type; + } + + /** + * Returns the Internet Media Type that classifies the data. + * + * @return Mime type. + */ + @NotNull + public EnhancedMimeType getMimeType() { + return EnhancedMimeType.create(mimeType); + } + + /** + * Returns the raw data block. + * + * @return Raw data. + */ + @NotNull + public String getContent() { + return content; + } + + @Override + public String toString() { + return "Data{" + + "type='" + type + '\'' + + ", mimeType='" + mimeType + '\'' + + ", content='" + content + '\'' + + '}'; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/DataWrapper.java b/jsonb/src/main/java/org/fuin/esc/jsonb/DataWrapper.java new file mode 100644 index 00000000..50dc3dbf --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/DataWrapper.java @@ -0,0 +1,60 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.IDataWrapper; +import org.fuin.objects4j.common.Contract; + +/** + * A structure that wraps another object of different types. + */ +public final class DataWrapper implements IDataWrapper { + + private Object obj; + + /** + * Default constructor for JAXB. + */ + protected DataWrapper() { + super(); + } + + /** + * Constructor with mandatory data. + * + * @param obj + * Object to wrap. + */ + public DataWrapper(@NotNull final Object obj) { + super(); + Contract.requireArgNotNull("obj", obj); + this.obj = obj; + } + + /** + * Returns the wrapped object. + * + * @return Inner object. + */ + @NotNull + public Object getObj() { + return obj; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvent.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvent.java new file mode 100644 index 00000000..852d2492 --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvent.java @@ -0,0 +1,162 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IDataWrapper; +import org.fuin.esc.api.IEscEvent; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.util.UUID; + +/** + * An event structure. + */ +@HasSerializedDataTypeConstant +public final class EscEvent implements IEscEvent { + + /** Unique name of the type. */ + public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); + + /** Unique name of the serialized type. */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + private String eventId; + + private String eventType; + + private DataWrapper data; + + private DataWrapper meta; + + /** + * Default constructor for JAXB. + */ + protected EscEvent() { + super(); + } + + + /** + * Constructor with all data. + * + * @param eventId + * Unique event identifier. + * @param eventType + * Unique type name of the event. + * @param data + * The data. + * @param meta + * The meta data, if available. + */ + public EscEvent(@NotNull final UUID eventId, + @NotNull final String eventType, + @NotNull final DataWrapper data, + @NotNull final DataWrapper meta) { + super(); + Contract.requireArgNotNull("eventId", eventId); + Contract.requireArgNotNull("eventType", eventType); + Contract.requireArgNotNull("data", data); + Contract.requireArgNotNull("meta", meta); + this.eventId = eventId.toString(); + this.eventType = eventType; + this.data = data; + this.meta = meta; + } + + /** + * Returns the unique event identifier. + * + * @return Event ID. + */ + public String getEventId() { + return eventId; + } + + /** + * Sets the unique event identifier. + * + * @param eventId Event ID. + */ + void setEventId(@NotNull final String eventId) { + Contract.requireArgNotNull("eventId", eventId); + this.eventId = eventId; + } + + /** + * Returns the unique type name of the event. + * + * @return Event type. + */ + public String getEventType() { + return eventType; + } + + /** + * Sets the unique type name of the event. + * + * @param eventType Event type. + */ + void setEventType(@NotNull final String eventType) { + Contract.requireArgNotNull("eventType", eventType); + this.eventType = eventType; + } + + /** + * Returns the data. + * + * @return Data. + */ + public IDataWrapper getData() { + return data; + } + + /** + * Sets the data. + * + * @param data Data. + */ + void setData(DataWrapper data) { + Contract.requireArgNotNull("data", data); + this.data = data; + } + + /** + * Returns the metadata. + * + * @return Metadata. + */ + @NotNull + public IDataWrapper getMeta() { + return meta; + } + + /** + * Sets the metadata. + * + * @param meta Metadata. + */ + void setMeta(@NotNull final DataWrapper meta) { + Contract.requireArgNotNull("meta", meta); + this.meta = meta; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializer.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializer.java new file mode 100644 index 00000000..0ab6d6e7 --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializer.java @@ -0,0 +1,102 @@ +package org.fuin.esc.jsonb; + +import jakarta.json.JsonObject; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import org.fuin.esc.api.Deserializer; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.DeserializerRegistryRequired; +import org.fuin.esc.api.SerializedDataType; + +import java.lang.reflect.Type; + +/** + * Adapter to use for JSON-B. + */ +public final class EscEventJsonbSerializerDeserializer implements JsonbSerializer, + JsonbDeserializer, DeserializerRegistryRequired { + + private DeserializerRegistry registry; + + @Override + public EscEvent deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + final EscEvent escEvent = new EscEvent(); + JsonObject content = null; + while (parser.hasNext()) { + final JsonParser.Event event = parser.next(); + if (event == JsonParser.Event.KEY_NAME) { + final String field = parser.getString(); + switch (field) { + case EscEvent.EL_EVENT_ID: + escEvent.setEventId(ctx.deserialize(String.class, parser)); + break; + case EscEvent.EL_EVENT_TYPE: + escEvent.setEventType(ctx.deserialize(String.class, parser)); + break; + case EscEvent.EL_META_DATA: + parser.next(); // Skip key and deserialize object + escEvent.setMeta(new DataWrapper(ctx.deserialize(EscMeta.class, parser))); + break; + case EscEvent.EL_DATA: + parser.next(); // Skip key and deserialize object + content = ctx.deserialize(JsonObject.class, parser); + break; + default: + // ignore + break; + } + } + } + + // Handle data at the end, because metadata is only safely available at the end of the process + if (content == null) { + throw new IllegalStateException("Expected content to be set, but was never processed during parse process"); + } + if (content.containsKey(Base64Data.EL_ROOT_NAME)) { + escEvent.setData(new DataWrapper(new Base64Data(content.getString(Base64Data.EL_ROOT_NAME)))); + } else { + if (escEvent.getMeta() == null) { + throw new IllegalStateException("Expected 'meta' to be set, but was never processed during parse process"); + } + if (!(escEvent.getMeta().getObj() instanceof EscMeta escMeta)) { + throw new IllegalStateException("Expected 'meta.object' to be of type 'EscMeta', but was: " + escEvent.getMeta().getObj()); + } + final Deserializer deserializer = registry.getDeserializer(new SerializedDataType(escEvent.getEventType()), + escMeta.getDataContentType()); + final Object obj = deserializer.unmarshal(content, new SerializedDataType(escEvent.getEventType()), + escMeta.getDataContentType()); + escEvent.setData(new DataWrapper(obj)); + } + + return escEvent; + } + + @Override + public void serialize(EscEvent escEvent, JsonGenerator generator, SerializationContext ctx) { + generator.writeStartObject(); + if (escEvent != null) { + generator.write(EscEvent.EL_EVENT_ID, escEvent.getEventId()); + generator.write(EscEvent.EL_EVENT_TYPE, escEvent.getEventType()); + if (escEvent.getData().getObj() instanceof Base64Data base64Data) { + generator.writeStartObject(EscEvent.EL_DATA); + generator.write(Base64Data.EL_ROOT_NAME, base64Data.getEncoded()); + generator.writeEnd(); + } else { + ctx.serialize(EscEvent.EL_DATA, escEvent.getData().getObj(), generator); + } + ctx.serialize(EscEvent.EL_META_DATA, escEvent.getMeta().getObj(), generator); + } + generator.writeEnd(); + } + + @Override + public void setRegistry(final DeserializerRegistry registry) { + this.registry = registry; + + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvents.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvents.java new file mode 100644 index 00000000..2cd77b41 --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEvents.java @@ -0,0 +1,86 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IEscEvent; +import org.fuin.esc.api.IEscEvents; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * A list of events. + */ +@HasSerializedDataTypeConstant +public final class EscEvents implements IEscEvents { + + /** + * Unique name of the type. + */ + public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); + + /** + * Unique name of the serialized type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + private List list; + + /** + * Default constructor for JAXB. + */ + protected EscEvents() { + super(); + } + + /** + * Constructor with array. + * + * @param events Event array. + */ + public EscEvents(@NotNull final EscEvent... events) { + this(Arrays.asList(events)); + } + + /** + * Constructor with list. + * + * @param events Event list. + */ + public EscEvents(@NotNull final List events) { + super(); + Contract.requireArgNotNull("events", events); + this.list = events; + } + + /** + * Returns an immutable event list. + * + * @return Unmodifiable list of events. + */ + public List getList() { + return Collections.unmodifiableList(list); + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializer.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializer.java new file mode 100644 index 00000000..2eb4fed1 --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializer.java @@ -0,0 +1,44 @@ +package org.fuin.esc.jsonb; + +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import org.fuin.esc.api.IEscEvent; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +/** + * Adapter to use for JSON-B. + */ +public final class EscEventsJsonbSerializerDeserializer implements JsonbSerializer, JsonbDeserializer { + + @Override + public EscEvents deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + final List events = new ArrayList<>(); + while (parser.hasNext()) { + final JsonParser.Event event = parser.next(); + if (event == JsonParser.Event.START_OBJECT) { + events.add(ctx.deserialize(EscEvent.class, parser)); + } + } + return new EscEvents(events); + } + + @Override + public void serialize(EscEvents escEvents, JsonGenerator generator, SerializationContext ctx) { + if (escEvents == null) { + return; + } + generator.writeStartArray(); + for (final IEscEvent event : escEvents.getList()) { + ctx.serialize(event, generator); + } + generator.writeEnd(); + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscJsonbUtils.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscJsonbUtils.java new file mode 100644 index 00000000..88bd5e3b --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscJsonbUtils.java @@ -0,0 +1,119 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Utilities for the JSON-B serialization module. + */ +public final class EscJsonbUtils { + + /** + * Private utility constructor. + */ + private EscJsonbUtils() { + throw new UnsupportedOperationException("Creating instances of a utility class is not allowed."); + } + + /** + * Creates all available JSON-B serializers necessary for the ESC implementation. + * + * @return New array with serializers. + */ + public static JsonbSerializer[] createEscJsonbSerializers() { + return new JsonbSerializer[]{ + new EscEventsJsonbSerializerDeserializer(), + new EscEventJsonbSerializerDeserializer(), + new EscMetaJsonbSerializerDeserializer() + }; + } + + /** + * Creates all available JSON-B serializers necessary for the ESC implementation. + * + * @return New array with serializers. + */ + public static JsonbSerializer[] joinJsonbSerializers(final JsonbSerializer[] serializersA, + final JsonbSerializer... serializersB) { + return joinJsonbSerializerArrays(serializersA, serializersB); + } + + /** + * Creates all available JSON-B serializers necessary for the ESC implementation. + * + * @return New array with serializers. + */ + public static JsonbSerializer[] joinJsonbSerializerArrays(final JsonbSerializer[]... serializerArrays) { + final List> all = joinArrays(serializerArrays); + return all.toArray(new JsonbSerializer[0]); + } + + /** + * Creates all available JSON-B deserializers necessary for the ESC implementation. + * + * @return New array with deserializers. + */ + public static JsonbDeserializer[] createEscJsonbDeserializers() { + return new JsonbDeserializer[]{ + new EscEventsJsonbSerializerDeserializer(), + new EscEventJsonbSerializerDeserializer(), + new EscMetaJsonbSerializerDeserializer() + }; + } + + /** + * Creates all available JSON-B deserializers necessary for the ESC implementation. + * + * @return New array with deserializers. + */ + public static JsonbDeserializer[] joinJsonbDeserializers(final JsonbDeserializer[] deserializersA, + final JsonbDeserializer... deserializersB) { + return joinJsonbDeserializerArrays(deserializersA, deserializersB); + } + + /** + * Creates all available JSON-B deserializers necessary for the ESC implementation. + * + * @return New array with deserializers. + */ + public static JsonbDeserializer[] joinJsonbDeserializerArrays(final JsonbDeserializer[]... deserializerArrays) { + final List> all = joinArrays(deserializerArrays); + return all.toArray(new JsonbDeserializer[0]); + } + + /** + * Creates all available JSON-B serializers necessary for the ESC implementation. + * + * @return New array with serializers. + */ + @SafeVarargs + static List joinArrays(final T[]... arrays) { + final List all = new ArrayList<>(); + for (final T[] array : arrays) { + all.addAll(Arrays.asList(array)); + } + return all; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscMeta.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscMeta.java new file mode 100644 index 00000000..0d511e73 --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscMeta.java @@ -0,0 +1,203 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.HasSerializedDataTypeConstant; +import org.fuin.esc.api.IEscMeta; +import org.fuin.objects4j.common.Contract; + +/** + * A structure that contains the user's metadata and the system's meta information. + */ +@HasSerializedDataTypeConstant +public final class EscMeta implements IEscMeta { + + private String dataType; + + private String dataContentTypeStr; + + private String metaType; + + private String metaContentTypeStr; + + private Object meta; + + private transient EnhancedMimeType dataContentType; + + private transient EnhancedMimeType metaContentType; + + /** + * Default constructor for JAXB. + */ + protected EscMeta() { + super(); + } + + /** + * Constructor with all mandatory data. + * + * @param dataType Type of the data. + * @param dataContentType Content type of the data. + */ + public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType) { + this(dataType, dataContentType, null, null, null); + } + + /** + * Constructor with all data. + * + * @param dataType Type of the data. + * @param dataContentType Type of the data. + * @param metaType Unique name of the metadata. Must be non-null if 'meta' is not null. + * @param metaContentType Type of the metadata. Must be non-null if 'meta' is not null. + * @param meta Metadata object, if available. + */ + public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType, @Nullable final String metaType, + @Nullable final EnhancedMimeType metaContentType, @Nullable final Object meta) { + super(); + Contract.requireArgNotNull("dataType", dataType); + Contract.requireArgNotNull("dataContentType", dataContentType); + if (meta != null) { + Contract.requireArgNotNull("metaType", metaType); + Contract.requireArgNotNull("metaContentType", metaContentType); + } + + this.dataType = dataType; + this.dataContentType = dataContentType; + this.dataContentTypeStr = dataContentType.toString(); + this.metaType = metaType; + this.metaContentType = metaContentType; + if (metaContentType != null) { + this.metaContentTypeStr = metaContentType.toString(); + } + this.meta = meta; + } + + /** + * Returns the unique name of the data type. + * + * @return Data type. + */ + @NotNull + public String getDataType() { + return dataType; + } + + /** + * Sets the unique name of the data type. + * + * @param dataType Data type. + */ + void setDataType(@NotNull final String dataType) { + Contract.requireArgNotNull("dataType", dataType); + this.dataType = dataType; + } + + /** + * Returns the type of the data. + * + * @return Data type. + */ + @NotNull + public EnhancedMimeType getDataContentType() { + if (dataContentType == null) { + dataContentType = EnhancedMimeType.create(dataContentTypeStr); + } + return dataContentType; + } + + /** + * Sets the type of the data. + * + * @param dataContentType Data type. + */ + void setDataContentType(EnhancedMimeType dataContentType) { + Contract.requireArgNotNull("dataContentType", dataContentType); + this.dataContentType = dataContentType; + this.dataContentTypeStr = dataContentType.toString(); + } + + /** + * Returns the unique name of the meta data type if available. + * + * @return Meta type. + */ + @Nullable + public String getMetaType() { + return metaType; + } + + /** + * Sets the unique name of the meta data type if available. + * + * @param metaType Meta type. + */ + public void setMetaType(@Nullable final String metaType) { + this.metaType = metaType; + } + + /** + * Returns the type of the metadata, if available. + * + * @return Meta type. + */ + @Nullable + public EnhancedMimeType getMetaContentType() { + if ((metaContentType == null) && (metaContentTypeStr != null)) { + metaContentType = EnhancedMimeType.create(metaContentTypeStr); + } + return metaContentType; + } + + /** + * Sets the type of the metadata, if available. + * + * @param metaContentType Meta content type. + */ + public void setMetaContentType(@Nullable final EnhancedMimeType metaContentType) { + this.metaContentType = metaContentType; + if (metaContentType == null) { + this.metaContentTypeStr = null; + } else { + this.metaContentTypeStr = metaContentType.toString(); + } + } + + /** + * Returns the meta data object. + * + * @return Meta data object. + */ + @NotNull + public Object getMeta() { + return meta; + } + + /** + * Sets the meta data object. + * + * @param meta Meta data object. + */ + void setMeta(@Nullable final Object meta) { + this.meta = meta; + } + +} diff --git a/jsonb/src/main/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializer.java b/jsonb/src/main/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializer.java new file mode 100644 index 00000000..a7b73adc --- /dev/null +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializer.java @@ -0,0 +1,83 @@ +package org.fuin.esc.jsonb; + +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SerializedDataTypeRegistryRequired; + +import java.lang.reflect.Type; + +/** + * Adapter to use for JSON-B. + */ +public final class EscMetaJsonbSerializerDeserializer + implements JsonbSerializer, JsonbDeserializer, SerializedDataTypeRegistryRequired { + + private SerializedDataTypeRegistry registry; + + @Override + public EscMeta deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + final EscMeta escMeta = new EscMeta(); + while (parser.hasNext()) { + final JsonParser.Event event = parser.next(); + if (event == JsonParser.Event.KEY_NAME) { + final String field = parser.getString(); + switch (field) { + case EscMeta.EL_DATA_TYPE: + escMeta.setDataType(ctx.deserialize(String.class, parser)); + break; + case EscMeta.EL_DATA_CONTENT_TYPE: + escMeta.setDataContentType(EnhancedMimeType.create(ctx.deserialize(String.class, parser))); + break; + case EscMeta.EL_META_TYPE: + escMeta.setMetaType(ctx.deserialize(String.class, parser)); + break; + case EscMeta.EL_META_CONTENT_TYPE: + escMeta.setMetaContentType(EnhancedMimeType.create(ctx.deserialize(String.class, parser))); + break; + default: + // meta + if (field.equals(Base64Data.EL_ROOT_NAME)) { + escMeta.setMeta(new Base64Data(ctx.deserialize(String.class, parser))); + } else { + final Class clasz = registry.findClass(new SerializedDataType(escMeta.getMetaType())); + escMeta.setMeta(ctx.deserialize(clasz, parser)); + } + break; + } + } + } + return escMeta; + } + + @Override + public void serialize(EscMeta escMeta, JsonGenerator generator, SerializationContext ctx) { + + generator.writeStartObject(); + generator.write(EscMeta.EL_DATA_TYPE, escMeta.getDataType()); + generator.write(EscMeta.EL_DATA_CONTENT_TYPE, escMeta.getDataContentType().toString()); + if (escMeta.getMeta() != null) { + generator.write(EscMeta.EL_META_TYPE, escMeta.getMetaType()); + generator.write(EscMeta.EL_META_CONTENT_TYPE, escMeta.getMetaContentType().toString()); + if (escMeta.getMeta() instanceof Base64Data base64data) { + generator.write(Base64Data.EL_ROOT_NAME, base64data.getEncoded()); + } else { + ctx.serialize(escMeta.getMetaType(), escMeta.getMeta(), generator); + } + } + generator.writeEnd(); + + } + + @Override + public void setRegistry(final SerializedDataTypeRegistry registry) { + this.registry = registry; + } + +} diff --git a/api/src/main/java/org/fuin/esc/api/JsonbDeSerializer.java b/jsonb/src/main/java/org/fuin/esc/jsonb/JsonbDeSerializer.java similarity index 80% rename from api/src/main/java/org/fuin/esc/api/JsonbDeSerializer.java rename to jsonb/src/main/java/org/fuin/esc/jsonb/JsonbDeSerializer.java index 0aadc4cf..e9e80f84 100644 --- a/api/src/main/java/org/fuin/esc/api/JsonbDeSerializer.java +++ b/jsonb/src/main/java/org/fuin/esc/jsonb/JsonbDeSerializer.java @@ -1,22 +1,23 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.api; +package org.fuin.esc.jsonb; +import jakarta.annotation.Nullable; import jakarta.json.JsonStructure; import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; @@ -27,9 +28,27 @@ import jakarta.json.bind.config.PropertyVisibilityStrategy; import jakarta.json.bind.serializer.JsonbDeserializer; import jakarta.json.bind.serializer.JsonbSerializer; - -import java.io.*; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.DeserializerRegistryRequired; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SerDeserializer; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SerializedDataTypeRegistryRequired; +import org.fuin.esc.api.SerializerRegistry; +import org.fuin.esc.api.SerializerRegistryRequired; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -37,8 +56,7 @@ /** * Serializes and deserializes an object from/to JSON using JSON-B. The content type for serialization is always "application/json". This - * implementation supports only byte[] and {@link JsonStructure} for unmarshalling content. Trying to use something else will - * result in an exception. + * implementation supports only byte[] for unmarshalling content. Trying to use something else will result in an exception. */ public final class JsonbDeSerializer implements SerDeserializer, Closeable { @@ -56,7 +74,7 @@ public final class JsonbDeSerializer implements SerDeserializer, Closeable { /** * Constructor with JAXB context classes. - * + * * @param config * JSON-B configuration to use. * @param encoding @@ -66,8 +84,10 @@ public final class JsonbDeSerializer implements SerDeserializer, Closeable { * @param deserializers * List of configured JSON-B deserializers. */ - private JsonbDeSerializer(final JsonbConfig config, final Charset encoding, final List> serializers, - final List> deserializers) { + private JsonbDeSerializer(@NotNull final JsonbConfig config, + @NotNull final Charset encoding, + @NotNull final List> serializers, + @NotNull final List> deserializers) { super(); this.jsonb = JsonbBuilder.create(config); this.mimeType = EnhancedMimeType.create("application", "json", encoding); @@ -76,12 +96,12 @@ private JsonbDeSerializer(final JsonbConfig config, final Charset encoding, fina } @Override - public final EnhancedMimeType getMimeType() { + public EnhancedMimeType getMimeType() { return mimeType; } @Override - public final byte[] marshal(final Object obj, final SerializedDataType type) { + public byte[] marshal(@NotNull final Object obj, @NotNull final SerializedDataType type) { ensureInitialized(); try { final Class clasz = typeRegistry.findClass(type); @@ -100,15 +120,15 @@ public final byte[] marshal(final Object obj, final SerializedDataType type) { @SuppressWarnings("unchecked") @Override - public final T unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { + public T unmarshal(@NotNull final Object data, @NotNull final SerializedDataType type, @NotNull final EnhancedMimeType mimeType) { ensureInitialized(); try { final Class clasz = typeRegistry.findClass(type); if (clasz.isAssignableFrom(data.getClass())) { return (T) data; } - if (data instanceof JsonStructure) { - return (T) jsonb.fromJson(data.toString(), clasz); + if (data instanceof JsonStructure js) { + return (T) jsonb.fromJson(js.toString(), clasz); } if (data instanceof byte[]) { final Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) data), mimeType.getEncoding()); @@ -132,9 +152,10 @@ public void close() throws IOException { /** * Returns the JSON-B instance for direct use. - * + * * @return Correctly configured instance. */ + @NotNull public Jsonb getJsonb() { ensureInitialized(); return jsonb; @@ -142,41 +163,41 @@ public Jsonb getJsonb() { /** * Initializes the instance only with type registry. - * + * * @param typeRegistry * Mapping from type name to type class. */ - public void init(final SerializedDataTypeRegistry typeRegistry) { + public void init(@NotNull final SerializedDataTypeRegistry typeRegistry) { init(typeRegistry, null, null); } /** * Initializes the instance only with type and serializer registry. - * + * * @param typeRegistry * Mapping from type name to type class. * @param serRegistry * Mapping from type name to serializers. */ - public void init(final SerializedDataTypeRegistry typeRegistry, final SerializerRegistry serRegistry) { + public void init(@Nullable final SerializedDataTypeRegistry typeRegistry, @Nullable final SerializerRegistry serRegistry) { init(typeRegistry, null, serRegistry); } /** * Initializes the instance only with type and deserializer registry. - * + * * @param typeRegistry * Mapping from type name to type class. * @param deserRegistry * Mapping from type name to deserializers. */ - public void init(final SerializedDataTypeRegistry typeRegistry, final DeserializerRegistry deserRegistry) { + public void init(@Nullable final SerializedDataTypeRegistry typeRegistry, @Nullable final DeserializerRegistry deserRegistry) { init(typeRegistry, deserRegistry, null); } /** * Initializes the instance with necessary registries. - * + * * @param typeRegistry * Mapping from type name to type class. * @param deserRegistry @@ -184,49 +205,46 @@ public void init(final SerializedDataTypeRegistry typeRegistry, final Deserializ * @param serRegistry * Mapping from type name to serializers. */ - public void init(final SerializedDataTypeRegistry typeRegistry, final DeserializerRegistry deserRegistry, - final SerializerRegistry serRegistry) { + public void init(@NotNull final SerializedDataTypeRegistry typeRegistry, + @Nullable final DeserializerRegistry deserRegistry, + @Nullable final SerializerRegistry serRegistry) { if (initialized) { throw new IllegalStateException("Instance already initialized - Don't call the init methods more than once"); } this.typeRegistry = typeRegistry; for (final JsonbDeserializer deserializer : deserializers) { - if (deserializer instanceof DeserializerRegistryRequired) { + if (deserializer instanceof DeserializerRegistryRequired des) { if (deserRegistry == null) { throw new IllegalStateException( "There is at least one deserializer that requires a 'DeserializerRegistry', but you didn't provide one (deserializer=" + deserializer.getClass().getName() + ")"); } - final DeserializerRegistryRequired des = (DeserializerRegistryRequired) deserializer; des.setRegistry(deserRegistry); } - if (deserializer instanceof SerializedDataTypeRegistryRequired) { + if (deserializer instanceof SerializedDataTypeRegistryRequired des) { if (typeRegistry == null) { throw new IllegalStateException( "There is at least one deserializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (deserializer=" + deserializer.getClass().getName() + ")"); } - final SerializedDataTypeRegistryRequired des = (SerializedDataTypeRegistryRequired) deserializer; des.setRegistry(typeRegistry); } } for (final JsonbSerializer serializer : serializers) { - if (serializer instanceof SerializerRegistryRequired) { + if (serializer instanceof SerializerRegistryRequired ser) { if (serRegistry == null) { throw new IllegalStateException( "There is at least one serializer that requires a 'SerializerRegistry', but you didn't provide one (serializer=" + serializer.getClass().getName() + ")"); } - final SerializerRegistryRequired ser = (SerializerRegistryRequired) serializer; ser.setRegistry(serRegistry); } - if (serializer instanceof SerializedDataTypeRegistryRequired) { + if (serializer instanceof SerializedDataTypeRegistryRequired ser) { if (typeRegistry == null) { throw new IllegalStateException( "There is at least one serializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (serializer=" + serializer.getClass().getName() + ")"); } - final SerializedDataTypeRegistryRequired ser = (SerializedDataTypeRegistryRequired) serializer; ser.setRegistry(typeRegistry); } } @@ -241,7 +259,7 @@ private void ensureInitialized() { /** * Static convenience method to shorten builder construction. - * + * * @return New builder instance. */ public static Builder builder() { @@ -269,7 +287,7 @@ public Builder() { } /** - * Property used to specify whether or not the serialized JSON data is formatted with linefeeds and indentation. + * Property used to specify whether the serialized JSON data is formatted with linefeeds and indentation. * * Configures value of {@code FORMATTING} property. * @@ -278,7 +296,7 @@ public Builder() { * * @return This builder. */ - public final Builder withFormatting(final Boolean formatted) { + public Builder withFormatting(final Boolean formatted) { config.withFormatting(formatted); return this; } @@ -293,7 +311,7 @@ public final Builder withFormatting(final Boolean formatted) { * * @return This builder. */ - public final Builder withNullValues(final Boolean serializeNullValues) { + public Builder withNullValues(final Boolean serializeNullValues) { config.withNullValues(serializeNullValues); return this; } @@ -310,7 +328,7 @@ public final Builder withNullValues(final Boolean serializeNullValues) { * * @return This builder. */ - public final Builder withEncoding(final Charset encoding) { + public Builder withEncoding(final Charset encoding) { config.withEncoding(encoding.name()); this.encoding = encoding; return this; @@ -326,7 +344,7 @@ public final Builder withEncoding(final Charset encoding) { * * @return This builder. */ - public final Builder withStrictIJSON(final Boolean enabled) { + public Builder withStrictIJSON(final Boolean enabled) { config.withStrictIJSON(enabled); return this; } @@ -341,7 +359,7 @@ public final Builder withStrictIJSON(final Boolean enabled) { * * @return This builder. */ - public final Builder withPropertyNamingStrategy(final PropertyNamingStrategy propertyNamingStrategy) { + public Builder withPropertyNamingStrategy(final PropertyNamingStrategy propertyNamingStrategy) { config.withPropertyNamingStrategy(propertyNamingStrategy); return this; } @@ -356,7 +374,7 @@ public final Builder withPropertyNamingStrategy(final PropertyNamingStrategy pro * * @return This builder. */ - public final Builder withPropertyNamingStrategy(final String propertyNamingStrategy) { + public Builder withPropertyNamingStrategy(final String propertyNamingStrategy) { config.withPropertyNamingStrategy(propertyNamingStrategy); return this; } @@ -371,7 +389,7 @@ public final Builder withPropertyNamingStrategy(final String propertyNamingStrat * * @return This builder. */ - public final Builder withPropertyOrderStrategy(final String propertyOrderStrategy) { + public Builder withPropertyOrderStrategy(final String propertyOrderStrategy) { config.withPropertyOrderStrategy(propertyOrderStrategy); return this; } @@ -386,7 +404,7 @@ public final Builder withPropertyOrderStrategy(final String propertyOrderStrateg * * @return This builder. */ - public final Builder withPropertyVisibilityStrategy(final PropertyVisibilityStrategy propertyVisibilityStrategy) { + public Builder withPropertyVisibilityStrategy(final PropertyVisibilityStrategy propertyVisibilityStrategy) { config.withPropertyVisibilityStrategy(propertyVisibilityStrategy); return this; } @@ -403,7 +421,7 @@ public final Builder withPropertyVisibilityStrategy(final PropertyVisibilityStra * * @return This builder. */ - public final Builder withAdapters(final JsonbAdapter... adapters) { + public Builder withAdapters(final JsonbAdapter... adapters) { config.withAdapters(adapters); return this; } @@ -420,7 +438,7 @@ public final Builder withAdapters(final JsonbAdapter... adapters) { * * @return This builder. */ - public final Builder withSerializers(final JsonbSerializer... serializers) { + public Builder withSerializers(final JsonbSerializer... serializers) { config.withSerializers(serializers); this.serializers.addAll(Arrays.asList(serializers)); return this; @@ -438,7 +456,7 @@ public final Builder withSerializers(final JsonbSerializer... serializers) { * * @return This builder. */ - public final Builder withDeserializers(final JsonbDeserializer... deserializers) { + public Builder withDeserializers(final JsonbDeserializer... deserializers) { config.withDeserializers(deserializers); this.deserializers.addAll(Arrays.asList(deserializers)); return this; @@ -454,7 +472,7 @@ public final Builder withDeserializers(final JsonbDeserializer... deserialize * * @return This builder. */ - public final Builder withBinaryDataStrategy(final String binaryDataStrategy) { + public Builder withBinaryDataStrategy(final String binaryDataStrategy) { config.withBinaryDataStrategy(binaryDataStrategy); return this; } @@ -467,22 +485,22 @@ public final Builder withBinaryDataStrategy(final String binaryDataStrategy) { * Custom date format as specified in {@link java.time.format.DateTimeFormatter}. * @param locale * Locale, default is null. - * + * * @return This builder. */ - public final Builder withDateFormat(final String dateFormat, final Locale locale) { + public Builder withDateFormat(final String dateFormat, final Locale locale) { config.withDateFormat(dateFormat, locale); return this; } /** - * Creates an instance with the configured values.. - * + * Creates an instance with the configured values. + * * @return New instance. */ - public final JsonbDeSerializer build() { + public JsonbDeSerializer build() { if (encoding == null) { - withEncoding(Charset.forName("UTF-8")); + withEncoding(StandardCharsets.UTF_8); } return new JsonbDeSerializer(config, encoding, serializers, deserializers); } diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/ArchitectureTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/ArchitectureTest.java new file mode 100644 index 00000000..39f2c102 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/ArchitectureTest.java @@ -0,0 +1,62 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; +import org.fuin.esc.spi.EscSpiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.annotation..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.slf4j..", + "jakarta.json..", + "org.apache.commons.lang3.." + ); + + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/Base64DataTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/Base64DataTest.java new file mode 100644 index 00000000..36c6bf73 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/Base64DataTest.java @@ -0,0 +1,63 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link Base64Data} class. + */ +class Base64DataTest { + + @Test + void testCreateBytes() { + + // PREPARE + final byte[] data = "Hello world!".getBytes(StandardCharsets.UTF_8); + final String base64 = "SGVsbG8gd29ybGQh"; + + // TEST + final Base64Data testee = new Base64Data(data); + + // VERIFY + assertThat(testee.getDecoded()).isEqualTo(data); + assertThat(testee.getEncoded()).isEqualTo(base64); + + } + + @Test + void testCreateBase64() { + + // PREPARE + final byte[] data = new byte[]{72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33}; + final String base64 = "SGVsbG8gd29ybGQh"; + + // TEST + final Base64Data testee = new Base64Data(base64); + + // VERIFY + assertThat(testee.getDecoded()).isEqualTo(data); + assertThat(testee.getEncoded()).isEqualTo(base64); + + } + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTest.java new file mode 100644 index 00000000..c803d9e8 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTest.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; + +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { + + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTypeFactoryTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTypeFactoryTest.java new file mode 100644 index 00000000..7c67fcfc --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/BaseTypeFactoryTest.java @@ -0,0 +1,29 @@ +package org.fuin.esc.jsonb; + +import jakarta.activation.MimeTypeParseException; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBaseTypeFactory; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for the {@link BaseTypeFactory} class. + */ +public class BaseTypeFactoryTest { + + @Test + void testCreate() throws MimeTypeParseException { + final IBaseTypeFactory testee = new BaseTypeFactory(); + assertThat(testee.createBase64Data("Hello".getBytes(StandardCharsets.UTF_8))).isInstanceOf(Base64Data.class); + assertThat(testee.createEscMeta( + "EventX", + new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"), + "MetaY", + new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"), + "Meta")).isInstanceOf(EscMeta.class); + } + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/BookAddedEvent.java b/jsonb/src/test/java/org/fuin/esc/jsonb/BookAddedEvent.java new file mode 100644 index 00000000..107b3f45 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/BookAddedEvent.java @@ -0,0 +1,107 @@ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.json.bind.annotation.JsonbProperty; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; + +/** + * Example event. + */ +@ArchIgnore +public class BookAddedEvent { + + /** + * Never changing unique event type name. + */ + public static final TypeName TYPE = new TypeName("BookAddedEvent"); + + /** + * Unique name of the serialized type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @JsonbProperty + private String name; + + @JsonbProperty + private String author; + + /** + * Protected default constructor for deserialization. + */ + protected BookAddedEvent() { + super(); + } + + /** + * Constructor with name and author. + * + * @param name Name. + * @param author Author. + */ + public BookAddedEvent(final String name, final String author) { + super(); + this.name = name; + this.author = author; + } + + /** + * @return the name + */ + public final String getName() { + return name; + } + + /** + * @return the author + */ + public final String getAuthor() { + return author; + } + + @Override + public final int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public final boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BookAddedEvent other = (BookAddedEvent) obj; + if (author == null) { + if (other.author != null) { + return false; + } + } else if (!author.equals(other.author)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public final String toString() { + return "BookAddedEvent [name=" + name + ", author=" + author + "]"; + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/DataTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/DataTest.java new file mode 100644 index 00000000..f3a80b1b --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/DataTest.java @@ -0,0 +1,44 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import org.fuin.esc.api.EnhancedMimeType; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the {@link Data} class. + */ +public class DataTest { + + @Test + public void testCreate() { + + final Data testee = new Data("MyEvent", EnhancedMimeType + .create("text/plain; version=1; encoding=utf-8"), "Hello, world!"); + + assertThat(testee.getType()).isEqualTo("MyEvent"); + assertThat(testee.getMimeType()).isEqualTo(EnhancedMimeType + .create("text/plain; version=1; encoding=utf-8")); + assertThat(testee.getContent()).isEqualTo("Hello, world!"); + + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/DataWrapperTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/DataWrapperTest.java new file mode 100644 index 00000000..0a854b33 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/DataWrapperTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link DataWrapper} class. + */ +public class DataWrapperTest { + + @Test + public final void testCreate() throws Exception { + + final Base64Data base64 = new Base64Data("Hello world!".getBytes(StandardCharsets.UTF_8)); + final DataWrapper testee = new DataWrapper(base64); + assertThat(testee.getObj()).isEqualTo(base64); + + } + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializerTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializerTest.java new file mode 100644 index 00000000..d13a54a0 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventJsonbSerializerDeserializerTest.java @@ -0,0 +1,16 @@ +package org.fuin.esc.jsonb; + +import org.fuin.utils4j.TestOmitted; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test for the {@link EscEventJsonbSerializerDeserialize} class. + */ +@TestOmitted("Already tested along with the other tests in this package") +public class EscEventJsonbSerializerDeserializerTest { + + // Nothing to test in addition + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventTest.java new file mode 100644 index 00000000..454df4ae --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventTest.java @@ -0,0 +1,275 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.activation.MimeTypeParseException; +import jakarta.json.bind.Jsonb; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link EscEvent} class. + */ +public class EscEventTest { + + @Test + public void testMarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "EventId":"b2a936ce-d479-414f-b67f-3df4da383d47", + "EventType":"MyEvent", + "Data":{ + "id":"b2a936ce-d479-414f-b67f-3df4da383d47", + "description":"Hello, JSON!" + }, + "MetaData":{ + "data-type":"MyEvent", + "data-content-type":"application/json; version=1; encoding=UTF-8", + "meta-type":"MyMeta", + "meta-content-type":"application/json; version=1; encoding=UTF-8", + "MyMeta":{ + "user":"abc" + } + } + } + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + final UUID eventId = UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"); + final MyEvent myEvent = new MyEvent(UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("abc"); + + final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/json; version=1; encoding=UTF-8"); + final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/json; version=1; encoding=UTF-8"); + final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + myMeta); + final DataWrapper dataWrapper = new DataWrapper(myEvent); + final DataWrapper metaWrapper = new DataWrapper(escMeta); + final EscEvent event = new EscEvent(eventId, MyEvent.TYPE.asBaseType(), dataWrapper, metaWrapper); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final String currentJson = jsonb.toJson(event); + + // VERIFY + assertThatJson(currentJson).isEqualTo(expectedJson); + + } + } + + } + + @Test + public final void testUnmarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "EventId":"b2a936ce-d479-414f-b67f-3df4da383d47", + "EventType":"MyEvent", + "Data":{ + "id":"b2a936ce-d479-414f-b67f-3df4da383d47", + "description":"Hello, JSON!" + }, + "MetaData":{ + "data-type":"MyEvent", + "data-content-type":"application/json; version=1; encoding=UTF-8", + "meta-type":"MyMeta", + "meta-content-type":"application/json; version=1; encoding=UTF-8", + "MyMeta":{ + "user":"abc" + } + } + } + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final EscEvent testee = jsonb.fromJson(expectedJson, EscEvent.class); + + // VERIFY + assertThat(testee.getEventId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); + assertThat(testee.getEventType()).isEqualTo("MyEvent"); + assertThat(testee.getData().getObj()).isInstanceOf(MyEvent.class); + final MyEvent myEvent = (MyEvent) testee.getData().getObj(); + assertThat(myEvent.getId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); + assertThat(myEvent.getDescription()).isEqualTo("Hello, JSON!"); + assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); + final EscMeta escMeta = (EscMeta) testee.getMeta().getObj(); + assertThat(escMeta.getDataType()).isEqualTo("MyEvent"); + assertThat(escMeta.getDataContentType()).isEqualTo(EnhancedMimeType.create("application/json; version=1; encoding=UTF-8")); + assertThat(escMeta.getMetaType()).isEqualTo("MyMeta"); + assertThat(escMeta.getMetaContentType()).isEqualTo(EnhancedMimeType.create("application/json; version=1; encoding=UTF-8")); + assertThat(escMeta.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta myMeta = (MyMeta) escMeta.getMeta(); + assertThat(myMeta.getUser()).isEqualTo("abc"); + + } + + } + } + + @Test + public void testMarshalJsonBBase64() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", + "EventType": "MyEvent", + "Data": { + "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + } + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + final EscEvent event = createEventBase64(); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final String currentJson = jsonb.toJson(event); + + // VERIFY + assertThatJson(currentJson).isEqualTo(expectedJson); + + } + } + + } + + @Test + public final void testUnmarshalJsonBBase64() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", + "EventType": "MyEvent", + "Data": { + "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + } + """; + + final EscEvent expectedEvent = createEventBase64(); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final EscEvent testee = jsonb.fromJson(expectedJson, EscEvent.class); + + // VERIFY + assertThat(testee.getEventId()).isEqualTo(expectedEvent.getEventId()); + assertThat(testee.getEventType()).isEqualTo(expectedEvent.getEventType()); + assertThat(testee.getData().getObj()).isInstanceOf(Base64Data.class); + final Base64Data base64Data = (Base64Data) testee.getData().getObj(); + assertThat(base64Data.getEncoded()).isEqualTo(((Base64Data) expectedEvent.getData().getObj()).getEncoded()); + assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); + final EscMeta actualEscMeta = (EscMeta) testee.getMeta().getObj(); + final EscMeta expectedEscMeta = (EscMeta) expectedEvent.getMeta().getObj(); + assertThat(actualEscMeta.getDataType()).isEqualTo(expectedEscMeta.getDataType()); + assertThat(actualEscMeta.getDataContentType()).isEqualTo(expectedEscMeta.getDataContentType()); + assertThat(actualEscMeta.getMetaType()).isEqualTo(expectedEscMeta.getMetaType()); + assertThat(actualEscMeta.getMetaContentType()).isEqualTo(expectedEscMeta.getMetaContentType()); + assertThat(actualEscMeta.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta actualMyMeta = (MyMeta) actualEscMeta.getMeta(); + final MyMeta expectedMyMeta = (MyMeta) expectedEscMeta.getMeta(); + assertThat(actualMyMeta.getUser()).isEqualTo(expectedMyMeta.getUser()); + + } + } + + } + + private EscEvent createEventBase64() throws MimeTypeParseException { + final UUID eventId = UUID.fromString("68616d90-cf72-4c2a-b913-32bf6e6506ed"); + final Base64Data data = new Base64Data( + "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9"); + + final MyMeta myMeta = new MyMeta("abc"); + + final Map params = new HashMap<>(); + params.put("transfer-encoding", "base64"); + final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1", params); + final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + myMeta); + return new EscEvent(eventId, MyEvent.TYPE.asBaseType(), new DataWrapper(data), new DataWrapper(escMeta)); + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializerTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializerTest.java new file mode 100644 index 00000000..719ab461 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsJsonbSerializerDeserializerTest.java @@ -0,0 +1,16 @@ +package org.fuin.esc.jsonb; + +import org.fuin.utils4j.TestOmitted; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test for the {@link EscEventsJsonbSerializerDeserializer} class. + */ +@TestOmitted("Already tested along with the other tests in this package") +public class EscEventsJsonbSerializerDeserializerTest { + + // Nothing to test in addition + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsTest.java new file mode 100644 index 00000000..b49dc7ab --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscEventsTest.java @@ -0,0 +1,194 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.activation.MimeTypeParseException; +import jakarta.json.bind.Jsonb; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link EscEvents} class. + */ +public class EscEventsTest { + + @Test + public void testMarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + [ + { + "EventId": "b2a936ce-d479-414f-b67f-3df4da383d47", + "EventType": "MyEvent", + "Data": { + "id": "b2a936ce-d479-414f-b67f-3df4da383d47", + "description": "Hello, JSON!" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + }, + { + "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", + "EventType": "MyEvent", + "Data": { + "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + } + ] + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + final EscEvents events = new EscEvents(createEvent1(), createEvent2()); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final String currentJson = jsonb.toJson(events); + + // VERIFY + assertThatJson(currentJson).isEqualTo(expectedJson); + + } + } + + } + + @Test + public final void testUnmarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + [ + { + "EventId": "b2a936ce-d479-414f-b67f-3df4da383d47", + "EventType": "MyEvent", + "Data": { + "id": "b2a936ce-d479-414f-b67f-3df4da383d47", + "description": "Hello, JSON!" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + }, + { + "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", + "EventType": "MyEvent", + "Data": { + "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" + }, + "MetaData": { + "data-type": "MyEvent", + "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/json; version=1; encoding=UTF-8", + "MyMeta": { + "user": "abc" + } + } + } + ] + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final EscEvents testee = jsonb.fromJson(expectedJson, EscEvents.class); + + // VERIFY + assertThat(testee.getList()).hasSize(2); + assertThat(testee.getList().get(0).getEventId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); + assertThat(testee.getList().get(1).getEventId()).isEqualTo("68616d90-cf72-4c2a-b913-32bf6e6506ed"); + + } + } + } + + private EscEvent createEvent1() throws MimeTypeParseException { + final UUID eventId = UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"); + final MyEvent myEvent = new MyEvent(UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"), "Hello, JSON!"); + final MyMeta myMeta = new MyMeta("abc"); + final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + myMeta); + return new EscEvent(eventId, MyEvent.TYPE.asBaseType(), new DataWrapper(myEvent), new DataWrapper(escMeta)); + } + + private EscEvent createEvent2() throws MimeTypeParseException { + final UUID eventId = UUID.fromString("68616d90-cf72-4c2a-b913-32bf6e6506ed"); + final Base64Data data = new Base64Data( + "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9"); + + final MyMeta myMeta = new MyMeta("abc"); + + final Map params = new HashMap<>(); + params.put("transfer-encoding", "base64"); + final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1", params); + final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + myMeta); + return new EscEvent(eventId, MyEvent.TYPE.asBaseType(), new DataWrapper(data), new DataWrapper(escMeta)); + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscJsonbUtilsTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscJsonbUtilsTest.java new file mode 100644 index 00000000..080566c5 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscJsonbUtilsTest.java @@ -0,0 +1,235 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.activation.MimeTypeParseException; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.Deserializer; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.Serializer; +import org.fuin.esc.spi.EscSpiUtils; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the {@link EscSpiUtils} class together with {@link EscMeta}. + */ +public class EscJsonbUtilsTest { + + @Test + public void testJoinJsonbSerializers() { + + final JsonbSerializer a = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer b = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer c = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer d = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + + assertThat(EscJsonbUtils.joinJsonbSerializers(new JsonbSerializer[]{})).isEmpty(); + ; + assertThat(EscJsonbUtils.joinJsonbSerializers(new JsonbSerializer[]{}, a)).containsExactly(a); + assertThat(EscJsonbUtils.joinJsonbSerializers(new JsonbSerializer[]{a}, b)).containsExactly(a, b); + assertThat(EscJsonbUtils.joinJsonbSerializers(new JsonbSerializer[]{a, b}, c)).containsExactly(a, b, c); + assertThat(EscJsonbUtils.joinJsonbSerializers(new JsonbSerializer[]{a, b}, c, d)).containsExactly(a, b, c, d); + + } + + @Test + public void testJoinJsonbSerializerArrays() { + + final JsonbSerializer a = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer b = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer c = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + final JsonbSerializer d = new JsonbSerializer() { + @Override + public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { + } + }; + + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{})).isEmpty(); + ; + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{}, new JsonbSerializer[]{a})).containsExactly(a); + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{a}, new JsonbSerializer[]{b})).contains(a, b); + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{a, b}, new JsonbSerializer[]{c})).contains(a, b, c); + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{a, b}, new JsonbSerializer[]{c, d})).contains(a, b, c, d); + assertThat(EscJsonbUtils.joinJsonbSerializerArrays(new JsonbSerializer[]{a}, new JsonbSerializer[]{b}, new JsonbSerializer[]{c})).contains(a, b, c); + + } + + @Test + public void testJoinJsonbDeserializers() { + + final JsonbDeserializer a = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer b = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer c = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer d = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + + assertThat(EscJsonbUtils.joinJsonbDeserializers(new JsonbDeserializer[]{})).isEmpty(); + ; + assertThat(EscJsonbUtils.joinJsonbDeserializers(new JsonbDeserializer[]{}, a)).containsExactly(a); + assertThat(EscJsonbUtils.joinJsonbDeserializers(new JsonbDeserializer[]{a}, b)).containsExactly(a, b); + assertThat(EscJsonbUtils.joinJsonbDeserializers(new JsonbDeserializer[]{a, b}, c)).containsExactly(a, b, c); + assertThat(EscJsonbUtils.joinJsonbDeserializers(new JsonbDeserializer[]{a, b}, c, d)).containsExactly(a, b, c, d); + + } + + @Test + public void testJoinJsonbDeserializerArrays() { + + final JsonbDeserializer a = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer b = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer c = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + final JsonbDeserializer d = new JsonbDeserializer() { + @Override + public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { + return null; + } + }; + + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{})).isEmpty(); + ; + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{}, new JsonbDeserializer[]{a})).containsExactly(a); + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{a}, new JsonbDeserializer[]{b})).contains(a, b); + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{a, b}, new JsonbDeserializer[]{c})).contains(a, b, c); + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{a, b}, new JsonbDeserializer[]{c, d})).contains(a, b, c, d); + assertThat(EscJsonbUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[]{a}, new JsonbDeserializer[]{b}, new JsonbDeserializer[]{c})).contains(a, b, c); + + } + + private EnhancedMimeType mimeType(String str) { + try { + return new EnhancedMimeType(str); + } catch (final MimeTypeParseException ex) { + throw new RuntimeException(ex); + } + } + + private Serializer dummySerializer(final String baseType) { + return new Serializer() { + @Override + public byte[] marshal(T obj, SerializedDataType type) { + if (obj == null) { + return null; + } + return obj.toString().getBytes(); + } + + @Override + public EnhancedMimeType getMimeType() { + return mimeType(baseType); + } + }; + } + + private Deserializer dummyDeserializer() { + return new Deserializer() { + @SuppressWarnings("unchecked") + @Override + public T unmarshal(Object data, SerializedDataType type, EnhancedMimeType mimeType) { + if (data instanceof byte[]) { + return (T) new String((byte[]) data); + } + throw new IllegalArgumentException("Unknown input type: " + data); + } + }; + } + + private List asList(CommonEvent... events) { + final List list = new ArrayList<>(); + for (final CommonEvent event : events) { + list.add(event); + } + return list; + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializerTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializerTest.java new file mode 100644 index 00000000..bfcc8751 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaJsonbSerializerDeserializerTest.java @@ -0,0 +1,16 @@ +package org.fuin.esc.jsonb; + +import org.fuin.utils4j.TestOmitted; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test for the {@link EscMetaJsonbSerializerDeserializer} class. + */ +@TestOmitted("Already tested along with the other tests in this package") +public class EscMetaJsonbSerializerDeserializerTest { + + // Nothing to test in addition + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaTest.java new file mode 100644 index 00000000..0092722b --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscMetaTest.java @@ -0,0 +1,217 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.json.bind.Jsonb; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IEscMeta; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link IEscMeta} class. + */ +public class EscMetaTest { + + @Test + public final void testMarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "data-type": "MyEvent", + "data-content-type":"application/xml; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type":"application/json; version=1; encoding=UTF-8", + "MyMeta":{ + "user":"abc" + } + } + """; + + final MyMeta myMeta = new MyMeta("abc"); + + final Map params = new HashMap<>(); + params.put("transfer-encoding", "base64"); + final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "xml", StandardCharsets.UTF_8, "1", params); + final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + final IEscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + myMeta); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(EscMeta.SER_TYPE, IEscMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final String currentJson = jsonb.toJson(escMeta); + + // VERIFY + assertThatJson(currentJson).isEqualTo(expectedJson); + + } + + } + + } + + @Test + public final void testUnmarshalJsonB() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "data-type": "MyEvent", + "data-content-type":"application/xml; version=1; transfer-encoding=base64; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type":"application/json; version=1; encoding=UTF-8", + "MyMeta":{ + "user":"abc" + } + } + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + final Map params = new HashMap<>(); + params.put("transfer-encoding", "base64"); + final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "xml", StandardCharsets.UTF_8, "1", params); + final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", StandardCharsets.UTF_8, "1"); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final IEscMeta testee = jsonb.fromJson(expectedJson, EscMeta.class); + + // VERIFY + assertThat(testee.getDataType()).isEqualTo("MyEvent"); + assertThat(testee.getDataContentType()).isEqualTo(dataContentType); + assertThat(testee.getMetaType()).isEqualTo("MyMeta"); + assertThat(testee.getMetaContentType()).isEqualTo(metaContentType); + assertThat(testee.getMeta()).isInstanceOf(MyMeta.class); + final MyMeta myMeta = (MyMeta) testee.getMeta(); + assertThat(myMeta.getUser()).isEqualTo("abc"); + + } + + } + + } + + @Test + public final void testMarshalJsonBBase64() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "data-type": "MyEvent", + "data-content-type": "application/xml; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/xml; transfer-encoding=base64; encoding=UTF-8", + "Base64": "PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+" + } + + """; + + final IBase64Data base64Data = new Base64Data("PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+"); + + final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/xml; encoding=UTF-8"); + final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8"); + final IEscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, + base64Data); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(EscMeta.SER_TYPE, IEscMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final String currentJson = jsonb.toJson(escMeta); + + // VERIFY + assertThatJson(currentJson).isEqualTo(expectedJson); + + } + + } + + } + + @Test + public final void testUnmarshalJsonBBase64() throws Exception { + + // PREPARE + final String expectedJson = """ + { + "data-type": "MyEvent", + "data-content-type": "application/xml; encoding=UTF-8", + "meta-type": "MyMeta", + "meta-content-type": "application/xml; transfer-encoding=base64; encoding=UTF-8", + "Base64": "PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+" + } + + """; + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/xml; encoding=UTF-8"); + final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8"); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { + + // TEST + final IEscMeta testee = jsonb.fromJson(expectedJson, EscMeta.class); + + // VERIFY + assertThat(testee.getDataType()).isEqualTo("MyEvent"); + assertThat(testee.getDataContentType()).isEqualTo(dataContentType); + assertThat(testee.getMetaType()).isEqualTo("MyMeta"); + assertThat(testee.getMetaContentType()).isEqualTo(metaContentType); + assertThat(testee.getMeta()).isInstanceOf(IBase64Data.class); + final IBase64Data base64Data = (IBase64Data) testee.getMeta(); + assertThat(base64Data.getEncoded()).isEqualTo("PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+"); + + } + + } + + } + +} + diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/EscSpiUtilsTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/EscSpiUtilsTest.java new file mode 100644 index 00000000..a711c28e --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/EscSpiUtilsTest.java @@ -0,0 +1,271 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import jakarta.activation.MimeTypeParseException; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.IBase64Data; +import org.fuin.esc.api.IEscMeta; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.Serializer; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.spi.EscSpiUtils; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the {@link EscSpiUtils} class together with {@link EscMeta}. + */ +public class EscSpiUtilsTest { + + private static final EnhancedMimeType TARGET_CONTENT_TYPE = EnhancedMimeType.create("application/json; encoding=UTF-8"); + + private static final UUID ID = UUID.fromString("f9004db0-0bd8-4e68-811c-89899e2ed9b1"); + + private static final String DESC = "Whatever"; + public static final EnhancedMimeType XML_BASE64_UTF8 = EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=utf-8"); + public static final EnhancedMimeType JSON_UTF8 = EnhancedMimeType.create("application/json; encoding=UTF-8"); + + @Test + public void testCreateEscMeta_TargetJson_DataJson_MetaNull() throws IOException { + + // PREPARE + final MyEvent myEvent = new MyEvent(ID, DESC); + final EventId eventId = new EventId(); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, jsonbDeSer); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), TARGET_CONTENT_TYPE, commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo(JSON_UTF8); + assertThat(result.getMetaType()).isNull(); + assertThat(result.getMetaContentType()).isNull(); + assertThat(result.getMeta()).isNull(); + + } + + } + + @Test + public void testCreateEscMeta_TargetJson_DataXml_MetaNull() throws IOException { + + // PREPARE + final MyEvent myEvent = new MyEvent(ID, DESC); + final EventId eventId = new EventId(); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, dummySerializer("application/xml; encoding=utf-8")); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), TARGET_CONTENT_TYPE, commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo(XML_BASE64_UTF8); + assertThat(result.getMetaType()).isNull(); + assertThat(result.getMetaContentType()).isNull(); + assertThat(result.getMeta()).isNull(); + + } + + } + + @Test + public void testCreateEscMeta_TargetJson_DataJson_MetaJson() throws IOException { + + // PREPARE + final MyEvent myEvent = new MyEvent(ID, DESC); + final EventId eventId = new EventId(); + final MyMeta myMeta = new MyMeta("peter"); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, jsonbDeSer); + registry.addSerializer(MyMeta.SER_TYPE, jsonbDeSer); + + + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, + myMeta); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), TARGET_CONTENT_TYPE, commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo(JSON_UTF8); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); + assertThat(result.getMetaContentType()).isEqualTo(JSON_UTF8); + assertThat(result.getMeta()).isEqualTo(myMeta); + + } + + } + + @Test + public void testCreateEscMeta_TargetJson_DataJson_MetaXml() throws IOException { + + // PREPARE + final MyEvent myEvent = new MyEvent(ID, DESC); + final EventId eventId = new EventId(); + final MyMeta myMeta = new MyMeta("peter"); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, jsonbDeSer); + registry.addSerializer(MyMeta.SER_TYPE, dummySerializer("application/xml; encoding=utf-8")); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, + myMeta); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), TARGET_CONTENT_TYPE, commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo(JSON_UTF8); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); + assertThat(result.getMetaContentType()).isEqualTo(XML_BASE64_UTF8); + assertThat(result.getMeta()).isInstanceOf(IBase64Data.class); + final IBase64Data base64Meta = (IBase64Data) result.getMeta(); + assertThat(new String(base64Meta.getDecoded(), StandardCharsets.UTF_8)).isEqualTo( + "peter"); + + } + + } + + @Test + public void testCreateEscMeta_TargetJson_DataXml_MetaJson() throws IOException { + + // PREPARE + final MyEvent myEvent = new MyEvent(ID, DESC); + final EventId eventId = new EventId(); + final MyMeta myMeta = new MyMeta("peter"); + + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + + try (final JsonbDeSerializer jsonbDeSer = TestUtils.createJsonbDeSerializer()) { + TestUtils.initSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.addSerializer(MyEvent.SER_TYPE, dummySerializer("application/xml; encoding=utf-8")); + registry.addSerializer(MyMeta.SER_TYPE, jsonbDeSer); + final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, + myMeta); + + // TEST + final IEscMeta result = EscSpiUtils.createEscMeta(registry, new BaseTypeFactory(), TARGET_CONTENT_TYPE, commonEvent); + + // VERIFY + assertThat(result).isNotNull(); + assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); + assertThat(result.getDataContentType()).isEqualTo(XML_BASE64_UTF8); + assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); + assertThat(result.getMetaContentType()).isEqualTo(JSON_UTF8); + assertThat(result.getMeta()).isInstanceOf(MyMeta.class); + + } + + } + + private EnhancedMimeType mimeType(String str) { + try { + return new EnhancedMimeType(str); + } catch (final MimeTypeParseException ex) { + throw new RuntimeException(ex); + } + } + + private Serializer dummySerializer(final String mimeType) { + return new Serializer() { + @Override + public byte[] marshal(T obj, SerializedDataType type) { + if (obj == null) { + return null; + } + if (obj instanceof MyEvent) { + return ("" + ID + "").getBytes(StandardCharsets.UTF_8); + } + if (obj instanceof MyMeta) { + return "peter".getBytes(StandardCharsets.UTF_8); + } + throw new IllegalStateException("Unknown object type: " + obj); + } + + @Override + public EnhancedMimeType getMimeType() { + return mimeType(mimeType); + } + }; + } + + private List asList(CommonEvent... events) { + return new ArrayList<>(Arrays.asList(events)); + } + +} + diff --git a/api/src/test/java/org/fuin/esc/api/JsonbDeSerializerTest.java b/jsonb/src/test/java/org/fuin/esc/jsonb/JsonbDeSerializerTest.java similarity index 70% rename from api/src/test/java/org/fuin/esc/api/JsonbDeSerializerTest.java rename to jsonb/src/test/java/org/fuin/esc/jsonb/JsonbDeSerializerTest.java index a61b087d..c1091df9 100644 --- a/api/src/test/java/org/fuin/esc/api/JsonbDeSerializerTest.java +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/JsonbDeSerializerTest.java @@ -1,30 +1,36 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.api; +package org.fuin.esc.jsonb; -import org.fuin.utils4j.TestOmitted; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; /** * Tests the {@link JsonbDeSerializer} class. */ -@TestOmitted("Already tested with the other tests") public class JsonbDeSerializerTest { - // Nothing to do - + @Disabled("TODO Implement!") + @Test + void testX() { + fail("Implement!"); + } + } diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/MyEvent.java b/jsonb/src/test/java/org/fuin/esc/jsonb/MyEvent.java new file mode 100644 index 00000000..fe0960c6 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/MyEvent.java @@ -0,0 +1,144 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.json.bind.annotation.JsonbProperty; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.io.Serializable; +import java.util.UUID; + +/** + * Something interesting happened. Equals and hash code are based on the UUID. + */ +@ArchIgnore +public final class MyEvent implements Serializable { + + private static final long serialVersionUID = 100L; + + /** Unique name of the event. */ + public static final TypeName TYPE = new TypeName("MyEvent"); + + /** Unique name of the serialized event. */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @JsonbProperty + private String id; + + @JsonbProperty + private String description; + + /** + * Protected default constructor for JAXB. + */ + protected MyEvent() { + super(); + } + + /** + * Constructor with random UUID. + * + * @param description + * The description. + */ + public MyEvent(@NotEmpty final String description) { + super(); + Contract.requireArgNotEmpty("description", description); + this.id = UUID.randomUUID().toString(); + this.description = description; + } + + /** + * Constructor with all mandatory data. + * + * @param uuid + * The unique identifier of the event. + * @param description + * The description. + */ + public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { + super(); + Contract.requireArgNotNull("uuid", uuid); + Contract.requireArgNotEmpty("description", description); + this.id = uuid.toString(); + this.description = description; + } + + /** + * Returns the unique identifier. + * + * @return UUID string. + */ + @NotNull + public final String getId() { + return id; + } + + /** + * Returns the description. + * + * @return The description. + */ + @NotEmpty + public final String getDescription() { + return description; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyEvent other = (MyEvent) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + + @Override + public final String toString() { + return "My event: " + description; + } + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/MyMeta.java b/jsonb/src/test/java/org/fuin/esc/jsonb/MyMeta.java new file mode 100644 index 00000000..ad2a0d79 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/MyMeta.java @@ -0,0 +1,114 @@ +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.annotation.Nullable; +import jakarta.json.bind.annotation.JsonbProperty; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; + +import java.io.Serial; +import java.io.Serializable; + +/** + * Example meta data. . + */ +@ArchIgnore +public final class MyMeta implements Serializable { + + @Serial + private static final long serialVersionUID = 100L; + + /** + * Unique name of the meta type. + */ + public static final TypeName TYPE = new TypeName("MyMeta"); + + /** + * Unique name of the serialized meta type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + @JsonbProperty + private String user; + + /** + * Protected default constructor for JAXB. + */ + protected MyMeta() { + super(); + } + + /** + * Constructor with all mandatory data. + * + * @param user User ID. + */ + public MyMeta(@Nullable final String user) { + super(); + this.user = user; + } + + /** + * Returns the user. + * + * @return User ID. + */ + public final String getUser() { + return user; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((user == null) ? 0 : user.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyMeta other = (MyMeta) obj; + if (user == null) { + if (other.user != null) { + return false; + } + } else if (!user.equals(other.user)) { + return false; + } + return true; + } + + + @Override + public final String toString() { + return "My meta: " + user; + } + +} diff --git a/jsonb/src/test/java/org/fuin/esc/jsonb/TestUtils.java b/jsonb/src/test/java/org/fuin/esc/jsonb/TestUtils.java new file mode 100644 index 00000000..21b7f5a0 --- /dev/null +++ b/jsonb/src/test/java/org/fuin/esc/jsonb/TestUtils.java @@ -0,0 +1,62 @@ +package org.fuin.esc.jsonb; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.validation.constraints.NotNull; +import org.eclipse.yasson.FieldAccessStrategy; +import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.objects4j.common.Contract; + +import java.nio.charset.StandardCharsets; + +/** + * Helper methods for the test package. + */ +@ArchIgnore +final class TestUtils { + + private TestUtils() { + } + + /** + * Creates a {@link JsonbDeSerializer} with standard settings. + * + * @return New instance. + */ + public static JsonbDeSerializer createJsonbDeSerializer() { + return JsonbDeSerializer.builder() + .withSerializers(EscJsonbUtils.createEscJsonbSerializers()) + .withDeserializers(EscJsonbUtils.createEscJsonbDeserializers()) + .withPropertyVisibilityStrategy(new FieldAccessStrategy()) + .withEncoding(StandardCharsets.UTF_8) + .build(); + } + + /** + * Creates a registry that connects the type with the appropriate serializer and de-serializer. + * + * @param typeRegistry Type registry (Mapping from type name to class). + * @param jsonbDeSer JSON-B serializer/deserializer to use. + */ + public static void initSerDeserializerRegistry(@NotNull SerializedDataTypeRegistry typeRegistry, + @NotNull JsonbDeSerializer jsonbDeSer) { + + Contract.requireArgNotNull("typeRegistry", typeRegistry); + Contract.requireArgNotNull("jsonbDeSer", jsonbDeSer); + + SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + + // Base types always needed + registry.add(EscEvents.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscEvent.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(EscMeta.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + // User defined types + registry.add(MyMeta.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + registry.add(MyEvent.SER_TYPE, jsonbDeSer.getMimeType().getBaseType(), jsonbDeSer); + + jsonbDeSer.init(typeRegistry, registry, registry); + + } + +} diff --git a/jsonb/src/test/resources/ok.png b/jsonb/src/test/resources/ok.png new file mode 100644 index 00000000..0ba1c041 Binary files /dev/null and b/jsonb/src/test/resources/ok.png differ diff --git a/mem/README.md b/mem/README.md index 9c88f8ca..c55cb05d 100644 --- a/mem/README.md +++ b/mem/README.md @@ -1,4 +1,6 @@ # esc-mem + In-memory implementation of the event store commons api for unit testing. -**LIMITATIONS**: This implementation can only handle integer values (not long) internally. This means event numbers larger that the max integer value will lead to an exception. \ No newline at end of file +**LIMITATIONS**: This implementation can only handle integer values (not long) internally. This means event numbers +larger that the max integer value will lead to an exception. \ No newline at end of file diff --git a/mem/pom.xml b/mem/pom.xml index 11199019..b1d85b8c 100644 --- a/mem/pom.xml +++ b/mem/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 @@ -41,11 +41,6 @@ esc-spi - - org.fuin.objects4j - objects4j-core - - jakarta.validation jakarta.validation-api @@ -53,13 +48,8 @@ - org.apache.commons - commons-lang3 - - - - org.slf4j - slf4j-api + org.fuin.objects4j + objects4j-common @@ -94,12 +84,42 @@ test + + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 + test + + + + org.fuin + units4j + test + + + + org.fuin.objects4j + objects4j-core + test + + + + org.fuin + utils4j + test + + - + - + org.apache.maven.plugins maven-compiler-plugin @@ -134,9 +154,27 @@ org.apache.maven.plugins maven-jdeps-plugin - + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + + - + diff --git a/mem/src/main/java/org/fuin/esc/mem/IInMemoryEventStore.java b/mem/src/main/java/org/fuin/esc/mem/IInMemoryEventStore.java index 47c28bb5..060794ce 100644 --- a/mem/src/main/java/org/fuin/esc/mem/IInMemoryEventStore.java +++ b/mem/src/main/java/org/fuin/esc/mem/IInMemoryEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/mem/src/main/java/org/fuin/esc/mem/InMemoryEventStore.java b/mem/src/main/java/org/fuin/esc/mem/InMemoryEventStore.java index c058e1b5..3255bf6c 100644 --- a/mem/src/main/java/org/fuin/esc/mem/InMemoryEventStore.java +++ b/mem/src/main/java/org/fuin/esc/mem/InMemoryEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -32,17 +32,17 @@ */ public final class InMemoryEventStore extends AbstractReadableEventStore implements IInMemoryEventStore { - private Executor executor; + private final Executor executor; - private Map streams; + private final Map streams; - private Map> subscriptions; + private final Map> subscriptions; private boolean open; /** * Constructor with all mandatory data. - * + * * @param executor * Executor used to create the necessary threads for event notifications. */ @@ -57,7 +57,7 @@ public InMemoryEventStore(@NotNull final Executor executor) { } @Override - public final InMemoryEventStore open() { + public InMemoryEventStore open() { if (open) { // Ignore return this; @@ -67,7 +67,7 @@ public final InMemoryEventStore open() { } @Override - public final void close() { + public void close() { if (!open) { // Ignore return; @@ -76,17 +76,17 @@ public final void close() { } @Override - public final boolean isSupportsCreateStream() { + public boolean isSupportsCreateStream() { return false; } @Override - public final void createStream(final StreamId streamId) throws StreamAlreadyExistsException { + public void createStream(final StreamId streamId) throws StreamAlreadyExistsException { // Do nothing } @Override - public final boolean streamExists(final StreamId streamId) { + public boolean streamExists(final StreamId streamId) { Contract.requireArgNotNull("streamId", streamId); ensureOpen(); @@ -97,7 +97,7 @@ public final boolean streamExists(final StreamId streamId) { } @Override - public final CommonEvent readEvent(final StreamId streamId, final long eventNumber) { + public CommonEvent readEvent(final StreamId streamId, final long eventNumber) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("eventNumber", eventNumber, 0); @@ -112,7 +112,7 @@ public final CommonEvent readEvent(final StreamId streamId, final long eventNumb } @Override - public final StreamEventsSlice readEventsForward(final StreamId streamId, final long start, final int count) { + public StreamEventsSlice readEventsForward(final StreamId streamId, final long start, final int count) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("start", start, 0); @@ -134,7 +134,7 @@ public final StreamEventsSlice readEventsForward(final StreamId streamId, final } @Override - public final StreamEventsSlice readEventsBackward(final StreamId streamId, final long start, final int count) { + public StreamEventsSlice readEventsBackward(final StreamId streamId, final long start, final int count) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgMin("start", start, 0); @@ -161,7 +161,7 @@ public final StreamEventsSlice readEventsBackward(final StreamId streamId, final } @Override - public final void deleteStream(final StreamId streamId, final long expected, final boolean hardDelete) { + public void deleteStream(final StreamId streamId, final long expected, final boolean hardDelete) { Contract.requireArgNotNull("streamId", streamId); ensureOpen(); @@ -200,14 +200,14 @@ public final void deleteStream(final StreamId streamId, final long expected, fin } @Override - public final void deleteStream(final StreamId streamId, final boolean hardDelete) { + public void deleteStream(final StreamId streamId, final boolean hardDelete) { deleteStream(streamId, ExpectedVersion.ANY.getNo(), hardDelete); } @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, final List toAppend) { + public long appendToStream(final StreamId streamId, final long expectedVersion, final List toAppend) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgNotNull("toAppend", toAppend); @@ -247,21 +247,21 @@ public final long appendToStream(final StreamId streamId, final long expectedVer } @Override - public final long appendToStream(final StreamId streamId, final long expectedVersion, final CommonEvent... events) { + public long appendToStream(final StreamId streamId, final long expectedVersion, final CommonEvent... events) { return appendToStream(streamId, expectedVersion, EscSpiUtils.asList(events)); } @Override - public final long appendToStream(final StreamId streamId, final List toAppend) { + public long appendToStream(final StreamId streamId, final List toAppend) { return appendToStream(streamId, ExpectedVersion.ANY.getNo(), toAppend); } @Override - public final long appendToStream(final StreamId streamId, final CommonEvent... events) { + public long appendToStream(final StreamId streamId, final CommonEvent... events) { Contract.requireArgNotNull("events", events); @@ -270,8 +270,8 @@ public final long appendToStream(final StreamId streamId, final CommonEvent... e } @Override - public final Subscription subscribeToStream(final StreamId streamId, final long eventNumber, - final BiConsumer onEvent, final BiConsumer onDrop) { + public Subscription subscribeToStream(final StreamId streamId, final long eventNumber, + final BiConsumer onEvent, final BiConsumer onDrop) { Contract.requireArgNotNull("streamId", streamId); Contract.requireArgNotNull("onEvent", onEvent); @@ -298,7 +298,7 @@ public final Subscription subscribeToStream(final StreamId streamId, final long } @Override - public final void unsubscribeFromStream(final Subscription subscription) { + public void unsubscribeFromStream(final Subscription subscription) { Contract.requireArgNotNull("subscription", subscription); ensureOpen(); @@ -319,7 +319,7 @@ public final void unsubscribeFromStream(final Subscription subscription) { } @Override - public final StreamState streamState(final StreamId streamId) { + public StreamState streamState(final StreamId streamId) { Contract.requireArgNotNull("streamId", streamId); ensureOpen(); @@ -415,46 +415,46 @@ public InternalStream() { /** * Adds a number of events to the stream. - * + * * @param events * Events to add. */ - public final void addAll(final List events) { + public void addAll(final List events) { this.events.addAll(events); version = version + events.size(); } /** * Returns the state of the stream. - * - * @return TRUE if it was a hard delete. + * + * @return State of the stream. */ - public final StreamState getState() { + public StreamState getState() { return state; } /** * Current version of the stream. - * + * * @return Version. */ - public final long getVersion() { + public long getVersion() { return version; } /** * Returns the event list. - * + * * @return Events before deletion. */ - public final List getEvents() { + public List getEvents() { return Collections.unmodifiableList(events); } /** * Hard deletes the stream. */ - public final void delete(final boolean hardDelete) { + public void delete(final boolean hardDelete) { if (hardDelete) { this.state = StreamState.HARD_DELETED; } else { @@ -466,7 +466,7 @@ public final void delete(final boolean hardDelete) { /** * Reverts the deletion of the stream. */ - public final void undelete() { + public void undelete() { if (state != StreamState.SOFT_DELETED) { throw new IllegalStateException("Undelete impossible, state was: " + state); } @@ -486,7 +486,7 @@ private static final class InternalSubscription { /** * Constructor for find operations. NEVER USE for - * + * * @param subscription * The subscription. */ @@ -496,13 +496,11 @@ public InternalSubscription(final InMemorySubscription subscription) { /** * Constructor with all mandatory data. - * + * * @param subscription * The subscription. * @param eventListener * Listens to events. - * @param dropListener - * Listens to exceptions. */ public InternalSubscription(final InMemorySubscription subscription, final BiConsumer eventListener) { super(); @@ -511,12 +509,12 @@ public InternalSubscription(final InMemorySubscription subscription, final BiCon } @Override - public final int hashCode() { + public int hashCode() { return subscription.hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -532,19 +530,19 @@ public final boolean equals(final Object obj) { /** * Returns the subscription. - * + * * @return the subscription */ - public final InMemorySubscription getSubscription() { + public InMemorySubscription getSubscription() { return subscription; } /** * Returns the event listener. - * + * * @return the listener */ - public final BiConsumer getEventListener() { + public BiConsumer getEventListener() { return eventListener; } diff --git a/mem/src/main/java/org/fuin/esc/mem/InMemorySubscription.java b/mem/src/main/java/org/fuin/esc/mem/InMemorySubscription.java index 934a7991..bf3b76dc 100644 --- a/mem/src/main/java/org/fuin/esc/mem/InMemorySubscription.java +++ b/mem/src/main/java/org/fuin/esc/mem/InMemorySubscription.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -33,7 +33,7 @@ public final class InMemorySubscription extends Subscription implements /** * Creates a subscription. - * + * * @param subscriberId * Uniquely identifies a subscriber. * @param streamId @@ -42,22 +42,22 @@ public final class InMemorySubscription extends Subscription implements * Last event seen on the stream. */ public InMemorySubscription(final int subscriberId, - final StreamId streamId, final Long lastEventNumber) { + final StreamId streamId, final Long lastEventNumber) { super(streamId, lastEventNumber); this.subscriberId = subscriberId; } /** * Returns the subscriber ID. - * + * * @return Uniquely identifies a subscriber. */ - public final int getSubscriberId() { + public int getSubscriberId() { return subscriberId; } @Override - public final int hashCode() { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + subscriberId; @@ -65,7 +65,7 @@ public final int hashCode() { } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -80,7 +80,7 @@ public final boolean equals(final Object obj) { } @Override - public final int compareTo(final InMemorySubscription other) { + public int compareTo(final InMemorySubscription other) { if (subscriberId > other.subscriberId) { return 1; } @@ -91,8 +91,8 @@ public final int compareTo(final InMemorySubscription other) { } @Override - public final String toString() { + public String toString() { return this.getClass().getSimpleName() + "#" + subscriberId; } - + } diff --git a/mem/src/test/java/org/fuin/esc/mem/ArchitectureTest.java b/mem/src/test/java/org/fuin/esc/mem/ArchitectureTest.java new file mode 100644 index 00000000..9a2540b9 --- /dev/null +++ b/mem/src/test/java/org/fuin/esc/mem/ArchitectureTest.java @@ -0,0 +1,60 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.mem; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; +import org.fuin.esc.spi.EscSpiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.annotation..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.slf4j.." + ); + + +} + diff --git a/mem/src/test/java/org/fuin/esc/mem/BaseTest.java b/mem/src/test/java/org/fuin/esc/mem/BaseTest.java index 45ed5afc..00266aec 100644 --- a/mem/src/test/java/org/fuin/esc/mem/BaseTest.java +++ b/mem/src/test/java/org/fuin/esc/mem/BaseTest.java @@ -1,44 +1,45 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. + * along with this library. If not, see . */ package org.fuin.esc.mem; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; -/** - * General tests for all classes. - */ -// CHECKSTYLE:OFF Test code -public class BaseTest { +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; - @Disabled("Implement with ArchUnit!") - @Test - public final void testCoverage() { - // Make sure all classes have a test - // TODO Implement! - } +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { - @Disabled("Implement with ArchUnit!") - @Test - public final void testNullability() { - // Make sure all public/protected methods have either @Nullable or @NotNull - // TODO Implement! - } + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); } -//CHECKSTYLE:ON + diff --git a/mem/src/test/java/org/fuin/esc/mem/InMemoryEventStoreTest.java b/mem/src/test/java/org/fuin/esc/mem/InMemoryEventStoreTest.java index 2e79575a..53410d69 100644 --- a/mem/src/test/java/org/fuin/esc/mem/InMemoryEventStoreTest.java +++ b/mem/src/test/java/org/fuin/esc/mem/InMemoryEventStoreTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -36,7 +36,6 @@ /** * Tests the {@link InMemoryEventStore} class. */ -// CHECKSTYLE:OFF Test public class InMemoryEventStoreTest { private InMemoryEventStore testee; @@ -337,4 +336,4 @@ public final String toString() { } } -// CHECKSTYLE:ON + diff --git a/mem/src/test/java/org/fuin/esc/mem/InMemorySubscriptionTest.java b/mem/src/test/java/org/fuin/esc/mem/InMemorySubscriptionTest.java index 417b3534..b41d3f84 100644 --- a/mem/src/test/java/org/fuin/esc/mem/InMemorySubscriptionTest.java +++ b/mem/src/test/java/org/fuin/esc/mem/InMemorySubscriptionTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -30,7 +30,7 @@ /** * Tests the class {@link InMemorySubscription}. */ -// CHECKSTYLE:OFF Test code + public class InMemorySubscriptionTest { @Test @@ -57,4 +57,4 @@ public void testEqualsHashCode() { } } -// CHECKSTYLE:ON + diff --git a/mem/src/test/java/org/fuin/esc/mem/MyEvent.java b/mem/src/test/java/org/fuin/esc/mem/MyEvent.java index 32067d7a..446f201a 100644 --- a/mem/src/test/java/org/fuin/esc/mem/MyEvent.java +++ b/mem/src/test/java/org/fuin/esc/mem/MyEvent.java @@ -1,9 +1,11 @@ -// CHECKSTYLE:OFF package org.fuin.esc.mem; +import com.tngtech.archunit.junit.ArchIgnore; + /** * Example event. */ +@ArchIgnore public class MyEvent { private String name; @@ -47,4 +49,4 @@ public String toString() { } } -// CHECKSTYLE:ON + diff --git a/pom.xml b/pom.xml index 1c71aff7..c29809f8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,456 +1,478 @@ - - - 4.0.0 - - - org.fuin - pom - 1.9.0 - - - org.fuin.esc - esc-parent - 0.8.0-SNAPSHOT - pom - esc-parent - Defines a common event store Java interface and provides some adapters (like for Greg Young's event store) and implementations (like in-memory or file-based). - - - https://github.com/fuinorg/event-store-commons/ - scm:git:git://github.com/fuinorg/event-store-commons.git - scm:git:git@github.com:fuinorg/event-store-commons.git - - - - GitHub Issues - https://github.com/fuinorg/event-store-commons/issues - - - - 21.10.1-bionic - --add-opens java.base/java.util=ALL-UNNAMED - 0.10.0-SNAPSHOT - - - - - - - - org.fuin.esc - esc-api - ${project.version} - - - - org.fuin.esc - esc-spi - ${project.version} - - - - org.fuin.esc - esc-mem - ${project.version} - - - - org.fuin.esc - esc-eshttp - ${project.version} - - - - org.fuin.esc - esc-jpa - ${project.version} - - - - org.fuin.esc - esc-esjc - ${project.version} - - - - org.fuin.esc - esc-esgrpc - ${project.version} - - - - org.fuin - utils4j - 0.14.0-SNAPSHOT - - - - org.fuin.objects4j - objects4j-common - ${objects4j.version} - - - - org.fuin.objects4j - objects4j-core - ${objects4j.version} - - - - io.smallrye - jandex - 3.1.6 - - - - jakarta.validation - jakarta.validation-api - 3.0.2 - - - - org.apache.commons - commons-lang3 - 3.14.0 - - - - commons-io - commons-io - 2.15.1 - - - - org.slf4j - slf4j-api - 2.0.9 - - - - io.github.threeten-jaxb - threeten-jaxb-core - 2.1.0 - - - - jakarta.json - jakarta.json-api - 2.1.3 - - - - com.jayway.jsonpath - json-path - 2.9.0 - - - - com.google.code.gson - gson - 2.10.1 - - - - org.junit.jupiter - junit-jupiter - 5.10.1 - - - - org.assertj - assertj-core - 3.25.2 - - - - org.hibernate.validator - hibernate-validator - 8.0.1.Final - - - - org.xmlunit - xmlunit-core - 2.9.1 - - - - nl.jqno.equalsverifier - equalsverifier - 3.15.6 - - - - commons-codec - commons-codec - 1.16.0 - - - - net.javacrumbs.json-unit - json-unit-fluent - 3.2.2 - - - - org.mockito - mockito-core - 5.10.0 - - - - org.mockito - mockito-junit-jupiter - 5.10.0 - test - - - - ch.qos.logback - logback-classic - 1.4.14 - - - - org.apache.httpcomponents - httpasyncclient - 4.1.5 - - - - org.apache.httpcomponents - httpcore-nio - 4.4.16 - - - - org.apache.httpcomponents - httpcore - 4.4.16 - - - - org.apache.httpcomponents - httpclient - 4.5.14 - - - - com.github.msemys - esjc - 2.6.0 - - - - io.cucumber - cucumber-java - 1.2.6 - - - - io.cucumber - cucumber-junit - 1.2.6 - - - - javax.transaction - jta - 1.1 - - - - org.jboss.logging - jboss-logging - 3.5.3.Final - - - - org.hibernate - hibernate-core-jakarta - 5.6.15.Final - - - - org.hsqldb - hsqldb - 2.7.2 - - - - jakarta.json.bind - jakarta.json.bind-api - 3.0.0 - - - - org.eclipse - yasson - 3.0.3 - - - - jakarta.enterprise - jakarta.enterprise.cdi-api - 4.0.1 - - - - jakarta.persistence - jakarta.persistence-api - 3.1.0 - - - - jakarta.xml.bind - jakarta.xml.bind-api - 4.0.1 - - - - org.glassfish.jaxb - jaxb-runtime - 4.0.4 - - - - jakarta.el - jakarta.el-api - 5.0.1 - - - - org.glassfish - jakarta.el - 4.0.1 - - - - io.smallrye - jandex - 3.1.6 - - - - - - - - api - spi - mem - jpa - esgrpc - test - - - - - - - - - - io.fabric8 - docker-maven-plugin - 0.38.1 - - - - org.apache.maven.plugins - maven-failsafe-plugin - 3.2.3 - - ${failsafe.argLine} - - - - integration-test - - integration-test - - - - verify - - verify - - - - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - --add-opens java.base/java.util=ALL-UNNAMED - - - - - io.smallrye - jandex-maven-plugin - 3.0.6 - - - make-index - - jandex - - - - - - - org.jacoco - jacoco-maven-plugin - - - pre-unit-test - - prepare-agent - - - - post-unit-test - test - - report - - - - pre-integration-test - pre-integration-test - - prepare-agent - - - target/jacoco.exec - failsafe.argLine - - - - post-integration-test - post-integration-test - - report - - - target/jacoco.exec - - - - - - - - + + + 4.0.0 + + + org.fuin + pom + 1.9.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + pom + esc-parent + Defines a common event store Java interface and provides some adapters (like for Greg Young's event store) and implementations (like in-memory or file-based). + + + + https://github.com/fuinorg/event-store-commons/ + scm:git:git://github.com/fuinorg/event-store-commons.git + scm:git:git@github.com:fuinorg/event-store-commons.git + + + + GitHub Issues + https://github.com/fuinorg/event-store-commons/issues + + + + 21.10.1-bionic + --add-opens java.base/java.util=ALL-UNNAMED + 0.10.0-SNAPSHOT + + + + + + + + org.fuin.esc + esc-api + ${project.version} + + + + org.fuin.esc + esc-client + ${project.version} + + + + org.fuin.esc + esc-spi + ${project.version} + + + + org.fuin.esc + esc-mem + ${project.version} + + + + org.fuin.esc + esc-jaxb + ${project.version} + + + + org.fuin.esc + esc-jpa + ${project.version} + + + + org.fuin.esc + esc-jsonb + ${project.version} + + + + org.fuin.esc + esc-esgrpc + ${project.version} + + + + org.fuin + utils4j + 0.14.0-SNAPSHOT + + + + org.fuin.objects4j + objects4j-common + ${objects4j.version} + + + + org.fuin.objects4j + objects4j-core + ${objects4j.version} + + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + + org.apache.commons + commons-lang3 + 3.14.0 + + + + commons-io + commons-io + 2.15.1 + + + + org.slf4j + slf4j-api + 2.0.9 + + + + com.google.code.gson + gson + 2.10.1 + + + + org.junit.jupiter + junit-jupiter + 5.10.1 + + + + org.assertj + assertj-core + 3.25.2 + + + + org.hibernate.validator + hibernate-validator + 8.0.1.Final + + + + nl.jqno.equalsverifier + equalsverifier + 3.15.6 + + + + commons-codec + commons-codec + 1.16.0 + + + + org.mockito + mockito-core + 5.10.0 + + + + org.mockito + mockito-junit-jupiter + 5.10.0 + test + + + + ch.qos.logback + logback-classic + 1.4.14 + + + + org.apache.httpcomponents + httpclient + 4.5.14 + + + + io.cucumber + cucumber-java + 1.2.6 + + + + io.cucumber + cucumber-junit + 1.2.6 + + + + javax.transaction + jta + 1.1 + + + + org.jboss.logging + jboss-logging + 3.5.3.Final + + + + org.hibernate + hibernate-core-jakarta + 5.6.15.Final + + + + org.hsqldb + hsqldb + 2.7.2 + + + + jakarta.persistence + jakarta.persistence-api + 3.1.0 + + + + jakarta.el + jakarta.el-api + 5.0.1 + + + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.1 + + + + io.github.threeten-jaxb + threeten-jaxb-core + 2.1.0 + + + + org.glassfish.jaxb + jaxb-runtime + 4.0.4 + + + + org.xmlunit + xmlunit-core + 2.9.1 + + + + jakarta.json.bind + jakarta.json.bind-api + 3.0.0 + + + + jakarta.json + jakarta.json-api + 2.1.3 + + + + org.eclipse + yasson + 3.0.3 + + + + org.glassfish + jakarta.el + 4.0.2 + + + + net.javacrumbs.json-unit + json-unit-fluent + 3.2.2 + + + + io.smallrye + jandex + 3.1.6 + + + + com.tngtech.archunit + archunit + 1.2.1 + + + + com.tngtech.archunit + archunit-junit5 + 1.2.1 + + + + org.fuin + units4j + 0.12.0-SNAPSHOT + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + jakarta.annotation + jakarta.annotation-api + 2.1.0 + + + + jakarta.activation + jakarta.activation-api + 2.1.2 + + + + + + + + api + client + spi + mem + jaxb + jpa + jsonb + esgrpc + test + + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.6.1 + + + analyze + + analyze-only + + + true + + + + + + + io.fabric8 + docker-maven-plugin + 0.38.1 + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.2.3 + + ${failsafe.argLine} + + + + integration-test + + integration-test + + + + verify + + verify + + + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + --add-opens java.base/java.util=ALL-UNNAMED + + + + + io.smallrye + jandex-maven-plugin + 3.0.6 + + + make-index + + jandex + + + + + + + org.jacoco + jacoco-maven-plugin + + + pre-unit-test + + prepare-agent + + + + post-unit-test + test + + report + + + + pre-integration-test + pre-integration-test + + prepare-agent + + + target/jacoco.exec + failsafe.argLine + + + + post-integration-test + post-integration-test + + report + + + target/jacoco.exec + + + + + + + + diff --git a/settings.xml b/settings.xml index e93a71df..ba5f8753 100644 --- a/settings.xml +++ b/settings.xml @@ -1,22 +1,22 @@ - + - sonatype-nexus-snapshots - ${env.OSS_SONATYPE_USERNAME} - ${env.OSS_SONATYPE_TOKEN} + sonatype-nexus-snapshots + ${env.OSS_SONATYPE_USERNAME} + ${env.OSS_SONATYPE_TOKEN} - + - sonatype-nexus-staging - ${env.OSS_SONATYPE_USERNAME} - ${env.OSS_SONATYPE_TOKEN} + sonatype-nexus-staging + ${env.OSS_SONATYPE_USERNAME} + ${env.OSS_SONATYPE_TOKEN} - + @@ -47,7 +47,7 @@ true - + sonatype.oss.releases Sonatype OSS Releases Repository @@ -76,7 +76,7 @@ true - + sonatype.oss.releases Sonatype OSS Releases Repository @@ -88,7 +88,7 @@ false - + diff --git a/spi/README.md b/spi/README.md index 888eb2f3..4363e84a 100644 --- a/spi/README.md +++ b/spi/README.md @@ -1,2 +1,3 @@ # esc-spi + The service provider interface provides helpful classes for creating an event store implementation or adapter. diff --git a/spi/pom.xml b/spi/pom.xml index 5dfc7d6d..c6758fd6 100644 --- a/spi/pom.xml +++ b/spi/pom.xml @@ -1,189 +1,206 @@ - - 4.0.0 - - - org.fuin.esc - esc-parent - 0.8.0-SNAPSHOT - - - esc-spi - jar - esc-spi - The service provider interface provides helpful classes for - creating an event store implementation or adapter. - - - https://github.com/fuinorg/event-store-commons/ - scm:git:git://github.com/fuinorg/event-store-commons.git - - scm:git:git@github.com:fuinorg/event-store-commons.git - - - - GitHub Issues - https://github.com/fuinorg/event-store-commons/issues - - - - - - - - org.fuin.esc - esc-api - - - - org.fuin.objects4j - objects4j-core - - - - jakarta.validation - jakarta.validation-api - true - - - - org.slf4j - slf4j-api - - - - commons-codec - commons-codec - - - - jakarta.json - jakarta.json-api - - - - jakarta.json.bind - jakarta.json.bind-api - - - - jakarta.xml.bind - jakarta.xml.bind-api - - - - - - org.junit.jupiter - junit-jupiter - test - - - - org.assertj - assertj-core - test - - - - org.xmlunit - xmlunit-core - test - - - - nl.jqno.equalsverifier - equalsverifier - test - - - - ch.qos.logback - logback-classic - - - - org.hibernate.validator - hibernate-validator - test - - - - commons-io - commons-io - test - - - - net.javacrumbs.json-unit - json-unit-fluent - test - - - - com.google.code.gson - gson - test - - - - org.eclipse - yasson - test - - - - org.glassfish.jaxb - jaxb-runtime - test - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - **/* - - - - org.fuin.esc.spi - - - - - - - org.apache.maven.plugins - maven-jdeps-plugin - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + 4.0.0 + + + org.fuin.esc + esc-parent + 0.8.0-SNAPSHOT + + + esc-spi + jar + esc-spi + The service provider interface provides helpful classes for + creating an event store implementation or adapter. + + + + https://github.com/fuinorg/event-store-commons/ + scm:git:git://github.com/fuinorg/event-store-commons.git + + scm:git:git@github.com:fuinorg/event-store-commons.git + + + + + GitHub Issues + https://github.com/fuinorg/event-store-commons/issues + + + + + + + + org.fuin.esc + esc-api + + + + org.fuin.objects4j + objects4j-core + + + + jakarta.validation + jakarta.validation-api + + + + org.slf4j + slf4j-api + + + + com.google.code.findbugs + jsr305 + + + + org.fuin.objects4j + objects4j-common + + + + jakarta.annotation + jakarta.annotation-api + + + + jakarta.activation + jakarta.activation-api + + + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + nl.jqno.equalsverifier + equalsverifier + test + + + + ch.qos.logback + logback-classic + + + + org.hibernate.validator + hibernate-validator + test + + + + org.mockito + mockito-core + test + + + + org.mockito + mockito-junit-jupiter + test + + + + com.tngtech.archunit + archunit + test + + + + com.tngtech.archunit + archunit-junit5 + test + + + + org.fuin + units4j + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + + + **/* + + + + org.fuin.esc.spi + + + + + + + org.apache.maven.plugins + maven-jdeps-plugin + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + org.mockito:mockito-junit-jupiter + + + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + jakarta.activation:jakarta.activation-api + + + + + + + diff --git a/spi/src/main/java/org/fuin/esc/spi/AbstractReadableEventStore.java b/spi/src/main/java/org/fuin/esc/spi/AbstractReadableEventStore.java index dbdc5313..4677359d 100644 --- a/spi/src/main/java/org/fuin/esc/spi/AbstractReadableEventStore.java +++ b/spi/src/main/java/org/fuin/esc/spi/AbstractReadableEventStore.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -34,8 +34,8 @@ public abstract class AbstractReadableEventStore implements ReadableEventStore { @Override public final void readAllEventsForward(final StreamId streamId, - final long startingAtEventNumber, final int chunkSize, - final ChunkEventHandler handler) { + final long startingAtEventNumber, final int chunkSize, + final ChunkEventHandler handler) { long sliceStart = startingAtEventNumber; StreamEventsSlice currentSlice; @@ -52,7 +52,7 @@ public final void readAllEventsForward(final StreamId streamId, LOG.debug(ex.getMessage()); break; } - if (currentSlice.getEvents().size() > 0) { + if (!currentSlice.getEvents().isEmpty()) { handler.handle(currentSlice); } sliceStart = currentSlice.getNextEventNumber(); diff --git a/spi/src/main/java/org/fuin/esc/spi/Base64Data.java b/spi/src/main/java/org/fuin/esc/spi/Base64Data.java deleted file mode 100644 index 3c0679f0..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/Base64Data.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.json.Json; -import jakarta.json.JsonObject; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlRootElement; -import jakarta.xml.bind.annotation.XmlTransient; -import jakarta.xml.bind.annotation.XmlValue; -import org.apache.commons.codec.binary.Base64; -import org.fuin.esc.api.*; -import org.fuin.objects4j.common.Contract; - -import java.nio.charset.Charset; - -/** - * Contains some Base64 encoded data. - */ -@HasSerializedDataTypeConstant -@XmlRootElement(name = Base64Data.EL_ROOT_NAME) -public final class Base64Data implements ToJsonCapable { - - /** Unique XML/JSON root element name of the type. */ - public static final String EL_ROOT_NAME = "Base64"; - - /** Unique name of the type. */ - public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); - - /** Unique name of the serialized type. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - @XmlValue - private String base64Str; - - @XmlTransient - private byte[] binaryData; - - /** - * Default constructor for JAXB. - */ - protected Base64Data() { - super(); - } - - /** - * Constructor with Base64 encoded string. - * - * @param base64Str - * Base64 encoded data. - */ - public Base64Data(@NotNull final String base64Str) { - super(); - Contract.requireArgNotNull("base64Str", base64Str); - this.base64Str = base64Str; - this.binaryData = Base64.decodeBase64(base64Str); - } - - /** - * Constructor with binary data that will be Base64 encoded. - * - * @param binaryData - * Binary data. - */ - public Base64Data(@NotNull final byte[] binaryData) { - super(); - Contract.requireArgNotNull("binaryData", binaryData); - this.base64Str = Base64.encodeBase64String(binaryData); - this.binaryData = binaryData; - } - - /** - * Returns the Base64 encoded data. - * - * @return Base64 string. - */ - public final String getEncoded() { - return base64Str; - } - - /** - * Returns the decoded data. - * - * @return Binary data. - */ - public final byte[] getDecoded() { - if (binaryData == null) { - binaryData = Base64.decodeBase64(base64Str); - } - return binaryData; - } - - @Override - public final JsonObject toJson() { - return Json.createObjectBuilder().add(EL_ROOT_NAME, base64Str).build(); - } - - /** - * Creates in instance from the given JSON object. - * - * @param jsonObj - * Object to read values from. - * - * @return New instance. - */ - public static Base64Data create(final JsonObject jsonObj) { - final String base64Str = jsonObj.getString(EL_ROOT_NAME); - return new Base64Data(base64Str); - } - - /** - * Serializes and deserializes a {@link Base64Data} object as JSON. The - * content type for serialization is always "application/json". - */ - public static class Base64DataJsonDeSerializer implements SerDeserializer { - - private final JsonDeSerializer jsonDeSer; - - /** - * Default constructor. - */ - public Base64DataJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with encoding. - * - * @param encoding - * Default encoding to use. - */ - public Base64DataJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final Base64Data unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonObject jsonObj = jsonDeSer.unmarshal(data, type, mimeType); - return Base64Data.create(jsonObj); - } - - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/Data.java b/spi/src/main/java/org/fuin/esc/spi/Data.java deleted file mode 100644 index b8011ca3..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/Data.java +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import jakarta.json.JsonReader; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlRootElement; -import jakarta.xml.bind.annotation.XmlValue; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; -import org.fuin.objects4j.common.ValueObject; -import org.fuin.utils4j.jaxb.CDataXmlAdapter; - -import java.io.Serializable; -import java.io.StringReader; - -import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; -import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; - -/** - * Helper class that allows sending the data of an event as XML directly to the - * event store. Represents a block of data in a serialized form. This class - * might be useful for tests. It's not used in the 'esc-spi' code itself - */ -@Immutable -@XmlRootElement(name = "data") -public final class Data implements ValueObject, Serializable { - - private static final long serialVersionUID = 1000L; - - /** Unique type of the data. */ - @NotNull - @XmlAttribute(name = "type") - private String type; - - /** Internet Media Type that classifies the raw event data. */ - @NotNull - @XmlAttribute(name = "mime-type") - private String mimeType; - - /** Raw event data in format defined by the mime type and encoding. */ - @NotNull - @XmlValue - @XmlJavaTypeAdapter(CDataXmlAdapter.class) - private String content; - - /** - * Protected constructor for deserialization. - */ - protected Data() { //NOSONAR Ignore uninitialized fields - super(); - } - - /** - * Creates a data object. - * - * @param type - * Unique identifier for the type of data. - * @param mimeType - * Internet Media Type with encoding and version that classifies - * the data. - * @param content - * Content. - */ - public Data(@NotNull final String type, - @NotNull final EnhancedMimeType mimeType, - @NotNull final String content) { - super(); - - Contract.requireArgNotNull("type", type); - Contract.requireArgNotNull("mimeType", mimeType); - Contract.requireArgNotNull("content", content); - - this.type = type; - this.mimeType = mimeType.toString(); - this.content = content; - - } - - /** - * Returns the unique identifier for the type of data. - * - * @return Unique and never changing type name. - */ - @NotNull - public final String getType() { - return type; - } - - /** - * Returns the Internet Media Type that classifies the data. - * - * @return Mime type. - */ - @NotNull - public final EnhancedMimeType getMimeType() { - return EnhancedMimeType.create(mimeType); - } - - /** - * Returns the raw data block. - * - * @return Raw data. - */ - @NotNull - public final String getContent() { - return content; - } - - /** - * Returns the information if the content is XML. - * - * @return TRUE if the mime type is 'application/xml' else FALSE. - */ - public final boolean isXml() { - return getMimeType().getBaseType().equals("application/xml"); - } - - /** - * Returns the information if the content is JSON. - * - * @return TRUE if the mime type is 'application/json' else FALSE. - */ - public final boolean isJson() { - return getMimeType().getBaseType().equals("application/json"); - } - - /** - * Returns the information if the content is TEXT. - * - * @return TRUE if the mime type is 'text/plain' else FALSE. - */ - public final boolean isText() { - return getMimeType().getBaseType().equals("text/plain"); - } - - - /** - * Unmarshals the content into an object. Content is required to be - * "application/xml", "application/json" or "text/plain". - * - * @param ctx - * In case the XML JAXB unmarshalling is used, you have to pass - * the JAXB context here. - * - * @return Object created from content. - * - * @param - * Type expected to be returned. - */ - @SuppressWarnings("unchecked") - public final T unmarshalContent(final JAXBContext ctx) { - if (!(isJson() || isXml() || isText())) { - throw new IllegalStateException( - "Can only unmarshal JSON, XML or TEXT content, not: " - + mimeType); - } - - // We can only handle JSON... - if (isJson()) { - try { - try (final JsonReader reader = Json.createReader(new StringReader(content))) { - return (T) reader.readObject(); - } - } catch (final RuntimeException ex) { - throw new RuntimeException( - "Error parsing json content: '" + content + "'", ex); - } - } - // ...or XML - if (isXml()) { - try { - return unmarshal(ctx, content, null); - } catch (final RuntimeException ex) { - throw new RuntimeException( - "Error parsing xml content: '" + content + "'", ex); - } - } - // ...or TEXT - return (T) content; - } - - @Override - public final String toString() { - return new ToStringBuilder(this).append("type", type) - .append("mimeType", mimeType).append("content", content) - .toString(); - } - - /** - * Creates a new instance from a given object. - * - * @param type - * Name of the type. - * @param obj - * Object to convert. - * - * @return Either JSON or XML UTF-8 encoded content without a version. - */ - public static Data valueOf(final String type, final Object obj) { - return new Data(type, mimeType(obj), content(obj)); - } - - private static EnhancedMimeType mimeType(final Object obj) { - try { - // We can only handle JSON... - if (obj instanceof JsonObject) { - return new EnhancedMimeType("application/json; encoding=utf-8"); - } - // ...or XML - return new EnhancedMimeType("application/xml; encoding=utf-8"); - } catch (final MimeTypeParseException ex) { - throw new RuntimeException(ex); - } - } - - private static String content(final Object obj) { - // We can only handle JSON... - if (obj instanceof JsonObject) { - return obj.toString(); - } - // ...or XML - return marshal(obj, obj.getClass()); - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/EscEvent.java b/spi/src/main/java/org/fuin/esc/spi/EscEvent.java deleted file mode 100644 index 18cedf2f..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/EscEvent.java +++ /dev/null @@ -1,308 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.annotation.Nullable; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import jakarta.json.bind.serializer.DeserializationContext; -import jakarta.json.bind.serializer.JsonbDeserializer; -import jakarta.json.bind.serializer.JsonbSerializer; -import jakarta.json.bind.serializer.SerializationContext; -import jakarta.json.stream.JsonGenerator; -import jakarta.json.stream.JsonParser; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.fuin.esc.api.*; -import org.fuin.objects4j.common.Contract; - -import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.util.UUID; - -/** - * An event structure. - */ -@HasSerializedDataTypeConstant -@XmlRootElement(name = EscEvent.EL_ROOT_NAME) -public final class EscEvent implements ToJsonCapable { - - /** Unique XML/JSON root element name of the type. */ - public static final String EL_ROOT_NAME = "Event"; - - private static final String EL_EVENT_ID = "EventId"; - - private static final String EL_EVENT_TYPE = "EventType"; - - private static final String EL_DATA = "Data"; - - private static final String EL_META_DATA = "MetaData"; - - /** Unique name of the type. */ - public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); - - /** Unique name of the serialized type. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - @XmlElement(name = EL_EVENT_ID) - private String eventId; - - @XmlElement(name = EL_EVENT_TYPE) - private String eventType; - - @XmlElement(name = EL_DATA) - private DataWrapper data; - - @XmlElement(name = EL_META_DATA) - private DataWrapper meta; - - /** - * Default constructor for JAXB. - */ - protected EscEvent() { - super(); - } - - /** - * Constructor with mandatory data. - * - * @param eventId - * Unique event identifier. - * @param eventType - * Unique type name of the event. - * @param data - * The data. - */ - public EscEvent(@NotNull final UUID eventId, @NotNull final String eventType, @NotNull final DataWrapper data) { - this(eventId, eventType, data, null); - } - - /** - * Constructor with all data. - * - * @param eventId - * Unique event identifier. - * @param eventType - * Unique type name of the event. - * @param data - * The data. - * @param meta - * The meta data if available. - */ - public EscEvent(@NotNull final UUID eventId, @NotNull final String eventType, @NotNull final DataWrapper data, - @Nullable final DataWrapper meta) { - super(); - Contract.requireArgNotNull("eventId", eventId); - Contract.requireArgNotNull("eventType", eventType); - Contract.requireArgNotNull("data", data); - this.eventId = eventId.toString(); - this.eventType = eventType; - this.data = data; - this.meta = meta; - } - - /** - * Returns the unique event identifier. - * - * @return Event ID. - */ - public final String getEventId() { - return eventId; - } - - /** - * Returns the unique type name of the event. - * - * @return Event type. - */ - public final String getEventType() { - return eventType; - } - - /** - * Returns the data. - * - * @return Data. - */ - public final DataWrapper getData() { - return data; - } - - /** - * Returns the meta data. - * - * @return Meta data. - */ - public final DataWrapper getMeta() { - return meta; - } - - @Override - public final JsonObject toJson() { - return Json.createObjectBuilder().add(EL_EVENT_ID, eventId).add(EL_EVENT_TYPE, eventType).add(EL_DATA, data.toJson()) - .add(EL_META_DATA, meta.toJson()).build(); - } - - /** - * Creates in instance from the given JSON object. - * - * @param jsonObj - * Object to read values from. - * - * @return New instance. - */ - public static EscEvent create(final JsonObject jsonObj) { - final String eventId = jsonObj.getString(EL_EVENT_ID); - final String eventType = jsonObj.getString(EL_EVENT_TYPE); - final JsonObject jsonData = jsonObj.getJsonObject(EL_DATA); - final JsonObject jsonMeta = jsonObj.getJsonObject(EL_META_DATA); - return new EscEvent(UUID.fromString(eventId), eventType, new DataWrapper(jsonData), new DataWrapper(jsonMeta)); - } - - /** - * Serializes and deserializes a {@link EscEvent} object as JSON. The content type for serialization is always "application/json". - */ - public static class EscEventJsonDeSerializer implements SerDeserializer { - - private JsonDeSerializer jsonDeSer; - - /** - * Constructor with UTF-8 encoding. - */ - public EscEventJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public EscEventJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final EscEvent unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonObject jsonObj = jsonDeSer.unmarshal(data, type, mimeType); - return EscEvent.create(jsonObj); - } - - } - - /** - * Adapter to use for JSON-B. - */ - public static final class JsonbDeSer implements JsonbSerializer, JsonbDeserializer, DeserializerRegistryRequired { - - private DeserializerRegistry registry; - - @Override - public EscEvent deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { - final EscEvent escEvent = new EscEvent(); - JsonObject content = null; - while (parser.hasNext()) { - final JsonParser.Event event = parser.next(); - if (event == JsonParser.Event.KEY_NAME) { - final String field = parser.getString(); - switch (field) { - case EL_EVENT_ID: - escEvent.eventId = ctx.deserialize(String.class, parser); - break; - case EL_EVENT_TYPE: - escEvent.eventType = ctx.deserialize(String.class, parser); - break; - case EL_META_DATA: - parser.next(); // Skip key and deserialize object - escEvent.meta = new DataWrapper(ctx.deserialize(EscMeta.class, parser)); - break; - case EL_DATA: - parser.next(); // Skip key and deserialize object - content = ctx.deserialize(JsonObject.class, parser); - break; - default: - // ignore - break; - } - } - } - - // Handle data at the end, because meta data is only safely available at the end of the process - if (content == null) { - throw new IllegalStateException("Expected content to be set, but was never processed during parse process"); - } - if (content.containsKey(Base64Data.EL_ROOT_NAME)) { - escEvent.data = new DataWrapper(new Base64Data(content.getString(Base64Data.EL_ROOT_NAME))); - } else { - if (!(escEvent.meta.getObj() instanceof EscMeta)) { - throw new IllegalStateException("Expected 'meta.object' to be of type 'EscMeta', but was: " + escEvent.meta.getObj()); - } - final EscMeta escMeta = (EscMeta) escEvent.meta.getObj(); - final Deserializer deserializer = registry.getDeserializer(new SerializedDataType(escEvent.eventType), - escMeta.getDataContentType()); - final Object obj = deserializer.unmarshal(content, new SerializedDataType(escEvent.eventType), - escMeta.getDataContentType()); - escEvent.data = new DataWrapper(obj); - } - - return escEvent; - } - - @Override - public void serialize(EscEvent obj, JsonGenerator generator, SerializationContext ctx) { - generator.writeStartObject(); - if (obj != null) { - generator.write(EL_EVENT_ID, obj.eventId); - generator.write(EL_EVENT_TYPE, obj.eventType); - if (obj.getData().getObj() instanceof Base64Data) { - final Base64Data base64Data = (Base64Data) obj.getData().getObj(); - generator.writeStartObject(EL_DATA); - generator.write(Base64Data.EL_ROOT_NAME, base64Data.getEncoded()); - generator.writeEnd(); - } else { - ctx.serialize(EL_DATA, obj.getData().getObj(), generator); - } - ctx.serialize(EL_META_DATA, obj.getMeta().getObj(), generator); - } - generator.writeEnd(); - } - - @Override - public void setRegistry(final DeserializerRegistry registry) { - this.registry = registry; - - } - - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/EscEvents.java b/spi/src/main/java/org/fuin/esc/spi/EscEvents.java deleted file mode 100644 index 6db7917c..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/EscEvents.java +++ /dev/null @@ -1,206 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.json.*; -import jakarta.json.bind.serializer.DeserializationContext; -import jakarta.json.bind.serializer.JsonbDeserializer; -import jakarta.json.bind.serializer.JsonbSerializer; -import jakarta.json.bind.serializer.SerializationContext; -import jakarta.json.stream.JsonGenerator; -import jakarta.json.stream.JsonParser; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.fuin.esc.api.*; -import org.fuin.objects4j.common.Contract; - -import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * A list of events. - */ -@HasSerializedDataTypeConstant -@XmlRootElement(name = EscEvents.EL_ROOT_NAME) -public final class EscEvents implements ToJsonCapable { - - /** Unique root element name of the type. */ - protected static final String EL_ROOT_NAME = "Events"; - - private static final String EL_EVENT = "Event"; - - /** Unique name of the type. */ - public static final TypeName TYPE = new TypeName(EL_ROOT_NAME); - - /** Unique name of the serialized type. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - @XmlElement(name = EL_EVENT) - private List list; - - /** - * Default constructor for JAXB. - */ - protected EscEvents() { - super(); - } - - /** - * Constructor with array. - * - * @param events - * Event array. - */ - public EscEvents(@NotNull final EscEvent... events) { - this(Arrays.asList(events)); - } - - /** - * Constructor with list. - * - * @param events - * Event list. - */ - public EscEvents(@NotNull final List events) { - super(); - Contract.requireArgNotNull("events", events); - this.list = events; - } - - /** - * Returns an immutable event list. - * - * @return Unmodifiable list of events. - */ - public final List getList() { - return Collections.unmodifiableList(list); - } - - @Override - public final JsonArray toJson() { - final JsonArrayBuilder builder = Json.createArrayBuilder(); - for (final EscEvent event : list) { - builder.add(event.toJson()); - } - return builder.build(); - } - - /** - * Creates in instance from the given JSON array. - * - * @param jsonArray - * Array to read values from. - * - * @return New instance. - */ - public static EscEvents create(final JsonArray jsonArray) { - final List events = new ArrayList<>(); - for (final JsonValue jsonValue : jsonArray) { - if (jsonValue.getValueType() != JsonValue.ValueType.OBJECT) { - throw new IllegalArgumentException( - "All elements in the JSON array must be an JsonObject, but was: " + jsonValue.getValueType()); - } - events.add(EscEvent.create((JsonObject) jsonValue)); - } - return new EscEvents(events); - } - - /** - * Serializes and deserializes a {@link EscEvents} object as JSON. The content type for serialization is always "application/json". - */ - public static class EscEventsJsonDeSerializer implements SerDeserializer { - - private JsonDeSerializer jsonDeSer; - - /** - * Constructor with UTF-8 encoding. - */ - public EscEventsJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public EscEventsJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final EscEvents unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonArray jsonArray = jsonDeSer.unmarshal(data, type, mimeType); - return EscEvents.create(jsonArray); - } - - } - - /** - * Adapter to use for JSON-B. - */ - public static final class JsonbDeSer implements JsonbSerializer, JsonbDeserializer { - - @Override - public EscEvents deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { - final List events = new ArrayList<>(); - while (parser.hasNext()) { - final JsonParser.Event event = parser.next(); - if (event == JsonParser.Event.START_OBJECT) { - events.add(ctx.deserialize(EscEvent.class, parser)); - } - } - return new EscEvents(events); - } - - @Override - public void serialize(EscEvents obj, JsonGenerator generator, SerializationContext ctx) { - if (obj == null) { - return; - } - generator.writeStartArray(); - if (obj.list != null) { - for (final EscEvent event : obj.list) { - ctx.serialize(event, generator); - } - } - generator.writeEnd(); - } - - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/EscMeta.java b/spi/src/main/java/org/fuin/esc/spi/EscMeta.java deleted file mode 100644 index fc3ba014..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/EscMeta.java +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.annotation.Nullable; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import jakarta.json.JsonObjectBuilder; -import jakarta.json.bind.serializer.DeserializationContext; -import jakarta.json.bind.serializer.JsonbDeserializer; -import jakarta.json.bind.serializer.JsonbSerializer; -import jakarta.json.bind.serializer.SerializationContext; -import jakarta.json.stream.JsonGenerator; -import jakarta.json.stream.JsonParser; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlAnyElement; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import jakarta.xml.bind.annotation.XmlTransient; -import org.fuin.esc.api.*; -import org.fuin.objects4j.common.Contract; - -import java.lang.reflect.Type; - -/** - * A structure that contains the user's meta data and the system's meta information. - */ -@HasSerializedDataTypeConstant -@XmlRootElement(name = EscMeta.EL_ROOT_NAME) -public final class EscMeta implements ToJsonCapable { - - /** Unique XML/JSON root element name of the type. */ - public static final String EL_ROOT_NAME = "esc-meta"; - - /** Unique name of the type. */ - public static final TypeName TYPE = new TypeName(EscMeta.class.getSimpleName()); - - /** Unique name of the serialized type. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - private static final String EL_DATA_TYPE = "data-type"; - - private static final String EL_DATA_CONTENT_TYPE = "data-content-type"; - - private static final String EL_META_TYPE = "meta-type"; - - private static final String EL_META_CONTENT_TYPE = "meta-content-type"; - - @XmlElement(name = EL_DATA_TYPE) - private String dataType; - - @XmlElement(name = EL_DATA_CONTENT_TYPE) - private String dataContentTypeStr; - - @XmlElement(name = EL_META_TYPE) - private String metaType; - - @XmlElement(name = EL_META_CONTENT_TYPE) - private String metaContentTypeStr; - - @XmlAnyElement(lax = true) - private Object meta; - - @XmlTransient - private EnhancedMimeType dataContentType; - - @XmlTransient - private EnhancedMimeType metaContentType; - - /** - * Default constructor for JAXB. - */ - protected EscMeta() { - super(); - } - - /** - * Constructor with all mandatory data. - * - * @param dataType - * Type of the data. - * @param dataContentType - * Content type of the data. - */ - public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType) { - this(dataType, dataContentType, null, null, null); - } - - /** - * Constructor with all data. - * - * @param dataType - * Type of the data. - * @param dataContentType - * Type of the data. - * @param metaType - * Unique name of the meta data type if available. - * @param metaContentType - * Type of the meta data if meta data is available. - * @param meta - * Meta data object if available. - */ - public EscMeta(@NotNull final String dataType, @NotNull final EnhancedMimeType dataContentType, @Nullable final String metaType, - @Nullable final EnhancedMimeType metaContentType, @Nullable final Object meta) { - super(); - Contract.requireArgNotNull("dataType", dataType); - Contract.requireArgNotNull("dataContentType", dataContentType); - - this.dataType = dataType; - this.dataContentType = dataContentType; - this.dataContentTypeStr = dataContentType.toString(); - this.metaType = metaType; - this.metaContentType = metaContentType; - if (metaContentType != null) { - this.metaContentTypeStr = metaContentType.toString(); - } - this.meta = meta; - } - - /** - * Returns the unique name of the data type. - * - * @return Data type. - */ - @Nullable - public final String getDataType() { - return dataType; - } - - /** - * Returns the type of the data. - * - * @return Data type. - */ - @NotNull - public final EnhancedMimeType getDataContentType() { - if (dataContentType == null) { - dataContentType = EnhancedMimeType.create(dataContentTypeStr); - } - return dataContentType; - } - - /** - * Returns the unique name of the meta data type if available. - * - * @return Meta type. - */ - @Nullable - public final String getMetaType() { - return metaType; - } - - /** - * Returns the type of the meta data if meta data is available. - * - * @return Meta type. - */ - @Nullable - public final EnhancedMimeType getMetaContentType() { - if ((metaContentType == null) && (metaContentTypeStr != null)) { - metaContentType = EnhancedMimeType.create(metaContentTypeStr); - } - return metaContentType; - } - - /** - * Returns the meta data object. - * - * @return Meta data object. - */ - @NotNull - public final Object getMeta() { - return meta; - } - - /** - * Converts the object into a JSON object. - * - * @return JSON object. - */ - public JsonObject toJson() { - final JsonObjectBuilder builder = Json.createObjectBuilder(); - builder.add(EL_DATA_TYPE, dataType); - builder.add(EL_DATA_CONTENT_TYPE, dataContentTypeStr); - if (meta == null) { - return builder.build(); - } - builder.add(EL_META_TYPE, metaType); - builder.add(EL_META_CONTENT_TYPE, metaContentTypeStr); - if (meta instanceof JsonObject) { - final JsonObject jo = (JsonObject) meta; - return builder.add(metaType, jo).build(); - } - if (meta instanceof ToJsonCapable) { - final ToJsonCapable tjc = (ToJsonCapable) meta; - return builder.add(metaType, tjc.toJson()).build(); - } - if (meta instanceof Base64Data) { - final Base64Data base64data = (Base64Data) meta; - return builder.add(metaType, base64data.getEncoded()).build(); - } - throw new IllegalStateException("Unknown meta object type: " + meta.getClass()); - } - - /** - * Creates in instance from the given JSON object. - * - * @param jsonObj - * Object to read values from. - * - * @return New instance. - */ - public static EscMeta create(final JsonObject jsonObj) { - final String dataType = jsonObj.getString(EL_DATA_TYPE); - final EnhancedMimeType dataContentType = EnhancedMimeType.create(jsonObj.getString(EL_DATA_CONTENT_TYPE)); - if (!jsonObj.containsKey(EL_META_TYPE)) { - return new EscMeta(jsonObj.getString(EL_DATA_TYPE), dataContentType); - } - final String metaType = jsonObj.getString(EL_META_TYPE); - final EnhancedMimeType metaContentType = EnhancedMimeType.create(jsonObj.getString(EL_META_CONTENT_TYPE)); - final String transferEncoding = metaContentType.getParameter("transfer-encoding"); - if (transferEncoding == null) { - return new EscMeta(dataType, dataContentType, metaType, metaContentType, jsonObj.get(metaType)); - } - final JsonObject base64obj = jsonObj.getJsonObject(metaType); - return new EscMeta(dataType, dataContentType, metaType, metaContentType, - new Base64Data(base64obj.getString(Base64Data.EL_ROOT_NAME))); - } - - /** - * Adapter to use for JSON-B. - */ - public static final class JsonbDeSer - implements JsonbSerializer, JsonbDeserializer, SerializedDataTypeRegistryRequired { - - private SerializedDataTypeRegistry registry; - - @Override - public EscMeta deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - final EscMeta escMeta = new EscMeta(); - while (parser.hasNext()) { - final JsonParser.Event event = parser.next(); - if (event == JsonParser.Event.KEY_NAME) { - final String field = parser.getString(); - switch (field) { - case EL_DATA_TYPE: - escMeta.dataType = ctx.deserialize(String.class, parser); - break; - case EL_DATA_CONTENT_TYPE: - escMeta.dataContentType = EnhancedMimeType.create(ctx.deserialize(String.class, parser)); - escMeta.dataContentTypeStr = escMeta.dataContentType.toString(); - break; - case EL_META_TYPE: - escMeta.metaType = ctx.deserialize(String.class, parser); - break; - case EL_META_CONTENT_TYPE: - escMeta.metaContentType = EnhancedMimeType.create(ctx.deserialize(String.class, parser)); - if (escMeta.metaContentType != null) { - escMeta.metaContentTypeStr = escMeta.metaContentType.toString(); - } - break; - default: - // meta - if (field.equals("Base64")) { - escMeta.meta = new Base64Data(ctx.deserialize(String.class, parser)); - } else { - final Class clasz = registry.findClass(new SerializedDataType(escMeta.metaType)); - escMeta.meta = ctx.deserialize(clasz, parser); - } - break; - } - } - } - return escMeta; - } - - @Override - public void serialize(EscMeta obj, JsonGenerator generator, SerializationContext ctx) { - - generator.writeStartObject(); - generator.write(EL_DATA_TYPE, obj.dataType); - generator.write(EL_DATA_CONTENT_TYPE, obj.dataContentTypeStr); - if (obj.meta != null) { - generator.write(EL_META_TYPE, obj.metaType); - generator.write(EL_META_CONTENT_TYPE, obj.metaContentTypeStr); - if (obj.meta instanceof Base64Data) { - final Base64Data base64data = (Base64Data) obj.meta; - generator.write(Base64Data.EL_ROOT_NAME, base64data.getEncoded()); - } else { - ctx.serialize(obj.metaType, obj.meta, generator); - } - } - generator.writeEnd(); - - } - - @Override - public void setRegistry(final SerializedDataTypeRegistry registry) { - this.registry = registry; - } - - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/EscMetaJsonDeSerializer.java b/spi/src/main/java/org/fuin/esc/spi/EscMetaJsonDeSerializer.java deleted file mode 100644 index a8aa50a3..00000000 --- a/spi/src/main/java/org/fuin/esc/spi/EscMetaJsonDeSerializer.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.json.JsonObject; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.JsonDeSerializer; -import org.fuin.esc.api.SerDeserializer; -import org.fuin.esc.api.SerializedDataType; - -import java.nio.charset.Charset; - -/** - * Serializes and deserializes a {@link EscMeta} object as JSON. The content - * type for serialization is always "application/json". - */ -public class EscMetaJsonDeSerializer implements SerDeserializer { - - private JsonDeSerializer jsonDeSer; - - /** - * Constructor with UTF-8 encoding. - */ - public EscMetaJsonDeSerializer() { - super(); - this.jsonDeSer = new JsonDeSerializer(); - } - - /** - * Constructor with type and encoding. - * - * @param encoding - * Default encoding to use. - */ - public EscMetaJsonDeSerializer(final Charset encoding) { - super(); - this.jsonDeSer = new JsonDeSerializer(encoding); - } - - @Override - public final EnhancedMimeType getMimeType() { - return jsonDeSer.getMimeType(); - } - - @Override - public final byte[] marshal(final T obj, final SerializedDataType type) { - return jsonDeSer.marshal(obj, type); - } - - @SuppressWarnings("unchecked") - @Override - public final EscMeta unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { - final JsonObject jsonObj = jsonDeSer.unmarshal(data, type, mimeType); - return EscMeta.create(jsonObj); - } - -} diff --git a/spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java b/spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java index 4990853a..849c4327 100644 --- a/spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java +++ b/spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java @@ -1,38 +1,35 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.spi; import jakarta.annotation.Nullable; -import jakarta.json.bind.serializer.JsonbDeserializer; -import jakarta.json.bind.serializer.JsonbSerializer; import jakarta.validation.constraints.NotNull; -import org.fuin.esc.api.*; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.Deserializer; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.IEscMeta; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.Serializer; +import org.fuin.esc.api.SerializerRegistry; import org.fuin.objects4j.common.Contract; -import org.w3c.dom.Node; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.StringWriter; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -50,19 +47,19 @@ private EscSpiUtils() { /** * Tries to find a serializer for the given type of object and converts it into a storable data block. - * + * * @param registry * Registry with known serializers. * @param type * Type of event. * @param data * Event of the given type. - * + * * @return Event ready to persist or null if the given data was null. */ @Nullable public static SerializedData serialize(@NotNull final SerializerRegistry registry, @NotNull final SerializedDataType type, - @Nullable final Object data) { + @Nullable final Object data) { if (data == null) { return null; @@ -77,14 +74,14 @@ public static SerializedData serialize(@NotNull final SerializerRegistry registr /** * Tries to find a deserializer for the given data block. - * + * * @param registry * Registry with known deserializers. * @param data * Persisted data. - * + * * @return Unmarshalled event. - * + * * @param * Expected type of event. */ @@ -99,12 +96,12 @@ public static T deserialize(@NotNull final DeserializerRegistry registry, @N /** * Returns the mime types shared by all events in the list. - * + * * @param registry * Registry used to peek the mime type used to serialize the event. * @param commonEvents * List to test. - * + * * @return Mime type if all events share the same type or null if there are events with different mime types. */ public static EnhancedMimeType mimeType(@NotNull final SerializerRegistry registry, @NotNull final List commonEvents) { @@ -128,16 +125,17 @@ public static EnhancedMimeType mimeType(@NotNull final SerializerRegistry regist /** * Returns the array as a list in a null-safe way. - * + * * @param array * Array to convert into a list. - * + * * @return Array list. - * + * * @param * Type of the array and list. */ - public static List asList(final T[] array) { + @Nullable + public static List asList(@Nullable final T[] array) { if (array == null) { return null; } @@ -146,22 +144,22 @@ public static List asList(final T[] array) { /** * Tests if both lists contain the same events. - * + * * @param eventsA * First event list. * @param eventsB * Second event list. - * + * * @return TRUE if both lists have the same size and all event identifiers are equal. */ public static boolean eventsEqual(@Nullable final List eventsA, @Nullable final List eventsB) { if ((eventsA == null) && (eventsB == null)) { return true; } - if ((eventsA == null) && (eventsB != null)) { + if (eventsA == null) { return false; } - if ((eventsA != null) && (eventsB == null)) { + if (eventsB == null) { return false; } if (eventsA.size() != eventsB.size()) { @@ -183,18 +181,22 @@ public static boolean eventsEqual(@Nullable final List eventsA, @Nu /** * Create meta information for a given a {@link CommonEvent}. - * + * * @param registry * Registry with serializers. + * @param baseTypeFactory + * Helper class to create required implementations. * @param targetContentType * Content type that will later be used to serialize the created result. * @param commonEvent * Event to create meta information for. - * + * * @return New meta instance. */ - public static EscMeta createEscMeta(@NotNull final SerializerRegistry registry, @NotNull final EnhancedMimeType targetContentType, - @Nullable final CommonEvent commonEvent) { + public static IEscMeta createEscMeta(@NotNull final SerializerRegistry registry, + @NotNull final IBaseTypeFactory baseTypeFactory, + @NotNull final EnhancedMimeType targetContentType, + @Nullable final CommonEvent commonEvent) { Contract.requireArgNotNull("registry", registry); Contract.requireArgNotNull("targetContentType", targetContentType); @@ -208,19 +210,19 @@ public static EscMeta createEscMeta(@NotNull final SerializerRegistry registry, final EnhancedMimeType dataContentType = contentType(dataSerializer.getMimeType(), targetContentType); if (commonEvent.getMeta() == null) { - return new EscMeta(dataType, dataContentType); + return baseTypeFactory.createEscMeta(dataType, dataContentType, null, null, null); } final String metaType = commonEvent.getMetaType().asBaseType(); final SerializedDataType serDataType = new SerializedDataType(metaType); final Serializer metaSerializer = registry.getSerializer(serDataType); if (metaSerializer.getMimeType().matchEncoding(targetContentType)) { - return new EscMeta(dataType, dataContentType, metaType, metaSerializer.getMimeType(), commonEvent.getMeta()); + return baseTypeFactory.createEscMeta(dataType, dataContentType, metaType, metaSerializer.getMimeType(), commonEvent.getMeta()); } final byte[] serMeta = metaSerializer.marshal(commonEvent.getMeta(), serDataType); final EnhancedMimeType metaContentType = contentType(metaSerializer.getMimeType(), targetContentType); - return new EscMeta(dataType, dataContentType, metaType, metaContentType, new Base64Data(serMeta)); + return baseTypeFactory.createEscMeta(dataType, dataContentType, metaType, metaContentType, baseTypeFactory.createBase64Data(serMeta)); } @@ -228,101 +230,7 @@ private static EnhancedMimeType contentType(final EnhancedMimeType sourceContent if (sourceContentType.matchEncoding(targetContentType)) { return sourceContentType; } - return EnhancedMimeType.create(sourceContentType.toString() + "; transfer-encoding=base64"); - } - - /** - * Render a node as string. - * - * @param node - * Node to render. - * - * @return XML. - */ - public static String nodeToString(final Node node) { - try { - final Transformer t = TransformerFactory.newInstance().newTransformer(); - t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - final StringWriter sw = new StringWriter(); - t.transform(new DOMSource(node), new StreamResult(sw)); - return sw.toString(); - } catch (final TransformerException ex) { - throw new RuntimeException("Failed to render node", ex); - } - } - - /** - * Creates all available JSON-B serializers necessary for the ESC implementation. - * - * @return New array with serializers. - */ - public static JsonbSerializer[] createEscJsonbSerializers() { - return new JsonbSerializer[] { new EscEvents.JsonbDeSer(), new EscEvent.JsonbDeSer(), new EscMeta.JsonbDeSer() }; - } - - /** - * Creates all available JSON-B serializers necessary for the ESC implementation. - * - * @return New array with serializers. - */ - public static JsonbSerializer[] joinJsonbSerializers(final JsonbSerializer[] serializersA, - final JsonbSerializer... serializersB) { - return joinJsonbSerializerArrays(serializersA, serializersB); - } - - /** - * Creates all available JSON-B serializers necessary for the ESC implementation. - * - * @return New array with serializers. - */ - public static JsonbSerializer[] joinJsonbSerializerArrays(final JsonbSerializer[]... serializerArrays) { - final List> all = joinArrays(serializerArrays); - return all.toArray(new JsonbSerializer[all.size()]); - } - - /** - * Creates all available JSON-B deserializers necessary for the ESC implementation. - * - * @return New array with deserializers. - */ - public static JsonbDeserializer[] createEscJsonbDeserializers() { - return new JsonbDeserializer[] { new EscEvents.JsonbDeSer(), new EscEvent.JsonbDeSer(), new EscMeta.JsonbDeSer() }; - } - - /** - * Creates all available JSON-B deserializers necessary for the ESC implementation. - * - * @return New array with deserializers. - */ - public static JsonbDeserializer[] joinJsonbDeserializers(final JsonbDeserializer[] deserializersA, - final JsonbDeserializer... deserializersB) { - return joinJsonbDeserializerArrays(deserializersA, deserializersB); - } - - /** - * Creates all available JSON-B deserializers necessary for the ESC implementation. - * - * @return New array with deserializers. - */ - public static JsonbDeserializer[] joinJsonbDeserializerArrays(final JsonbDeserializer[]... deserializerArrays) { - final List> all = joinArrays(deserializerArrays); - return all.toArray(new JsonbDeserializer[all.size()]); - } - - /** - * Creates all available JSON-B serializers necessary for the ESC implementation. - * - * @return New array with serializers. - */ - @SafeVarargs - static List joinArrays(final T[]... arrays) { - final List all = new ArrayList<>(); - for (final T[] array : arrays) { - for (int j = 0; j < array.length; j++) { - all.add(array[j]); - } - } - return all; + return EnhancedMimeType.create(sourceContentType + "; transfer-encoding=base64"); } } diff --git a/spi/src/main/java/org/fuin/esc/spi/ProjectionJavaScriptBuilder.java b/spi/src/main/java/org/fuin/esc/spi/ProjectionJavaScriptBuilder.java index a00889e7..4ce3297f 100644 --- a/spi/src/main/java/org/fuin/esc/spi/ProjectionJavaScriptBuilder.java +++ b/spi/src/main/java/org/fuin/esc/spi/ProjectionJavaScriptBuilder.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -37,8 +37,8 @@ public final class ProjectionJavaScriptBuilder { private StringBuilder sb; /** - * Constructor for building an tenant based projection. - * + * Constructor for building a tenant based projection. + * * @param tenantStreamId * Tenant ID to use as category and delegate name as projection name. */ @@ -54,7 +54,7 @@ public ProjectionJavaScriptBuilder(@NotNull final TenantStreamId tenantStreamId) /** * Constructor for building an 'all' based projection. - * + * * @param projectionId * Projection ID to use as projection name. */ @@ -66,7 +66,7 @@ public ProjectionJavaScriptBuilder(@NotNull final StreamId projectionId) { /** * Constructor for building an 'all' based projection. - * + * * @param projection * Projection name. */ @@ -78,7 +78,7 @@ public ProjectionJavaScriptBuilder(@NotNull final String projection) { /** * Constructor for building a 'category' based projection. - * + * * @param projectionId * Projection. * @param categoryId @@ -93,7 +93,7 @@ public ProjectionJavaScriptBuilder(@NotNull final StreamId projectionId, @NotNul /** * Constructor for building a 'category' based projection. - * + * * @param projection * Projection name. * @param category @@ -122,13 +122,13 @@ private void initCategory(final String projection, final String category) { /** * Adds another type to select. - * + * * @param eventType * Unique event type to select from the category of streams. - * + * * @return this. */ - public final ProjectionJavaScriptBuilder type(final String eventType) { + public ProjectionJavaScriptBuilder type(final String eventType) { if (count > 0) { sb.append(","); } @@ -139,25 +139,25 @@ public final ProjectionJavaScriptBuilder type(final String eventType) { /** * Adds another type to select. Convenience method to add a {@link TypeName} instead of a string. - * + * * @param eventType * Unique event type to select from the category of streams. - * + * * @return this. */ - public final ProjectionJavaScriptBuilder type(final TypeName eventType) { + public ProjectionJavaScriptBuilder type(final TypeName eventType) { return type(eventType.asBaseType()); } /** * Adds more types to select. Convenience method to add multiple {@link TypeName} instead of strings. - * + * * @param eventTypes * Unique event type list to select from the category of streams. - * + * * @return this. */ - public final ProjectionJavaScriptBuilder types(final List eventTypes) { + public ProjectionJavaScriptBuilder types(final List eventTypes) { for (final TypeName type : eventTypes) { type(type.asBaseType()); } @@ -166,10 +166,10 @@ public final ProjectionJavaScriptBuilder types(final List eventTypes) /** * Builds the JavaScript for the projection. - * + * * @return Projection script. */ - public final String build() { + public String build() { if (count == 0) { throw new IllegalStateException("No types were added. Use 'type(String)' to add at least one event."); } diff --git a/spi/src/main/java/org/fuin/esc/spi/SerializedData.java b/spi/src/main/java/org/fuin/esc/spi/SerializedData.java index 4e511e88..53d0a749 100644 --- a/spi/src/main/java/org/fuin/esc/spi/SerializedData.java +++ b/spi/src/main/java/org/fuin/esc/spi/SerializedData.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -21,9 +21,12 @@ import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.SerializedDataType; import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; + import org.fuin.objects4j.common.ValueObject; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; @@ -33,6 +36,7 @@ @Immutable public class SerializedData implements ValueObject, Serializable { + @Serial private static final long serialVersionUID = 1000L; /** Unique type of the data. */ @@ -56,7 +60,7 @@ protected SerializedData() { //NOSONAR Ignore uninitialized fields /** * Creates a data object. - * + * * @param type * Unique identifier for the type of data. * @param mimeType @@ -79,7 +83,7 @@ public SerializedData(@NotNull final SerializedDataType type, /** * Returns the unique identifier for the type of data. - * + * * @return Unique and never changing type name. */ @NotNull @@ -89,7 +93,7 @@ public final SerializedDataType getType() { /** * Returns the Internet Media Type that classifies the data. - * + * * @return Mime type. */ @NotNull @@ -99,7 +103,7 @@ public final EnhancedMimeType getMimeType() { /** * Returns the raw data block. - * + * * @return Raw data. */ @NotNull @@ -107,7 +111,6 @@ public final byte[] getRaw() { return raw; } - // CHECKSTYLE:OFF Generated code @Override public final int hashCode() { final int prime = 31; @@ -136,13 +139,9 @@ public final boolean equals(Object obj) { if (!Arrays.equals(raw, other.raw)) return false; if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; + return other.type == null; + } else return type.equals(other.type); } - // CHECKSTYLE:ON } diff --git a/spi/src/main/java/org/fuin/esc/spi/TenantStreamId.java b/spi/src/main/java/org/fuin/esc/spi/TenantStreamId.java index 65b4fe6f..75807d7d 100644 --- a/spi/src/main/java/org/fuin/esc/spi/TenantStreamId.java +++ b/spi/src/main/java/org/fuin/esc/spi/TenantStreamId.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,6 +24,7 @@ import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.core.KeyValue; +import java.io.Serial; import java.util.List; /** @@ -31,6 +32,7 @@ */ public final class TenantStreamId implements StreamId { + @Serial private static final long serialVersionUID = 1000L; private final TenantId tenantId; @@ -81,7 +83,7 @@ public String asString() { /** * Returns the tenant identifier. - * + * * @return Tenant identifier. */ @Nullable @@ -91,7 +93,7 @@ public TenantId getTenantId() { /** * Returns the underlying stream identifier. - * + * * @return Stream identifier. */ @NotNull @@ -100,12 +102,12 @@ public StreamId getDelegate() { } @Override - public final int hashCode() { + public int hashCode() { return asString().hashCode(); } @Override - public final boolean equals(final Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -120,7 +122,7 @@ public final boolean equals(final Object obj) { } @Override - public final String toString() { + public String toString() { return asString(); } diff --git a/spi/src/main/java/org/fuin/esc/spi/TextDeSerializer.java b/spi/src/main/java/org/fuin/esc/spi/TextDeSerializer.java index 0b744abf..900e8120 100644 --- a/spi/src/main/java/org/fuin/esc/spi/TextDeSerializer.java +++ b/spi/src/main/java/org/fuin/esc/spi/TextDeSerializer.java @@ -1,27 +1,29 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.spi; +import jakarta.validation.constraints.NotNull; import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.SerDeserializer; import org.fuin.esc.api.SerializedDataType; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * Serializes and deserializes a String object. The content type for serialization is always "text/plain". @@ -34,38 +36,37 @@ public final class TextDeSerializer implements SerDeserializer { * Constructor with UTF-8 encoding. */ public TextDeSerializer() { - this(Charset.forName("utf-8")); + this(StandardCharsets.UTF_8); } /** * Constructor with type and encoding. - * + * * @param encoding * Default encoding to use. */ - public TextDeSerializer(final Charset encoding) { + public TextDeSerializer(@NotNull final Charset encoding) { super(); this.mimeType = EnhancedMimeType.create("text", "plain", encoding); } @Override - public final EnhancedMimeType getMimeType() { + public EnhancedMimeType getMimeType() { return mimeType; } @Override - public final byte[] marshal(final Object obj, final SerializedDataType type) { - if (!(obj instanceof String)) { + public byte[] marshal(@NotNull final Object obj, @NotNull final SerializedDataType type) { + if (!(obj instanceof String str)) { throw new IllegalArgumentException("Can only handle instances of type 'String', but not: " + obj.getClass()); } - final String str = (String) obj; return str.getBytes(mimeType.getEncoding()); } @SuppressWarnings("unchecked") @Override - public final T unmarshal(final Object data, final SerializedDataType type, final EnhancedMimeType mimeType) { + public T unmarshal(@NotNull final Object data, @NotNull final SerializedDataType type, @NotNull final EnhancedMimeType mimeType) { if (data instanceof byte[]) { return (T) new String((byte[]) data, mimeType.getEncoding()); diff --git a/spi/src/test/java/org/fuin/esc/spi/ArchitectureTest.java b/spi/src/test/java/org/fuin/esc/spi/ArchitectureTest.java new file mode 100644 index 00000000..5e4e3b8e --- /dev/null +++ b/spi/src/test/java/org/fuin/esc/spi/ArchitectureTest.java @@ -0,0 +1,59 @@ +/** + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + */ +package org.fuin.esc.spi; + +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; +import org.fuin.esc.api.EscApiUtils; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + +@AnalyzeClasses(packagesOf = ArchitectureTest.class, importOptions = ImportOption.DoNotIncludeTests.class) +class ArchitectureTest { + + private static final String API_PACKAGE = EscApiUtils.class.getPackageName(); + + private static final String SPI_PACKAGE = EscSpiUtils.class.getPackageName(); + + private static final String THIS_PACKAGE = ArchitectureTest.class.getPackageName(); + + @ArchTest + static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES; + + @ArchTest + static final ArchRule common_access_only_to_defined_packages = classes() + .that() + .resideInAPackage(THIS_PACKAGE) + .should() + .onlyDependOnClassesThat() + .resideInAnyPackage(THIS_PACKAGE, API_PACKAGE, SPI_PACKAGE, + "java..", + "jakarta.annotation..", + "jakarta.validation..", + "javax.annotation.concurrent..", + "org.fuin.objects4j.common..", + "org.fuin.objects4j.core..", + "org.slf4j.." + ); + + +} + diff --git a/spi/src/test/java/org/fuin/esc/spi/BaseTest.java b/spi/src/test/java/org/fuin/esc/spi/BaseTest.java index 1cd83dcb..d5e96086 100644 --- a/spi/src/test/java/org/fuin/esc/spi/BaseTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/BaseTest.java @@ -1,44 +1,45 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * + * Copyright (C) 2013 Future Invent Informationsmanagement GmbH. All rights + * reserved. + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. + * along with this library. If not, see . */ package org.fuin.esc.spi; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchIgnore; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; -/** - * General tests for all classes. - */ -// CHECKSTYLE:OFF Test code -public class BaseTest { +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static org.fuin.units4j.archunit.AllTopLevelClassesHaveATestCondition.haveACorrespondingClassEndingWith; - @Disabled("Implement with ArchUnit!") - @Test - public final void testCoverage() { - // Make sure all classes have a test - // TODO Implement! - } +@AnalyzeClasses(packagesOf = BaseTest.class) +class BaseTest { - @Disabled("Implement with ArchUnit!") - @Test - public final void testNullability() { - // Make sure all public/protected methods have either @Nullable or @NotNull - // TODO Implement! - } + @ArchTest + static final ArchRule all_classes_should_have_tests = + classes() + .that() + .areTopLevelClasses() + .and().areNotInterfaces() + .and().areNotRecords() + .and().areNotEnums() + .and().doNotHaveModifier(JavaModifier.ABSTRACT) + .and().areNotAnnotatedWith(ArchIgnore.class) + .should(haveACorrespondingClassEndingWith("Test")); } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/EscEventTest.java b/spi/src/test/java/org/fuin/esc/spi/EscEventTest.java deleted file mode 100644 index 77367fd1..00000000 --- a/spi/src/test/java/org/fuin/esc/spi/EscEventTest.java +++ /dev/null @@ -1,309 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.bind.Jsonb; -import org.apache.commons.io.IOUtils; -import org.eclipse.yasson.FieldAccessStrategy; -import org.fuin.esc.api.*; -import org.junit.jupiter.api.Test; -import org.xmlunit.builder.DiffBuilder; -import org.xmlunit.diff.Diff; - -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; -import static org.assertj.core.api.Assertions.assertThat; -import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; -import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; - -/** - * Test for {@link EscEvent} class. - */ -// CHECKSTYLE:OFF Test -public class EscEventTest { - - @Test - public final void testMarshalUnmarshalJaxb() throws Exception { - - // PREPARE - final String expectedXml = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event.xml"), StandardCharsets.UTF_8); - - // TEST - final EscEvent testee = unmarshal(expectedXml, EscEvent.class, EscMeta.class, MyMeta.class, MyEvent.class, Base64Data.class); - - // VERIFY - assertThat(testee).isNotNull(); - assertThat(testee.getEventId()).isEqualTo("68616d90-cf72-4c2a-b913-32bf6e6506ed"); - assertThat(testee.getEventType()).isEqualTo("MyEvent"); - assertThat(testee.getData()).isNotNull(); - assertThat(testee.getData().getObj()).isInstanceOf(MyEvent.class); - assertThat(testee.getMeta()).isNotNull(); - assertThat(testee.getMeta().getObj()).isNotNull(); - assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); - - // TEST - final String xml = marshal(testee, EscEvent.class, EscMeta.class, MyMeta.class, MyEvent.class, Base64Data.class); - - // VERIFY - final Diff documentDiff = DiffBuilder.compare(expectedXml).withTest(xml).ignoreWhitespace().build(); - assertThat(documentDiff.hasDifferences()).describedAs(documentDiff.toString()).isFalse(); - - } - - @Test - public final void testToJson() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event.json"), StandardCharsets.UTF_8); - final UUID eventId = UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"); - final MyEvent myEvent = new MyEvent(UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"), "Hello, JSON!"); - final MyMeta myMeta = new MyMeta("abc"); - - final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1"); - final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1"); - final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, - myMeta); - final DataWrapper dataWrapper = new DataWrapper(myEvent); - final DataWrapper metaWrapper = new DataWrapper(escMeta); - final EscEvent event = new EscEvent(eventId, MyEvent.TYPE.asBaseType(), dataWrapper, metaWrapper); - - // TEST - final StringWriter sw = new StringWriter(); - Json.createWriter(sw).writeObject(event.toJson()); - final String actualJson = sw.toString(); - - // VERIFY - assertThatJson(expectedJson).isEqualTo(actualJson); - - } - - @Test - public void testMarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final UUID eventId = UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"); - final MyEvent myEvent = new MyEvent(UUID.fromString("b2a936ce-d479-414f-b67f-3df4da383d47"), "Hello, JSON!"); - final MyMeta myMeta = new MyMeta("abc"); - - final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/json; version=1; encoding=UTF-8"); - final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/json; version=1; encoding=UTF-8"); - final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, - myMeta); - final DataWrapper dataWrapper = new DataWrapper(myEvent); - final DataWrapper metaWrapper = new DataWrapper(escMeta); - final EscEvent event = new EscEvent(eventId, MyEvent.TYPE.asBaseType(), dataWrapper, metaWrapper); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - jsonbDeSer.init(typeRegistry); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final String currentJson = jsonb.toJson(event); - - // VERIFY - assertThatJson(currentJson).isEqualTo(expectedJson); - - } - - } - - @Test - public final void testUnmarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withDeserializers(EscSpiUtils.createEscJsonbDeserializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - initSerDeserializerRegistry(typeRegistry, jsonbDeSer); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final EscEvent testee = jsonb.fromJson(expectedJson, EscEvent.class); - - // VERIFY - assertThat(testee.getEventId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); - assertThat(testee.getEventType()).isEqualTo("MyEvent"); - assertThat(testee.getData().getObj()).isInstanceOf(MyEvent.class); - final MyEvent myEvent = (MyEvent) testee.getData().getObj(); - assertThat(myEvent.getId()).isEqualTo("b2a936ce-d479-414f-b67f-3df4da383d47"); - assertThat(myEvent.getDescription()).isEqualTo("Hello, JSON!"); - assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); - final EscMeta escMeta = (EscMeta) testee.getMeta().getObj(); - assertThat(escMeta.getDataType()).isEqualTo("MyEvent"); - assertThat(escMeta.getDataContentType()).isEqualTo(EnhancedMimeType.create("application/json; version=1; encoding=UTF-8")); - assertThat(escMeta.getMetaType()).isEqualTo("MyMeta"); - assertThat(escMeta.getMetaContentType()).isEqualTo(EnhancedMimeType.create("application/json; version=1; encoding=UTF-8")); - assertThat(escMeta.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta myMeta = (MyMeta) escMeta.getMeta(); - assertThat(myMeta.getUser()).isEqualTo("abc"); - - } - } - - @Test - public void testMarshalJsonBBase64() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event-base64.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final EscEvent event = createEventBase64(); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withDeserializers(EscSpiUtils.createEscJsonbDeserializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - initSerDeserializerRegistry(typeRegistry, jsonbDeSer); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final String currentJson = jsonb.toJson(event); - - // VERIFY - assertThatJson(currentJson).isEqualTo(expectedJson); - - } - - } - - @Test - public final void testUnmarshalJsonBBase64() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-event-base64.json"), StandardCharsets.UTF_8); - - final EscEvent expectedEvent = createEventBase64(); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyEvent.SER_TYPE, MyEvent.class); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withDeserializers(EscSpiUtils.createEscJsonbDeserializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - initSerDeserializerRegistry(typeRegistry, jsonbDeSer); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final EscEvent testee = jsonb.fromJson(expectedJson, EscEvent.class); - - // VERIFY - assertThat(testee.getEventId()).isEqualTo(expectedEvent.getEventId()); - assertThat(testee.getEventType()).isEqualTo(expectedEvent.getEventType()); - assertThat(testee.getData().getObj()).isInstanceOf(Base64Data.class); - final Base64Data base64Data = (Base64Data) testee.getData().getObj(); - assertThat(base64Data.getEncoded()).isEqualTo(((Base64Data) expectedEvent.getData().getObj()).getEncoded()); - assertThat(testee.getMeta().getObj()).isInstanceOf(EscMeta.class); - final EscMeta actualEscMeta = (EscMeta) testee.getMeta().getObj(); - final EscMeta expectedEscMeta = (EscMeta) expectedEvent.getMeta().getObj(); - assertThat(actualEscMeta.getDataType()).isEqualTo(expectedEscMeta.getDataType()); - assertThat(actualEscMeta.getDataContentType()).isEqualTo(expectedEscMeta.getDataContentType()); - assertThat(actualEscMeta.getMetaType()).isEqualTo(expectedEscMeta.getMetaType()); - assertThat(actualEscMeta.getMetaContentType()).isEqualTo(expectedEscMeta.getMetaContentType()); - assertThat(actualEscMeta.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta actualMyMeta = (MyMeta) actualEscMeta.getMeta(); - final MyMeta expectedMyMeta = (MyMeta) expectedEscMeta.getMeta(); - assertThat(actualMyMeta.getUser()).isEqualTo(expectedMyMeta.getUser()); - - } - - } - - private EscEvent createEventBase64() throws MimeTypeParseException { - final UUID eventId = UUID.fromString("68616d90-cf72-4c2a-b913-32bf6e6506ed"); - final Base64Data data = new Base64Data( - "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9"); - - final MyMeta myMeta = new MyMeta("abc"); - - final Map params = new HashMap<>(); - params.put("transfer-encoding", "base64"); - final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1", params); - final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1"); - final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, - myMeta); - return new EscEvent(eventId, MyEvent.TYPE.asBaseType(), new DataWrapper(data), new DataWrapper(escMeta)); - } - - /** - * Creates a registry that connects the type with the appropriate serializer and de-serializer. - * - * @param typeRegistry - * Type registry (Mapping from type name to class). - * @param jsonbDeSer - * JSON-B serializer/deserializer to use. - */ - private static void initSerDeserializerRegistry(SerializedDataTypeRegistry typeRegistry, - JsonbDeSerializer jsonbDeSer) { - - SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - - // Base types always needed - registry.add(EscEvents.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscEvent.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscMeta.SER_TYPE, "application/json", jsonbDeSer); - - // User defined types - registry.add(MyMeta.SER_TYPE, "application/json", jsonbDeSer); - registry.add(MyEvent.SER_TYPE, "application/json", jsonbDeSer); - - jsonbDeSer.init(typeRegistry, registry, registry); - - } - -} -// CHECKSTYLE:ON diff --git a/spi/src/test/java/org/fuin/esc/spi/EscMetaJsonDeSerializerTest.java b/spi/src/test/java/org/fuin/esc/spi/EscMetaJsonDeSerializerTest.java deleted file mode 100644 index d9ce1648..00000000 --- a/spi/src/test/java/org/fuin/esc/spi/EscMetaJsonDeSerializerTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.activation.MimeTypeParseException; -import jakarta.json.Json; -import jakarta.json.JsonObject; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.SerializedDataType; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests the {@link EscMetaJsonDeSerializer} class. - */ -// CHECKSTYLE:OFF Test -public class EscMetaJsonDeSerializerTest { - - private EscMetaJsonDeSerializer testee; - - @BeforeEach - public void setup() throws MimeTypeParseException { - testee = new EscMetaJsonDeSerializer(); - } - - @AfterEach - public void teardown() { - testee = null; - } - - @Test - public void testMarshalUnmarshal() { - - // PREPARE - final SerializedDataType dataType = new SerializedDataType("MyData"); - EnhancedMimeType dataContentType = EnhancedMimeType.create("application", "xml"); - final SerializedDataType metaType = new SerializedDataType("MyMeta"); - EnhancedMimeType metaContentType = EnhancedMimeType.create("application", "json"); - final JsonObject meta = Json.createObjectBuilder().add("user", "peter").add("ip", "127.0.0.1").build(); - final EscMeta escMeta = new EscMeta(dataType.asBaseType(), dataContentType, metaType.asBaseType(), metaContentType, meta); - - // TEST - final byte[] data = testee.marshal(escMeta, metaType); - final EscMeta copy = testee.unmarshal(data, dataType, EnhancedMimeType.create("application/json; encoding=utf-8")); - - // VERIFY - assertThat(copy.getDataType()).isEqualTo(dataType.asBaseType()); - assertThat(copy.getDataContentType()).isEqualTo(dataContentType); - assertThat(copy.getMetaType()).isEqualTo(metaType.asBaseType()); - assertThat(copy.getMetaContentType()).isEqualTo(metaContentType); - assertThat(copy.getMeta()).isInstanceOf(JsonObject.class); - final JsonObject jsonObj = (JsonObject) copy.getMeta(); - assertThat(jsonObj.keySet()).contains("user", "ip"); - assertThat(jsonObj.getString("user")).isEqualTo("peter"); - assertThat(jsonObj.getString("ip")).isEqualTo("127.0.0.1"); - - } - -} diff --git a/spi/src/test/java/org/fuin/esc/spi/EscMetaTest.java b/spi/src/test/java/org/fuin/esc/spi/EscMetaTest.java deleted file mode 100644 index 3ddf1e43..00000000 --- a/spi/src/test/java/org/fuin/esc/spi/EscMetaTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.json.Json; -import jakarta.json.bind.Jsonb; -import org.apache.commons.io.IOUtils; -import org.eclipse.yasson.FieldAccessStrategy; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.api.JsonbDeSerializer; -import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; -import org.junit.jupiter.api.Test; -import org.xmlunit.builder.DiffBuilder; -import org.xmlunit.diff.Diff; - -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; -import static org.assertj.core.api.Assertions.assertThat; -import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; -import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; - -/** - * Test for {@link EscMeta} class. - */ -// CHECKSTYLE:OFF Test -public class EscMetaTest { - - @Test - public final void testMarshalUnmarshalJaxb() throws Exception { - - // PREPARE - final String expectedXml = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta.xml"), StandardCharsets.UTF_8); - - // TEST - final EscMeta testee = unmarshal(expectedXml, EscMeta.class, MyMeta.class, Base64Data.class); - final String actualXml = marshal(testee, EscMeta.class, MyMeta.class, Base64Data.class); - - // VERIFY - final Diff documentDiff = DiffBuilder.compare(expectedXml).withTest(actualXml).ignoreWhitespace().build(); - assertThat(documentDiff.hasDifferences()).describedAs(documentDiff.toString()).isFalse(); - - } - - @Test - public final void testToJson() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta.json"), StandardCharsets.UTF_8); - - // TEST - final EscMeta testee = EscMeta.create(Json.createReader(new StringReader(expectedJson)).readObject()); - final StringWriter sw = new StringWriter(); - Json.createWriter(sw).writeObject(testee.toJson()); - final String actualJson = sw.toString(); - - // VERIFY - assertThatJson(expectedJson).isEqualTo(actualJson); - - } - - @Test - public final void testMarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta.json"), StandardCharsets.UTF_8); - - final MyMeta myMeta = new MyMeta("abc"); - - final Map params = new HashMap<>(); - params.put("transfer-encoding", "base64"); - final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "xml", Charset.forName("utf-8"), "1", params); - final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1"); - final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, - myMeta); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(EscMeta.SER_TYPE, EscMeta.class); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - jsonbDeSer.init(typeRegistry); - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final String currentJson = jsonb.toJson(escMeta); - - // VERIFY - assertThatJson(currentJson).isEqualTo(expectedJson); - - } - - } - - @Test - public final void testUnmarshalJsonB() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final Map params = new HashMap<>(); - params.put("transfer-encoding", "base64"); - final EnhancedMimeType dataContentType = new EnhancedMimeType("application", "xml", Charset.forName("utf-8"), "1", params); - final EnhancedMimeType metaContentType = new EnhancedMimeType("application", "json", Charset.forName("utf-8"), "1"); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(new EscMeta.JsonbDeSer()) - .withDeserializers(new EscMeta.JsonbDeSer()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - jsonbDeSer.init(typeRegistry); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final EscMeta testee = jsonb.fromJson(expectedJson, EscMeta.class); - - // VERIFY - assertThat(testee.getDataType()).isEqualTo("MyEvent"); - assertThat(testee.getDataContentType()).isEqualTo(dataContentType); - assertThat(testee.getMetaType()).isEqualTo("MyMeta"); - assertThat(testee.getMetaContentType()).isEqualTo(metaContentType); - assertThat(testee.getMeta()).isInstanceOf(MyMeta.class); - final MyMeta myMeta = (MyMeta) testee.getMeta(); - assertThat(myMeta.getUser()).isEqualTo("abc"); - - } - - } - - @Test - public final void testMarshalJsonBBase64() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta-base64.json"), StandardCharsets.UTF_8); - - final Base64Data base64Data = new Base64Data("PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+"); - - final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/xml; encoding=UTF-8"); - final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8"); - final EscMeta escMeta = new EscMeta(MyEvent.SER_TYPE.asBaseType(), dataContentType, MyMeta.SER_TYPE.asBaseType(), metaContentType, - base64Data); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(EscMeta.SER_TYPE, EscMeta.class); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - jsonbDeSer.init(typeRegistry); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final String currentJson = jsonb.toJson(escMeta); - - // VERIFY - assertThatJson(currentJson).isEqualTo(expectedJson); - - } - - } - - @Test - public final void testUnmarshalJsonBBase64() throws Exception { - - // PREPARE - final String expectedJson = IOUtils.toString(this.getClass().getResourceAsStream("/esc-meta-base64.json"), StandardCharsets.UTF_8); - - final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - - final EnhancedMimeType dataContentType = EnhancedMimeType.create("application/xml; encoding=UTF-8"); - final EnhancedMimeType metaContentType = EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8"); - - final JsonbDeSerializer jsonbDeSer = JsonbDeSerializer.builder() - .withSerializers(new EscMeta.JsonbDeSer()) - .withDeserializers(new EscMeta.JsonbDeSer()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()) - .withEncoding(Charset.forName("utf-8")) - .build(); - jsonbDeSer.init(typeRegistry); - - try (final Jsonb jsonb = jsonbDeSer.getJsonb()) { - - // TEST - final EscMeta testee = jsonb.fromJson(expectedJson, EscMeta.class); - - // VERIFY - assertThat(testee.getDataType()).isEqualTo("MyEvent"); - assertThat(testee.getDataContentType()).isEqualTo(dataContentType); - assertThat(testee.getMetaType()).isEqualTo("MyMeta"); - assertThat(testee.getMetaContentType()).isEqualTo(metaContentType); - assertThat(testee.getMeta()).isInstanceOf(Base64Data.class); - final Base64Data base64Data = (Base64Data) testee.getMeta(); - assertThat(base64Data.getEncoded()).isEqualTo("PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+"); - - } - - } - -} -// CHECKSTYLE:ON diff --git a/spi/src/test/java/org/fuin/esc/spi/EscSpiUtilsTest.java b/spi/src/test/java/org/fuin/esc/spi/EscSpiUtilsTest.java index e1827e33..3a0e8140 100644 --- a/spi/src/test/java/org/fuin/esc/spi/EscSpiUtilsTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/EscSpiUtilsTest.java @@ -1,35 +1,41 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.esc.spi; import jakarta.activation.MimeTypeParseException; -import jakarta.json.bind.serializer.DeserializationContext; -import jakarta.json.bind.serializer.JsonbDeserializer; -import jakarta.json.bind.serializer.JsonbSerializer; -import jakarta.json.bind.serializer.SerializationContext; -import jakarta.json.stream.JsonGenerator; -import jakarta.json.stream.JsonParser; -import org.fuin.esc.api.*; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.Deserializer; +import org.fuin.esc.api.DeserializerRegistry; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.IBaseTypeFactory; +import org.fuin.esc.api.IEscMeta; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.Serializer; +import org.fuin.esc.api.SerializerRegistry; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.api.TypeName; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -import java.lang.reflect.Type; -import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; @@ -38,7 +44,6 @@ /** * Tests the {@link EscSpiUtils} class. */ -// CHECKSTYLE:OFF Test public class EscSpiUtilsTest { @Test @@ -62,10 +67,10 @@ public void testEventsEqual() { assertThat(EscSpiUtils.eventsEqual(asList(eventA), asList(eventAa))).isTrue(); assertThat(EscSpiUtils.eventsEqual(asList(eventA), asList(eventA, eventB))).isFalse(); assertThat(EscSpiUtils.eventsEqual(asList(eventA, eventB), asList(eventB))).isFalse(); - + } - - + + @Test public void testSerializeNull() { @@ -193,7 +198,6 @@ public void testMimeTypeDifferent() { events.add(new SimpleCommonEvent(new EventId(), eventTypeA, "One")); events.add(new SimpleCommonEvent(new EventId(), eventTypeB, "")); - // TEST // TEST final EnhancedMimeType mimeType = EscSpiUtils.mimeType(registry, events); @@ -207,9 +211,10 @@ public void testCreateEscMetaNull() { // PREPARE final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + final IBaseTypeFactory baseTypeFactory = Mockito.mock(IBaseTypeFactory.class); // TEST - final EscMeta result = EscSpiUtils.createEscMeta(registry, + final IEscMeta result = EscSpiUtils.createEscMeta(registry, baseTypeFactory, EnhancedMimeType.create("application/xml"), null); // VERIFY @@ -217,261 +222,6 @@ public void testCreateEscMetaNull() { } - @Test - public void testCreateEscMetaTargetXmlDataXmlMetaNull() { - - // PREPARE - final String description = "Whatever"; - final UUID uuid = UUID.randomUUID(); - final MyEvent myEvent = new MyEvent(uuid, description); - final EventId eventId = new EventId(); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); - final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); - - // TEST - final EscMeta result = EscSpiUtils.createEscMeta(registry, - EnhancedMimeType.create("application/xml; encoding=UTF-8"), commonEvent); - - // VERIFY - assertThat(result).isNotNull(); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); - assertThat(result.getDataContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; encoding=UTF-8")); - assertThat(result.getMetaType()).isNull(); - assertThat(result.getMetaContentType()).isNull(); - assertThat(result.getMeta()).isNull(); - - } - - @Test - public void testCreateEscMetaTargetJsonDataXmlMetaNull() { - - // PREPARE - final String description = "Whatever"; - final UUID uuid = UUID.randomUUID(); - final MyEvent myEvent = new MyEvent(uuid, description); - final EventId eventId = new EventId(); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); - final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent); - - // TEST - final EscMeta result = EscSpiUtils.createEscMeta(registry, - EnhancedMimeType.create("application/json"), commonEvent); - - // VERIFY - assertThat(result).isNotNull(); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); - assertThat(result.getDataContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); - assertThat(result.getMetaType()).isNull(); - assertThat(result.getMetaContentType()).isNull(); - assertThat(result.getMeta()).isNull(); - - } - - @Test - public void testCreateEscMetaTargetXmlDataXmlMetaXml() { - - // PREPARE - final MyEvent myEvent = new MyEvent(UUID.randomUUID(), "Whatever"); - final EventId eventId = new EventId(); - final MyMeta myMeta = new MyMeta("peter"); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); - registry.addSerializer(MyMeta.SER_TYPE, new XmlDeSerializer(MyMeta.class)); - final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, - myMeta); - - // TEST - final EscMeta result = EscSpiUtils.createEscMeta(registry, - EnhancedMimeType.create("application/xml; encoding=UTF-8"), commonEvent); - - // VERIFY - assertThat(result).isNotNull(); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); - assertThat(result.getDataContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; encoding=UTF-8")); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); - assertThat(result.getMetaContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; encoding=UTF-8")); - assertThat(result.getMeta()).isEqualTo(myMeta); - - } - - @Test - public void testCreateEscMetaTargetJsonDataXmlMetaXml() { - - // PREPARE - final String description = "Whatever"; - final UUID uuid = UUID.randomUUID(); - final MyEvent myEvent = new MyEvent(uuid, description); - final EventId eventId = new EventId(); - final MyMeta myMeta = new MyMeta("peter"); - final SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - registry.addSerializer(MyEvent.SER_TYPE, new XmlDeSerializer(MyEvent.class)); - registry.addSerializer(MyMeta.SER_TYPE, new XmlDeSerializer(MyMeta.class)); - final CommonEvent commonEvent = new SimpleCommonEvent(eventId, MyEvent.TYPE, myEvent, MyMeta.TYPE, - myMeta); - - // TEST - final EscMeta result = EscSpiUtils.createEscMeta(registry, - EnhancedMimeType.create("application/json"), commonEvent); - - // VERIFY - assertThat(result).isNotNull(); - assertThat(result.getDataType()).isEqualTo(MyEvent.TYPE.asBaseType()); - assertThat(result.getDataContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); - assertThat(result.getMetaType()).isEqualTo(MyMeta.TYPE.asBaseType()); - assertThat(result.getMetaContentType()).isEqualTo( - EnhancedMimeType.create("application/xml; transfer-encoding=base64; encoding=UTF-8")); - assertThat(result.getMeta()).isInstanceOf(Base64Data.class); - final Base64Data base64Meta = (Base64Data) result.getMeta(); - assertThat(new String(base64Meta.getDecoded(), Charset.forName("utf-8"))).isEqualTo( - "peter"); - - } - - @Test - public void testJoinJsonbSerializers() { - - final JsonbSerializer a = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer b = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer c = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer d = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - - assertThat(EscSpiUtils.joinJsonbSerializers(new JsonbSerializer[] {})).isEmpty();; - assertThat(EscSpiUtils.joinJsonbSerializers(new JsonbSerializer[] {}, a)).containsExactly(a); - assertThat(EscSpiUtils.joinJsonbSerializers(new JsonbSerializer[] {a}, b)).containsExactly(a, b); - assertThat(EscSpiUtils.joinJsonbSerializers(new JsonbSerializer[] {a, b}, c)).containsExactly(a, b, c); - assertThat(EscSpiUtils.joinJsonbSerializers(new JsonbSerializer[] {a, b}, c, d)).containsExactly(a, b, c, d); - - } - - @Test - public void testJoinJsonbSerializerArrays() { - - final JsonbSerializer a = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer b = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer c = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - final JsonbSerializer d = new JsonbSerializer() { - @Override - public void serialize(Object obj, JsonGenerator generator, SerializationContext ctx) { - } - }; - - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {})).isEmpty();; - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {}, new JsonbSerializer[] {a})).containsExactly(a); - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {a}, new JsonbSerializer[] {b})).contains(a, b); - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {a, b}, new JsonbSerializer[] {c})).contains(a, b, c); - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {a, b}, new JsonbSerializer[] {c, d})).contains(a, b, c, d); - assertThat(EscSpiUtils.joinJsonbSerializerArrays(new JsonbSerializer[] {a}, new JsonbSerializer[] {b}, new JsonbSerializer[] {c})).contains(a, b, c); - - } - - @Test - public void testJoinJsonbDeserializers() { - - final JsonbDeserializer a = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer b = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer c = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer d = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - - assertThat(EscSpiUtils.joinJsonbDeserializers(new JsonbDeserializer[] {})).isEmpty();; - assertThat(EscSpiUtils.joinJsonbDeserializers(new JsonbDeserializer[] {}, a)).containsExactly(a); - assertThat(EscSpiUtils.joinJsonbDeserializers(new JsonbDeserializer[] {a}, b)).containsExactly(a, b); - assertThat(EscSpiUtils.joinJsonbDeserializers(new JsonbDeserializer[] {a, b}, c)).containsExactly(a, b, c); - assertThat(EscSpiUtils.joinJsonbDeserializers(new JsonbDeserializer[] {a, b}, c, d)).containsExactly(a, b, c, d); - - } - - @Test - public void testJoinJsonbDeserializerArrays() { - - final JsonbDeserializer a = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer b = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer c = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - final JsonbDeserializer d = new JsonbDeserializer() { - @Override - public Object deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { - return null; - } - }; - - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {})).isEmpty();; - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {}, new JsonbDeserializer[] {a})).containsExactly(a); - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {a}, new JsonbDeserializer[] {b})).contains(a, b); - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {a, b}, new JsonbDeserializer[] {c})).contains(a, b, c); - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {a, b}, new JsonbDeserializer[] {c, d})).contains(a, b, c, d); - assertThat(EscSpiUtils.joinJsonbDeserializerArrays(new JsonbDeserializer[] {a}, new JsonbDeserializer[] {b}, new JsonbDeserializer[] {c})).contains(a, b, c); - - } - private EnhancedMimeType mimeType(String str) { try { return new EnhancedMimeType(str); @@ -510,13 +260,8 @@ public T unmarshal(Object data, SerializedDataType type, EnhancedMimeType mi }; } - private List asList(CommonEvent...events) { - final List list = new ArrayList<>(); - for (final CommonEvent event : events) { - list.add(event); - } - return list; + private List asList(CommonEvent... events) { + return new ArrayList<>(Arrays.asList(events)); } } -// CHECKSTYLE:ON diff --git a/spi/src/test/java/org/fuin/esc/spi/JandexSerializedDataTypeRegistryTest.java b/spi/src/test/java/org/fuin/esc/spi/JandexSerializedDataTypeRegistryTest.java deleted file mode 100644 index 2a269603..00000000 --- a/spi/src/test/java/org/fuin/esc/spi/JandexSerializedDataTypeRegistryTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.fuin.esc.spi; - -import org.fuin.esc.api.JandexSerializedDataTypeRegistry; -import org.junit.jupiter.api.Test; - -import java.io.File; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test for the {@link JandexSerializedDataTypeRegistry} class. - */ -public class JandexSerializedDataTypeRegistryTest { - - @Test - public void testBaseDataTypes() { - final JandexSerializedDataTypeRegistry testee = new JandexSerializedDataTypeRegistry(); - assertThat(testee.getClasses()).containsOnly( - Base64Data.class, - EscEvent.class, - EscEvents.class, - EscMeta.class - ); - } - -} diff --git a/spi/src/test/java/org/fuin/esc/spi/MyEvent.java b/spi/src/test/java/org/fuin/esc/spi/MyEvent.java index 998ac11f..c9ba0a9c 100644 --- a/spi/src/test/java/org/fuin/esc/spi/MyEvent.java +++ b/spi/src/test/java/org/fuin/esc/spi/MyEvent.java @@ -1,155 +1,139 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.json.Json; -import jakarta.json.JsonStructure; -import jakarta.validation.constraints.NotEmpty; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.ToJsonCapable; -import org.fuin.esc.api.TypeName; -import org.fuin.objects4j.common.Contract; - -import java.io.Serializable; -import java.util.UUID; - -/** - * Something interesting happened. Equals and hash code are based on the UUID. - */ -@XmlRootElement(name = "MyEvent") -public final class MyEvent implements Serializable, ToJsonCapable { - - private static final long serialVersionUID = 100L; - - /** Unique name of the event. */ - public static final TypeName TYPE = new TypeName("MyEvent"); - - /** Unique name of the serialized event. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - @XmlElement(name = "id") - private String id; - - @XmlElement(name = "description") - private String description; - - /** - * Protected default constructor for JAXB. - */ - protected MyEvent() { - super(); - } - - /** - * Constructor with random UUID. - * - * @param description - * The description. - */ - public MyEvent(@NotEmpty final String description) { - super(); - Contract.requireArgNotEmpty("description", description); - this.id = UUID.randomUUID().toString(); - this.description = description; - } - - /** - * Constructor with all mandatory data. - * - * @param uuid - * The unique identifier of the event. - * @param description - * The description. - */ - public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { - super(); - Contract.requireArgNotNull("uuid", uuid); - Contract.requireArgNotEmpty("description", description); - this.id = uuid.toString(); - this.description = description; - } - - /** - * Returns the unique identifier. - * - * @return UUID string. - */ - @NotNull - public final String getId() { - return id; - } - - /** - * Returns the description. - * - * @return The description. - */ - @NotEmpty - public final String getDescription() { - return description; - } - - // CHECKSTYLE:OFF Generated code - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MyEvent other = (MyEvent) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - return true; - } - - // CHECKSTYLE:ON - - @Override - public final String toString() { - return "My event: " + description; - } - - @Override - @NotNull - public final JsonStructure toJson() { - return Json.createObjectBuilder().add("id", id).add("description", description).build(); - } - -} +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.spi; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; +import org.fuin.objects4j.common.Contract; + +import java.io.Serializable; +import java.util.UUID; + +/** + * Something interesting happened. Equals and hash code are based on the UUID. + */ +@ArchIgnore +public final class MyEvent implements Serializable { + + private static final long serialVersionUID = 100L; + + /** Unique name of the event. */ + public static final TypeName TYPE = new TypeName("MyEvent"); + + /** Unique name of the serialized event. */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + private String id; + + private String description; + + /** + * Protected default constructor for JAXB. + */ + protected MyEvent() { + super(); + } + + /** + * Constructor with random UUID. + * + * @param description + * The description. + */ + public MyEvent(@NotEmpty final String description) { + super(); + Contract.requireArgNotEmpty("description", description); + this.id = UUID.randomUUID().toString(); + this.description = description; + } + + /** + * Constructor with all mandatory data. + * + * @param uuid + * The unique identifier of the event. + * @param description + * The description. + */ + public MyEvent(@NotNull final UUID uuid, @NotEmpty final String description) { + super(); + Contract.requireArgNotNull("uuid", uuid); + Contract.requireArgNotEmpty("description", description); + this.id = uuid.toString(); + this.description = description; + } + + /** + * Returns the unique identifier. + * + * @return UUID string. + */ + @NotNull + public final String getId() { + return id; + } + + /** + * Returns the description. + * + * @return The description. + */ + @NotEmpty + public final String getDescription() { + return description; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyEvent other = (MyEvent) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + @Override + public final String toString() { + return "My event: " + description; + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/MyMeta.java b/spi/src/test/java/org/fuin/esc/spi/MyMeta.java index 461bc1ee..c2752b38 100644 --- a/spi/src/test/java/org/fuin/esc/spi/MyMeta.java +++ b/spi/src/test/java/org/fuin/esc/spi/MyMeta.java @@ -1,121 +1,110 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.annotation.Nullable; -import jakarta.json.Json; -import jakarta.json.JsonStructure; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.fuin.esc.api.SerializedDataType; -import org.fuin.esc.api.ToJsonCapable; -import org.fuin.esc.api.TypeName; - -import java.io.Serializable; - -/** - * Example meta data. . - */ -@XmlRootElement(name = "MyMeta") -public final class MyMeta implements Serializable, ToJsonCapable { - - private static final long serialVersionUID = 100L; - - /** Unique name of the meta type. */ - public static final TypeName TYPE = new TypeName("MyMeta"); - - /** Unique name of the serialized meta type. */ - public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - - @XmlElement(name = "user") - private String user; - - /** - * Protected default constructor for JAXB. - */ - protected MyMeta() { - super(); - } - - /** - * Constructor with all mandatory data. - * - * @param user - * User ID. - */ - public MyMeta(@Nullable final String user) { - super(); - this.user = user; - } - - /** - * Returns the user. - * - * @return User ID. - */ - public final String getUser() { - return user; - } - - // CHECKSTYLE:OFF Generated code - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((user == null) ? 0 : user.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MyMeta other = (MyMeta) obj; - if (user == null) { - if (other.user != null) { - return false; - } - } else if (!user.equals(other.user)) { - return false; - } - return true; - } - - // CHECKSTYLE:ON - - @Override - public final String toString() { - return "My meta: " + user; - } - - @Override - @NotNull - public final JsonStructure toJson() { - return Json.createObjectBuilder().add("user", user).build(); - } - -} +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.spi; + +import com.tngtech.archunit.junit.ArchIgnore; +import jakarta.annotation.Nullable; +import org.fuin.esc.api.SerializedDataType; +import org.fuin.esc.api.TypeName; + +import java.io.Serializable; + +/** + * Example meta data. . + */ +@ArchIgnore +public final class MyMeta implements Serializable { + + private static final long serialVersionUID = 100L; + + /** + * Unique name of the meta type. + */ + public static final TypeName TYPE = new TypeName("MyMeta"); + + /** + * Unique name of the serialized meta type. + */ + public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); + + private String user; + + /** + * Protected default constructor for JAXB. + */ + protected MyMeta() { + super(); + } + + /** + * Constructor with all mandatory data. + * + * @param user User ID. + */ + public MyMeta(@Nullable final String user) { + super(); + this.user = user; + } + + /** + * Returns the user. + * + * @return User ID. + */ + public final String getUser() { + return user; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((user == null) ? 0 : user.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MyMeta other = (MyMeta) obj; + if (user == null) { + if (other.user != null) { + return false; + } + } else if (!user.equals(other.user)) { + return false; + } + return true; + } + + + @Override + public final String toString() { + return "My meta: " + user; + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/ProjectionJavaScriptBuilderTest.java b/spi/src/test/java/org/fuin/esc/spi/ProjectionJavaScriptBuilderTest.java index 83d7865a..e83f922f 100644 --- a/spi/src/test/java/org/fuin/esc/spi/ProjectionJavaScriptBuilderTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/ProjectionJavaScriptBuilderTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,10 +31,9 @@ /** * Tests the {@link ProjectionJavaScriptBuilder} class. */ -// CHECKSTYLE:OFF Test public class ProjectionJavaScriptBuilderTest { - + @Test public void testFromAll() { @@ -44,7 +43,7 @@ public void testFromAll() { + "'AccountDebited': function(state, ev) { linkTo('AccountsView', ev); }" + "})"); } - + @Test public void testNoEventType() { @@ -109,4 +108,4 @@ public void testEventTypes() { } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/SerializedDataTest.java b/spi/src/test/java/org/fuin/esc/spi/SerializedDataTest.java index f41d8233..2d30ad3c 100644 --- a/spi/src/test/java/org/fuin/esc/spi/SerializedDataTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/SerializedDataTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -30,7 +30,6 @@ /** * Tests the {@link SerializedData} class. */ -// CHECKSTYLE:OFF Test public class SerializedDataTest { private static final SerializedDataType TYPE = new SerializedDataType( @@ -39,7 +38,7 @@ public class SerializedDataTest { private static final EnhancedMimeType MIME_TYPE = EnhancedMimeType .create("application/xml; encoding=utf-8"); - private static final byte[] RAW = new byte[] { 0x1, 0x2, 0x3 }; + private static final byte[] RAW = new byte[]{0x1, 0x2, 0x3}; private SerializedData testee; @@ -61,12 +60,12 @@ public void testGetter() { assertThat(testee.getRaw()).isEqualTo(RAW); } - + @Test public void testEqualsHashCode() { EqualsVerifier.forClass(SerializedData.class).verify(); } - + } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/TenantStreamIdTest.java b/spi/src/test/java/org/fuin/esc/spi/TenantStreamIdTest.java index d6d08f7b..d03f98ef 100644 --- a/spi/src/test/java/org/fuin/esc/spi/TenantStreamIdTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/TenantStreamIdTest.java @@ -32,7 +32,6 @@ /** * Tests the {@link TenantStreamId} class. */ -// CHECKSTYLE:OFF Test public class TenantStreamIdTest { private static final TenantId TENANT_ID = new SimpleTenantId("mycompany"); @@ -77,4 +76,4 @@ public void testGetSingleParamValue() { }).isInstanceOf(UnsupportedOperationException.class); } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/java/org/fuin/esc/spi/TextDeSerializerTest.java b/spi/src/test/java/org/fuin/esc/spi/TextDeSerializerTest.java index 93063085..ea996db5 100644 --- a/spi/src/test/java/org/fuin/esc/spi/TextDeSerializerTest.java +++ b/spi/src/test/java/org/fuin/esc/spi/TextDeSerializerTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,7 +31,6 @@ /** * Tests the {@link TextDeSerializer} class. */ -// CHECKSTYLE:OFF Test public class TextDeSerializerTest { private static final Charset CHARSET = Charset.forName("iso-8859-1"); @@ -89,4 +88,4 @@ public void testGetMimeType() { } } -// CHECKSTYLE:ON + diff --git a/spi/src/test/resources/esc-event-base64.json b/spi/src/test/resources/esc-event-base64.json deleted file mode 100644 index 89b26523..00000000 --- a/spi/src/test/resources/esc-event-base64.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", - "EventType": "MyEvent", - "Data": { - "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" - }, - "MetaData": { - "data-type": "MyEvent", - "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", - "meta-type": "MyMeta", - "meta-content-type": "application/json; version=1; encoding=UTF-8", - "MyMeta": { - "user": "abc" - } - } -} diff --git a/spi/src/test/resources/esc-event.json b/spi/src/test/resources/esc-event.json deleted file mode 100644 index 3b340b8b..00000000 --- a/spi/src/test/resources/esc-event.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "EventId":"b2a936ce-d479-414f-b67f-3df4da383d47", - "EventType":"MyEvent", - "Data":{ - "id":"b2a936ce-d479-414f-b67f-3df4da383d47", - "description":"Hello, JSON!" - }, - "MetaData":{ - "data-type":"MyEvent", - "data-content-type":"application/json; version=1; encoding=UTF-8", - "meta-type":"MyMeta", - "meta-content-type":"application/json; version=1; encoding=UTF-8", - "MyMeta":{ - "user":"abc" - } - } -} diff --git a/spi/src/test/resources/esc-event.xml b/spi/src/test/resources/esc-event.xml deleted file mode 100644 index a31a8378..00000000 --- a/spi/src/test/resources/esc-event.xml +++ /dev/null @@ -1,18 +0,0 @@ - - 68616d90-cf72-4c2a-b913-32bf6e6506ed - MyEvent - - 68616d90-cf72-4c2a-b913-32bf6e6506edHello, XML! - - - - MyEvent - application/xml; version=1; encoding=utf-8 - MyMeta - application/xml; version=1; encoding=utf-8 - - abc - - - - diff --git a/spi/src/test/resources/esc-events.json b/spi/src/test/resources/esc-events.json deleted file mode 100644 index e167fc80..00000000 --- a/spi/src/test/resources/esc-events.json +++ /dev/null @@ -1,35 +0,0 @@ -[ - { - "EventId": "b2a936ce-d479-414f-b67f-3df4da383d47", - "EventType": "MyEvent", - "Data": { - "id": "b2a936ce-d479-414f-b67f-3df4da383d47", - "description": "Hello, JSON!" - }, - "MetaData": { - "data-type": "MyEvent", - "data-content-type": "application/json; version=1; encoding=UTF-8", - "meta-type": "MyMeta", - "meta-content-type": "application/json; version=1; encoding=UTF-8", - "MyMeta": { - "user": "abc" - } - } - }, - { - "EventId": "68616d90-cf72-4c2a-b913-32bf6e6506ed", - "EventType": "MyEvent", - "Data": { - "Base64": "eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9" - }, - "MetaData": { - "data-type": "MyEvent", - "data-content-type": "application/json; version=1; transfer-encoding=base64; encoding=UTF-8", - "meta-type": "MyMeta", - "meta-content-type": "application/json; version=1; encoding=UTF-8", - "MyMeta": { - "user": "abc" - } - } - } -] \ No newline at end of file diff --git a/spi/src/test/resources/esc-events.xml b/spi/src/test/resources/esc-events.xml deleted file mode 100644 index 9937623f..00000000 --- a/spi/src/test/resources/esc-events.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 68616d90-cf72-4c2a-b913-32bf6e6506ed - MyEvent - - eyAibXktZXZlbnQiOiB7ICJpZCI6ICAiNjg2MTZkOTAtY2Y3Mi00YzJhLWI5MTMtMzJiZjZlNjUwNmVkIiwgImRlc2NyaXB0aW9uIjogIkhlbGxvLCBKU09OISIgfSB9 - - - - MyEvent - application/json; version=1; encoding=utf-8;transfer-encoding=base64 - MyMeta - application/xml; version=1; encoding=utf-8 - - abc - - - - - - c198a02e-126e-4fbb-910c-918abf39a4a6 - MyEvent - - - - - - MyEvent - application/xml; version=1; encoding=utf-8 - MyMeta - application/xml; version=1; encoding=utf-8 - - abc - - - - - diff --git a/spi/src/test/resources/esc-meta-base64.json b/spi/src/test/resources/esc-meta-base64.json deleted file mode 100644 index a7341404..00000000 --- a/spi/src/test/resources/esc-meta-base64.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "data-type": "MyEvent", - "data-content-type": "application/xml; encoding=UTF-8", - "meta-type": "MyMeta", - "meta-content-type": "application/xml; transfer-encoding=base64; encoding=UTF-8", - "Base64": "PG15LW1ldGE+PHVzZXI+bWljaGFlbDwvdXNlcj48L215LW1ldGE+" -} diff --git a/spi/src/test/resources/esc-meta.json b/spi/src/test/resources/esc-meta.json deleted file mode 100644 index 1a3baf12..00000000 --- a/spi/src/test/resources/esc-meta.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "data-type": "MyEvent", - "data-content-type":"application/xml; version=1; transfer-encoding=base64; encoding=UTF-8", - "meta-type": "MyMeta", - "meta-content-type":"application/json; version=1; encoding=UTF-8", - "MyMeta":{ - "user":"abc" - } -} \ No newline at end of file diff --git a/spi/src/test/resources/esc-meta.xml b/spi/src/test/resources/esc-meta.xml deleted file mode 100644 index 71a3420b..00000000 --- a/spi/src/test/resources/esc-meta.xml +++ /dev/null @@ -1,9 +0,0 @@ - - MyEvent - application/xml; version=1; encoding=utf-8 - MyMeta - application/xml; version=1; encoding=utf-8 - - abc - - \ No newline at end of file diff --git a/spi/src/test/resources/events.xml b/spi/src/test/resources/events.xml deleted file mode 100644 index c407af04..00000000 --- a/spi/src/test/resources/events.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/test/README.md b/test/README.md index c4c745a8..fa472a0c 100644 --- a/test/README.md +++ b/test/README.md @@ -1,4 +1,5 @@ # esc-test + Provides tests for all event store commons implementations. ## Performance @@ -7,13 +8,13 @@ Provides tests for all event store commons implementations. | Implementation | Type | One append (100,000 at once) | Multiple appends (100,000 times) | Read chunks of 4,000 (100,000 events) | Read one by one (100,000 events) | |:---------------------------------------------------------------------------------|:--------------------|:-----------------------------|:---------------------------------|:--------------------------------------|:---------------------------------| -| [esc-eshttp](src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java) | Physical PC SSD (1) | 2,467 events / second | 96 events / second | 901 events / second | 464 events / second | -| [esc-eshttp](src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java) | Physical PC HDD (2) | 2,426 events / second | 15 events / second | 909 events / second | 459 events / second | +| [esc-eshttp](src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java) | Physical PC SSD (1) | 2,467 events / second | 96 events / second | 901 events / second | 464 events / second | +| [esc-eshttp](src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java) | Physical PC HDD (2) | 2,426 events / second | 15 events / second | 909 events / second | 459 events / second | | [esc-eshttp](src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java) | Virtual Machine (3) | 4,042 events / second | 379 events / second | 832 events / second | 403 events / second | * 64 Bit Java 8 Runtime * (1) Intel Core i7-3820 @ 3.60 GHz, 16 GB RAM, Windows 7 SP 1, Crucial M4 512GB SSD -* (2) Intel Core i7-3820 @ 3.60 GHz, 16 GB RAM, Windows 7 SP 1, WD Scorpio Blue WD10JPVT 1TB 5400 RPM 8MB Cache SATA +* (2) Intel Core i7-3820 @ 3.60 GHz, 16 GB RAM, Windows 7 SP 1, WD Scorpio Blue WD10JPVT 1TB 5400 RPM 8MB Cache SATA * (3) VMWare Workstation 12 + Ubuntu 14.04 Desktop (Same machine as (1)) _The slower performance on a physical machine is somewhat surprising... Should be investigated!_ diff --git a/test/pom.xml b/test/pom.xml index b1bc53f6..83a722ab 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 @@ -18,7 +19,7 @@ https://github.com/fuinorg/event-store-commons/ scm:git:git://github.com/fuinorg/event-store-commons.git scm:git:git@github.com:fuinorg/event-store-commons.git - + GitHub Issues @@ -39,14 +40,20 @@ slf4j-api + + jakarta.annotation + jakarta.annotation-api + + + org.fuin.objects4j - objects4j-core + objects4j-common - org.apache.httpcomponents - httpclient + org.fuin.objects4j + objects4j-core @@ -65,25 +72,25 @@ org.fuin.esc - esc-eshttp + esc-jpa test org.fuin.esc - esc-jpa + esc-esgrpc test org.fuin.esc - esc-esjc + esc-jsonb test org.fuin.esc - esc-esgrpc + esc-jaxb test @@ -100,12 +107,6 @@ test - - jakarta.json - jakarta.json-api - test - - org.junit.jupiter junit-jupiter @@ -135,12 +136,6 @@ test - - commons-io - commons-io - test - - commons-codec commons-codec @@ -178,8 +173,8 @@ - org.hibernate - hibernate-core-jakarta + org.hibernate + hibernate-core-jakarta test @@ -189,6 +184,69 @@ test + + org.fuin + units4j + test + + + + jakarta.json.bind + jakarta.json.bind-api + test + + + + io.cucumber + cucumber-core + 1.2.6 + test + + + + jakarta.xml.bind + jakarta.xml.bind-api + test + + + + jakarta.persistence + jakarta.persistence-api + test + + + + info.cukes + gherkin + 2.12.2 + test + + + + com.eventstore + db-client-java + 5.2.0 + test + + + + com.google.code.findbugs + jsr305 + test + + + + org.fuin + utils4j + test + + + + org.apache.httpcomponents + httpclient + test + + @@ -235,64 +293,94 @@ maven-failsafe-plugin - - io.fabric8 - docker-maven-plugin - - - - - eventstore/eventstore:${eventstore.version} - - - bridge - - - 1113:1113 - 2113:2113 - - - TRUE - All - true - true - true - /tmp/log-eventstore - - - false - - - - http://localhost:2113/web/index.html#/ - GET - - - - - - - - - - - - start-images - pre-integration-test - - start - - - - stop-images - post-integration-test - - stop - - - - - + + io.fabric8 + docker-maven-plugin + + + + + eventstore/eventstore:${eventstore.version} + + + bridge + + + 1113:1113 + 2113:2113 + + + TRUE + All + true + true + true + /tmp/log-eventstore + + + false + + + + http://localhost:2113/web/index.html#/ + GET + + + + + + + + + + + + start-images + pre-integration-test + + start + + + + stop-images + post-integration-test + + stop + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.hibernate.validator:hibernate-validator + org.glassfish:jakarta.el + ch.qos.logback:logback-classic + commons-codec:commons-codec + javax.transaction:jta + org.jboss.logging:jboss-logging + org.hibernate:hibernate-core-jakarta + org.hsqldb:hsqldb + org.fuin:units4j + com.tngtech.archunit:archunit-junit5 + org.junit.jupiter:junit-jupiter + + + + junit:junit + com.tngtech.archunit:archunit-junit5-api + org.junit.jupiter:junit-jupiter-api + + + org.fuin.objects4j:objects4j-common + org.fuin.objects4j:objects4j-core + + + diff --git a/test/src/main/java/org/fuin/esc/test/EscTestUtils.java b/test/src/main/java/org/fuin/esc/test/EscTestUtils.java index cba0c982..4b40ca53 100644 --- a/test/src/main/java/org/fuin/esc/test/EscTestUtils.java +++ b/test/src/main/java/org/fuin/esc/test/EscTestUtils.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -36,12 +36,12 @@ private EscTestUtils() { /** * Creates a failure message from an exception. - * + * * @param identifier * Unique identifier this failure relates to. * @param exception * Current exception. - * + * * @return Message. */ public static String createExceptionFailureMessage(final String identifier, final Exception exception) { @@ -50,24 +50,24 @@ public static String createExceptionFailureMessage(final String identifier, fina /** * Creates a failure message from an expected type and an exception. - * + * * @param identifier * Unique identifier this failure relates to. * @param expectedExceptionClass * Expected exception type. * @param exception * Current exception. - * + * * @return Message. */ public static String createExceptionFailureMessage(final String identifier, final Class expectedExceptionClass, - final Exception exception) { + final Exception exception) { return createExceptionFailureMessage(identifier, expectedExceptionClass, null, exception); } /** * Creates a failure message from an expected type, message and an exception. - * + * * @param identifier * Unique identifier this failure relates to. * @param expectedExceptionClass @@ -76,11 +76,11 @@ public static String createExceptionFailureMessage(final String identifier, fina * Expected exception message. * @param exception * Current exception. - * + * * @return Message. */ public static String createExceptionFailureMessage(final String identifier, final Class expectedExceptionClass, - final String expectedExceptionMessage, final Exception exception) { + final String expectedExceptionMessage, final Exception exception) { if (expectedExceptionClass == null) { if (exception == null) { return "[" + identifier + "] OK"; @@ -113,10 +113,10 @@ private static String nameAndMessage(final Exception ex) { /** * Converts an empty string into null. - * + * * @param str * String to return. - * + * * @return String or null if the input string was "" or "-". */ public static String emptyAsNull(@Nullable final String str) { @@ -124,7 +124,7 @@ public static String emptyAsNull(@Nullable final String str) { return null; } final String name = str.trim(); - if (name.length() == 0 || name.equals("-")) { + if (name.isEmpty() || name.equals("-")) { return null; } return str; @@ -133,10 +133,10 @@ public static String emptyAsNull(@Nullable final String str) { /** * Creates an exception class from an exception name. If the name is NOT fully qualified (has no '.' in the name) it's assumed that it's * an API exception from package 'org.fuin.esc.api'. - * + * * @param exceptionName * Fully qualified name or a simple name of a class located in the "org.fuin.esc.api" package. - * + * * @return Class. */ @SuppressWarnings("unchecked") @@ -157,12 +157,12 @@ public static Class exceptionForName(final String exception /** * Compares the two events based on their content. - * + * * @param eventA * First event. * @param eventB * Second event. - * + * * @return TRUE id the events have the same content. */ public static boolean sameContent(@Nullable final CommonEvent eventA, @Nullable final CommonEvent eventB) { @@ -194,18 +194,18 @@ public static boolean sameContent(@Nullable final CommonEvent eventA, @Nullable /** * Creates an exception message by pointing out the differences between two events. - * + * * @param identifier * Unique identifier to use in case of a failure. * @param expectedEvent * First event. * @param actualEvent * Second event. - * + * * @return Exception message. */ public static String createExceptionFailureMessage(final String identifier, final CommonEvent expectedEvent, - final CommonEvent actualEvent) { + final CommonEvent actualEvent) { if (expectedEvent == null) { if (actualEvent == null) { return "[" + identifier + "] OK"; diff --git a/test/src/test/java/org/fuin/esc/test/AbstractXmlTest.java b/test/src/test/java/org/fuin/esc/test/AbstractXmlTest.java index 0f0c82e3..4edad43b 100644 --- a/test/src/test/java/org/fuin/esc/test/AbstractXmlTest.java +++ b/test/src/test/java/org/fuin/esc/test/AbstractXmlTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -22,6 +22,7 @@ import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.annotation.adapters.XmlAdapter; + import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -32,13 +33,12 @@ /** * Base class for XML marshal/unmarshal tests. */ -// CHECKSTYLE:OFF Test public abstract class AbstractXmlTest { /** * Marshals the given data. A null data argument returns * null. Handles CDATA sections correctly. - * + * * @param data * Data to serialize or null. * @param adapters @@ -47,14 +47,14 @@ public abstract class AbstractXmlTest { * @param classesToBeBound * List of java classes to be recognized by the * {@link JAXBContext}. - * + * * @return XML data or null. - * + * * @param * Type of the data. */ protected static String marshalToStr(final T data, final XmlAdapter[] adapters, - final Class... classesToBeBound) { + final Class... classesToBeBound) { final StringWriter writer = new StringWriter(); @@ -72,4 +72,4 @@ protected static String marshalToStr(final T data, final XmlAdapter[] } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/AppendToStreamCommand.java b/test/src/test/java/org/fuin/esc/test/AppendToStreamCommand.java index 51e6d416..1c8283ff 100644 --- a/test/src/test/java/org/fuin/esc/test/AppendToStreamCommand.java +++ b/test/src/test/java/org/fuin/esc/test/AppendToStreamCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -75,7 +75,7 @@ public AppendToStreamCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param expectedVersion @@ -86,14 +86,14 @@ public AppendToStreamCommand() { * Events to add. */ public AppendToStreamCommand(@NotNull final String streamName, @Nullable final long expectedVersion, - @Nullable final Class expectedExceptionClass, - @NotNull final CommonEvent... events) { + @Nullable final Class expectedExceptionClass, + @NotNull final CommonEvent... events) { this(streamName, expectedVersion, expectedExceptionClass, EscSpiUtils.asList(events)); } /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param expectedVersion @@ -104,8 +104,8 @@ public AppendToStreamCommand(@NotNull final String streamName, @Nullable final l * Events to add. */ public AppendToStreamCommand(@NotNull final String streamName, @Nullable final long expectedVersion, - @Nullable final Class expectedExceptionClass, - @NotNull final List events) { + @Nullable final Class expectedExceptionClass, + @NotNull final List events) { super(); this.streamName = streamName; this.expectedVersion = "" + expectedVersion; @@ -121,7 +121,7 @@ public AppendToStreamCommand(@NotNull final String streamName, @Nullable final l public void init(final TestContext context) { this.es = context.getEventStore(); this.streamName = context.getCurrentEventStoreImplType() + "_" + streamName; - + expectedVersion = EscTestUtils.emptyAsNull(expectedVersion); expectedException = EscTestUtils.emptyAsNull(expectedException); eventId = EscTestUtils.emptyAsNull(eventId); diff --git a/test/src/test/java/org/fuin/esc/test/CreateStreamCommand.java b/test/src/test/java/org/fuin/esc/test/CreateStreamCommand.java index 907c6b5e..9fd63842 100644 --- a/test/src/test/java/org/fuin/esc/test/CreateStreamCommand.java +++ b/test/src/test/java/org/fuin/esc/test/CreateStreamCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -57,7 +57,7 @@ public CreateStreamCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. */ @@ -67,7 +67,7 @@ public CreateStreamCommand(@NotNull final String streamName) { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param expectedException diff --git a/test/src/test/java/org/fuin/esc/test/CucumberIT.java b/test/src/test/java/org/fuin/esc/test/CucumberIT.java index 3e4464d8..4d23c12c 100644 --- a/test/src/test/java/org/fuin/esc/test/CucumberIT.java +++ b/test/src/test/java/org/fuin/esc/test/CucumberIT.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,7 +24,7 @@ /** * Locates all cucumber files and starts them as unit tests. */ -// CHECKSTYLE:OFF Test code + // @formatter:off @RunWith(EscCucumber.class) @EscCucumberArgs({ "jpa", "mem", "eshttp", "esjc", "esgrpc" }) @@ -35,4 +35,4 @@ public class CucumberIT { } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/DeleteCommand.java b/test/src/test/java/org/fuin/esc/test/DeleteCommand.java index 3a73cdfa..355b9c22 100644 --- a/test/src/test/java/org/fuin/esc/test/DeleteCommand.java +++ b/test/src/test/java/org/fuin/esc/test/DeleteCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -64,7 +64,7 @@ public DeleteCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param hardDelete @@ -77,7 +77,7 @@ public DeleteCommand() { * The exception that is expected, an empty string or "-". */ public DeleteCommand(@NotNull final String streamName, final boolean hardDelete, - final String expectedVersion, final String expectedException) { + final String expectedVersion, final String expectedException) { super(); this.streamName = streamName; this.hardDelete = hardDelete; diff --git a/test/src/test/java/org/fuin/esc/test/EscCucumber.java b/test/src/test/java/org/fuin/esc/test/EscCucumber.java index ce1ae106..b792dd2b 100644 --- a/test/src/test/java/org/fuin/esc/test/EscCucumber.java +++ b/test/src/test/java/org/fuin/esc/test/EscCucumber.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test; import java.io.IOException; @@ -72,7 +71,7 @@ public EscCucumber(Class clazz) throws InitializationError, IOException { } else { argList.addAll(EscSpiUtils.asList(args.value())); } - + RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz); RuntimeOptions runtimeOptions = runtimeOptionsFactory.create(); @@ -82,11 +81,11 @@ public EscCucumber(Class clazz) throws InitializationError, IOException { final JUnitOptions junitOptions = new JUnitOptions(runtimeOptions.getJunitOptions()); final List cucumberFeatures = runtimeOptions.cucumberFeatures(resourceLoader); jUnitReporter = new JUnitReporter(runtimeOptions.reporter(classLoader), runtimeOptions.formatter(classLoader), runtimeOptions.isStrict(), junitOptions); - + for (final String arg : argList) { addChildren(cucumberFeatures, arg); } - + } /** @@ -97,7 +96,7 @@ public EscCucumber(Class clazz) throws InitializationError, IOException { * @param runtimeOptions configuration * @return a new runtime * @throws InitializationError if a JUnit error occurred - * @throws IOException if a class or resource could not be loaded + * @throws IOException if a class or resource could not be loaded */ protected Runtime createRuntime(ResourceLoader resourceLoader, ClassLoader classLoader, RuntimeOptions runtimeOptions) throws InitializationError, IOException { @@ -129,7 +128,7 @@ public void run(RunNotifier notifier) { } private void addChildren(final List cucumberFeatures, - final String arg) throws InitializationError { + final String arg) throws InitializationError { for (final CucumberFeature cucumberFeature : cucumberFeatures) { children.add(new FeatureRunner(cucumberFeature, runtime, jUnitReporter) { @@ -146,6 +145,6 @@ public void run(RunNotifier notifier) { }); } } - + } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/EscCucumberArgs.java b/test/src/test/java/org/fuin/esc/test/EscCucumberArgs.java index 641261d4..ced11f77 100644 --- a/test/src/test/java/org/fuin/esc/test/EscCucumberArgs.java +++ b/test/src/test/java/org/fuin/esc/test/EscCucumberArgs.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ diff --git a/spi/src/main/java/org/fuin/esc/spi/Event.java b/test/src/test/java/org/fuin/esc/test/Event.java similarity index 62% rename from spi/src/main/java/org/fuin/esc/spi/Event.java rename to test/src/test/java/org/fuin/esc/test/Event.java index 655efc14..6eae53f4 100644 --- a/spi/src/main/java/org/fuin/esc/spi/Event.java +++ b/test/src/test/java/org/fuin/esc/test/Event.java @@ -1,217 +1,227 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.annotation.Nullable; -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.fuin.esc.api.CommonEvent; -import org.fuin.esc.api.EventId; -import org.fuin.esc.api.SimpleCommonEvent; -import org.fuin.esc.api.TypeName; -import org.fuin.objects4j.common.Contract; -import org.fuin.objects4j.common.Immutable; -import org.fuin.objects4j.common.ValueObject; - -import java.io.Serializable; - -/** - * Helper class that allows sending an event as XML directly to the event store. - * The event is uniquely identified by a UUID. It's equals and hash code methods - * are defined on the id. This class might be useful for tests. - * It's not used in the 'esc-spi' code itself - */ -@Immutable -@XmlRootElement(name = "event") -public final class Event implements Serializable, ValueObject { - - private static final long serialVersionUID = 1000L; - - /** The ID of the event, used as part of the idempotent write check. */ - @NotNull - @XmlAttribute(name = "id") - private EventId id; - - /** The event data. */ - @NotNull - @XmlElement(name = "data") - private Data data; - - /** The meta data. */ - @XmlElement(name = "meta") - private Data meta; - - /** - * Protected constructor for deserialization. - */ - protected Event() { //NOSONAR Ignore uninitialized fields - super(); - } - - /** - * Constructor without XML meta data. - * - * @param id - * The ID of the event, used as part of the idempotent write - * check. - * @param data - * Event data. - * - */ - public Event(@NotNull final EventId id, @NotNull final Data data) { - this(id, data, null); - } - - /** - * Constructor with XML meta data. - * - * @param id - * The ID of the event, used as part of the idempotent write - * check. - * @param data - * Event data. - * @param meta - * Meta data. - * - */ - public Event(@NotNull final EventId id, @NotNull final Data data, - @Nullable final Data meta) {//NOSONAR - super(); - - Contract.requireArgNotNull("id", id); - Contract.requireArgNotNull("data", data); - - this.id = id; - this.data = data; - this.meta = meta; - - } - - /** - * Returns the ID of the event, used as part of the idempotent write check. - * - * @return Unique event identifier. - */ - @NotNull - public final EventId getId() { - return id; - } - - /** - * Returns the event data. - * - * @return Event data. - */ - @NotNull - public final Data getData() { - return data; - } - - /** - * Returns the meta data. - * - * @return Meta data. - */ - @Nullable - public final Data getMeta() { - return meta; - } - - /** - * Returns this object as a common event object. - * - * @param ctx - * In case the XML JAXB unmarshalling is used, you have to pass - * the JAXB context here. - * - * @return Converted object. - */ - public final CommonEvent asCommonEvent(final JAXBContext ctx) { - final Object m; - if (getMeta() == null) { - m = null; - } else { - m = getMeta().unmarshalContent(ctx); - } - final Object d = getData().unmarshalContent(ctx); - if (getMeta() == null) { - return new SimpleCommonEvent(getId(), - new TypeName(getData().getType()), d); - } - return new SimpleCommonEvent(getId(), new TypeName(getData().getType()), - d, new TypeName(getMeta().getType()), m); - } - - // CHECKSTYLE:OFF Generated code - - @Override - public final int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public final boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Event)) - return false; - Event other = (Event) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - // CHECKSTYLE:ON - - @Override - public String toString() { - return new ToStringBuilder(this).append("id", id).append("data", data) - .append("meta", meta).toString(); - } - - /** - * Creates an event using a common event. - * - * @param selEvent - * Event to copy. - * - * @return New instance. - */ - public static Event valueOf(final CommonEvent selEvent) { - final Data data = Data.valueOf(selEvent.getDataType().asBaseType(), - selEvent.getData()); - if (selEvent.getMeta() == null) { - return new Event(selEvent.getId(), data); - } - final Data meta = Data.valueOf("meta", selEvent.getMeta()); - return new Event(selEvent.getId(), data, meta); - } - -} +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.test; + +import jakarta.annotation.Nullable; +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Unmarshaller; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EnhancedMimeType; +import org.fuin.esc.api.EventId; +import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.TypeName; +import org.fuin.esc.jaxb.Data; +import org.fuin.objects4j.common.Contract; + +import javax.annotation.concurrent.Immutable; + +import org.fuin.objects4j.common.ValueObject; +import org.fuin.utils4j.jaxb.JaxbUtils; + +import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; +import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; + +import java.io.Serial; +import java.io.Serializable; + +/** + * Helper class that allows sending an event as XML directly to the event store. + * The event is uniquely identified by a UUID. It's equals and hash code methods + * are defined on the id. This class might be useful for tests. + * It's not used in the 'esc-spi' code itself + */ +@Immutable +@XmlRootElement(name = "event") +public final class Event implements Serializable, ValueObject { + + @Serial + private static final long serialVersionUID = 1000L; + + private static final EnhancedMimeType MIME_TYPE = EnhancedMimeType.create("application/xml; encoding=utf-8"); + + /** + * The ID of the event, used as part of the idempotent write check. + */ + @NotNull + @XmlAttribute(name = "id") + @XmlJavaTypeAdapter(EventIdXmlAdapter.class) + private EventId id; + + /** + * The event data. + */ + @NotNull + @XmlElement(name = "data") + private Data data; + + /** + * The meta data. + */ + @XmlElement(name = "meta") + private Data meta; + + /** + * Protected constructor for deserialization. + */ + protected Event() { //NOSONAR Ignore uninitialized fields + super(); + } + + /** + * Constructor without XML metadata. + * + * @param id The ID of the event, used as part of the idempotent write + * check. + * @param data Event data. + */ + public Event(@NotNull final EventId id, + @NotNull final Data data) { + this(id, data, null); + } + + /** + * Constructor with XML metadata. + * + * @param id The ID of the event, used as part of the idempotent write + * check. + * @param data Event data. + * @param meta Meta data. + */ + public Event(@NotNull final EventId id, + @NotNull final Data data, + @Nullable final Data meta) {//NOSONAR + super(); + + Contract.requireArgNotNull("id", id); + Contract.requireArgNotNull("data", data); + + this.id = id; + this.data = data; + this.meta = meta; + + } + + /** + * Returns the ID of the event, used as part of the idempotent write check. + * + * @return Unique event identifier. + */ + @NotNull + public EventId getId() { + return id; + } + + /** + * Returns the event data. + * + * @return Event data. + */ + @NotNull + public Data getData() { + return data; + } + + /** + * Returns the metadata. + * + * @return Meta data. + */ + @Nullable + public Data getMeta() { + return meta; + } + + /** + * Returns this object as a common event object. + * + * @param ctx In case the XML JAXB unmarshalling is used, you have to pass + * the JAXB context here. + * @return Converted object. + */ + public CommonEvent asCommonEvent(final JAXBContext ctx) { + final Object m; + if (getMeta() == null) { + m = null; + } else { + m = JaxbUtils.unmarshal(ctx, getMeta().getContent(), null); + } + final Object d = JaxbUtils.unmarshal(ctx, getData().getContent(), null); + if (getMeta() == null) { + return new SimpleCommonEvent(getId(), + new TypeName(getData().getType()), d); + } + return new SimpleCommonEvent(getId(), new TypeName(getData().getType()), + d, new TypeName(getMeta().getType()), m); + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Event other)) + return false; + if (id == null) { + return other.id == null; + } else return id.equals(other.id); + } + + + @Override + public String toString() { + return new ToStringBuilder(this).append("id", id).append("data", data) + .append("meta", meta).toString(); + } + + /** + * Creates an event using a common event. + * + * @param selEvent Event to copy. + * @return New instance. + */ + public static Event valueOf(final CommonEvent selEvent) { + + final String dataXml = marshal(selEvent.getData(), selEvent.getData().getClass()); + final Data data = new Data(selEvent.getDataType().asBaseType(), MIME_TYPE, dataXml); + if (selEvent.getMeta() == null) { + return new Event(selEvent.getId(), data); + } + + final String metaXml = marshal(selEvent.getMeta(), selEvent.getMeta().getClass()); + final Data meta = new Data("meta", MIME_TYPE, metaXml); + return new Event(selEvent.getId(), data, meta); + + } + +} diff --git a/api/src/main/java/org/fuin/esc/api/EventIdConverter.java b/test/src/test/java/org/fuin/esc/test/EventIdXmlAdapter.java similarity index 71% rename from api/src/main/java/org/fuin/esc/api/EventIdConverter.java rename to test/src/test/java/org/fuin/esc/test/EventIdXmlAdapter.java index ddebb70e..84eea871 100644 --- a/api/src/main/java/org/fuin/esc/api/EventIdConverter.java +++ b/test/src/test/java/org/fuin/esc/test/EventIdXmlAdapter.java @@ -1,33 +1,35 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.api; +package org.fuin.esc.test; import jakarta.annotation.Nullable; import jakarta.xml.bind.annotation.adapters.XmlAdapter; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.fuin.esc.api.EventId; /** * XML Converter for event IDs. */ -public final class EventIdConverter extends XmlAdapter { +public final class EventIdXmlAdapter extends XmlAdapter { @Override @Nullable - public final EventId unmarshal(@Nullable final String value) throws Exception { + public EventId unmarshal(@Nullable final String value) throws Exception { if (value == null) { return null; } @@ -36,7 +38,7 @@ public final EventId unmarshal(@Nullable final String value) throws Exception { @Override @Nullable - public final String marshal(@Nullable final EventId value) throws Exception { + public String marshal(@Nullable final EventId value) throws Exception { if (value == null) { return null; } diff --git a/api/src/test/java/org/fuin/esc/api/EventIdConverterTest.java b/test/src/test/java/org/fuin/esc/test/EventIdXmlAdapterTest.java similarity index 70% rename from api/src/test/java/org/fuin/esc/api/EventIdConverterTest.java rename to test/src/test/java/org/fuin/esc/test/EventIdXmlAdapterTest.java index 31e1fc33..b223f628 100644 --- a/api/src/test/java/org/fuin/esc/api/EventIdConverterTest.java +++ b/test/src/test/java/org/fuin/esc/test/EventIdXmlAdapterTest.java @@ -1,52 +1,52 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.api; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -// CHECKSTYLE:OFF Test code -public final class EventIdConverterTest { - - private static final String UUID = "f73422c8-2ed9-4613-865d-fa82adf43767"; - - @Test - public final void testMarshalNull() throws Exception { - assertThat(new EventIdConverter().marshal(null)).isNull(); - } - - @Test - public final void testMarshal() throws Exception { - final EventId eventId = new EventId(UUID); - assertThat(new EventIdConverter().marshal(eventId)).isEqualTo(UUID); - } - - @Test - public final void testUnmarshalNull() throws Exception { - assertThat(new EventIdConverter().unmarshal(null)).isNull(); - } - - @Test - public final void testUnmarshal() throws Exception { - final EventId eventId = new EventId(UUID); - assertThat(new EventIdConverter().unmarshal(UUID)).isEqualTo(eventId); - } - -} -// CHECKSTYLE:ON +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.test; + +import org.fuin.esc.api.EventId; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public final class EventIdXmlAdapterTest { + + private static final String UUID = "f73422c8-2ed9-4613-865d-fa82adf43767"; + + @Test + public final void testMarshalNull() throws Exception { + assertThat(new EventIdXmlAdapter().marshal(null)).isNull(); + } + + @Test + public final void testMarshal() throws Exception { + final EventId eventId = new EventId(UUID); + assertThat(new EventIdXmlAdapter().marshal(eventId)).isEqualTo(UUID); + } + + @Test + public final void testUnmarshalNull() throws Exception { + assertThat(new EventIdXmlAdapter().unmarshal(null)).isNull(); + } + + @Test + public final void testUnmarshal() throws Exception { + final EventId eventId = new EventId(UUID); + assertThat(new EventIdXmlAdapter().unmarshal(UUID)).isEqualTo(eventId); + } + +} + diff --git a/spi/src/test/java/org/fuin/esc/spi/EventTest.java b/test/src/test/java/org/fuin/esc/test/EventTest.java similarity index 92% rename from spi/src/test/java/org/fuin/esc/spi/EventTest.java rename to test/src/test/java/org/fuin/esc/test/EventTest.java index 14c6faf7..5e1425cf 100644 --- a/spi/src/test/java/org/fuin/esc/spi/EventTest.java +++ b/test/src/test/java/org/fuin/esc/test/EventTest.java @@ -1,27 +1,28 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.test; import jakarta.xml.bind.annotation.adapters.XmlAdapter; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.EventId; +import org.fuin.esc.jaxb.Data; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -36,7 +37,6 @@ /** * Tests the {@link Event} class. */ -// CHECKSTYLE:OFF Test public class EventTest extends AbstractXmlTest { private static final EventId ID = new EventId(); @@ -103,7 +103,7 @@ public final void testMarshalUnmarshalXML() throws Exception { final Event original = testee; // TEST - final String xml = marshalToStr(original, createXmlAdapter(), Event.class); + final String xml = AbstractXmlTest.marshalToStr(original, createXmlAdapter(), Event.class); // VERIFY final String expectedXml = @@ -127,7 +127,7 @@ public final void testMarshalUnmarshalEquals() throws Exception { final Event original = testee; // TEST - final String xml = marshalToStr(original, createXmlAdapter(), Event.class); + final String xml = AbstractXmlTest.marshalToStr(original, createXmlAdapter(), Event.class); final Event copy = unmarshal(xml, createXmlAdapter(), Event.class); // VERIFY @@ -146,8 +146,8 @@ private void assertEqualsConstantValues(Event ed) { } private XmlAdapter[] createXmlAdapter() { - return new XmlAdapter[] {}; + return new XmlAdapter[]{}; } } -// CHECKSTYLE:ON + diff --git a/spi/src/main/java/org/fuin/esc/spi/Events.java b/test/src/test/java/org/fuin/esc/test/Events.java similarity index 79% rename from spi/src/main/java/org/fuin/esc/spi/Events.java rename to test/src/test/java/org/fuin/esc/test/Events.java index 51f87eba..ef2a7736 100644 --- a/spi/src/main/java/org/fuin/esc/spi/Events.java +++ b/test/src/test/java/org/fuin/esc/test/Events.java @@ -1,120 +1,118 @@ -/** - * Copyright (C) 2015 Michael Schnell. All rights reserved. - * http://www.fuin.org/ - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at your option) any - * later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library. If not, see http://www.gnu.org/licenses/. - */ -package org.fuin.esc.spi; - -import jakarta.validation.constraints.NotNull; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.fuin.esc.api.CommonEvent; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Helper class that allows sending multiple events as XML directly to the event - * store. It a wrapper to allow an XML list of events. This class might be - * useful for tests. It's not used in the 'esc-spi' code itself - */ -@XmlRootElement(name = "events") -public final class Events implements Serializable { - - private static final long serialVersionUID = 1000L; - - @XmlElement(name = "event") - private List events; - - /** - * Default constructor. - */ - public Events() { - super(); - this.events = new ArrayList(); - } - - /** - * Constructor with all data. - * - * @param events - * The events read. The list is internally copied to avoid - */ - public Events(final List events) { - this(); - append(events); - } - - /** - * Appends events to the list. - * - * @param events - * Events to add. - */ - public void append(final List events) { - if (events != null && events.size() > 0) { - this.events.addAll(events); - } - } - - /** - * Appends events to the list. - * - * @param events - * Events to add. - */ - public void append(final Event... events) { - if (events != null && events.length > 0) { - this.events.addAll(EscSpiUtils.asList(events)); - } - } - - /** - * Returns the events read. - * - * @return Unmodifiable list of events. - */ - @NotNull - public List getEvents() { - return Collections.unmodifiableList(events); - } - - /** - * Returns this object as a list of common event objects. - * - * @param ctx - * In case the XML JAXB unmarshalling is used, you have to pass - * the JAXB context here. - * - * @return Converted list. - */ - public List asCommonEvents(final JAXBContext ctx) { - final List list = new ArrayList(); - for (final Event event : events) { - list.add(event.asCommonEvent(ctx)); - } - return list; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("events", events).toString(); - } - -} +/** + * Copyright (C) 2015 Michael Schnell. All rights reserved. + * http://www.fuin.org/ + *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 3 of the License, or (at your option) any + * later version. + *

+ * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see http://www.gnu.org/licenses/. + */ +package org.fuin.esc.test; + +import jakarta.validation.constraints.NotNull; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.spi.EscSpiUtils; + +import java.io.Serial; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Helper class that allows sending multiple events as XML directly to the event + * store. It a wrapper to allow an XML list of events. This class might be + * useful for tests. It's not used in the 'esc-spi' code itself + */ +@XmlRootElement(name = "events") +public final class Events implements Serializable { + + @Serial + private static final long serialVersionUID = 1000L; + + @XmlElement(name = "event") + private List events; + + /** + * Default constructor. + */ + public Events() { + super(); + this.events = new ArrayList<>(); + } + + /** + * Constructor with all data. + * + * @param events The events read. The list is internally copied to avoid + */ + public Events(final List events) { + this(); + append(events); + } + + /** + * Appends events to the list. + * + * @param events Events to add. + */ + public void append(final List events) { + if (events != null && !events.isEmpty()) { + this.events.addAll(events); + } + } + + /** + * Appends events to the list. + * + * @param events Events to add. + */ + public void append(final Event... events) { + if (events != null && events.length > 0) { + this.events.addAll(EscSpiUtils.asList(events)); + } + } + + /** + * Returns the events read. + * + * @return Unmodifiable list of events. + */ + @NotNull + public List getEvents() { + return Collections.unmodifiableList(events); + } + + /** + * Returns this object as a list of common event objects. + * + * @param ctx In case the XML JAXB unmarshalling is used, you have to pass + * the JAXB context here. + * @return Converted list. + */ + public List asCommonEvents(final JAXBContext ctx) { + final List list = new ArrayList<>(); + for (final Event event : events) { + list.add(event.asCommonEvent(ctx)); + } + return list; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("events", events).toString(); + } + +} diff --git a/spi/src/test/java/org/fuin/esc/spi/EventsTest.java b/test/src/test/java/org/fuin/esc/test/EventsTest.java similarity index 69% rename from spi/src/test/java/org/fuin/esc/spi/EventsTest.java rename to test/src/test/java/org/fuin/esc/test/EventsTest.java index 940cc6d6..4ee928fd 100644 --- a/spi/src/test/java/org/fuin/esc/spi/EventsTest.java +++ b/test/src/test/java/org/fuin/esc/test/EventsTest.java @@ -1,45 +1,51 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ -package org.fuin.esc.spi; +package org.fuin.esc.test; import jakarta.xml.bind.annotation.adapters.XmlAdapter; -import org.apache.commons.io.IOUtils; import org.fuin.esc.api.EventId; import org.junit.jupiter.api.Test; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.diff.Diff; -import java.nio.charset.StandardCharsets; - import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; /** * Tests the {@link Events} class. */ -// CHECKSTYLE:OFF Test public class EventsTest extends AbstractXmlTest { @Test public final void testUnMarshal() throws Exception { // PREPARE - final String expectedXml = IOUtils.toString(this.getClass().getResourceAsStream("/events.xml"), StandardCharsets.UTF_8); + final String expectedXml = """ + + + + + + + + + + """; // TEST final Events testee = unmarshal(expectedXml, Events.class); @@ -52,7 +58,7 @@ public final void testUnMarshal() throws Exception { assertThat(testee.getEvents().get(1).getId()).isEqualTo(new EventId("35ae2b63-c820-4cea-8ad6-0d25e4519390")); // TEST - final String xml = marshalToStr(testee, createXmlAdapter(), Events.class); + final String xml = AbstractXmlTest.marshalToStr(testee, createXmlAdapter(), Events.class); // VERIFY final Diff documentDiff = DiffBuilder.compare(expectedXml).withTest(xml).ignoreWhitespace().build(); @@ -61,8 +67,8 @@ public final void testUnMarshal() throws Exception { } private XmlAdapter[] createXmlAdapter() { - return new XmlAdapter[] {}; + return new XmlAdapter[]{}; } - + } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/ReadAllForwardChunk.java b/test/src/test/java/org/fuin/esc/test/ReadAllForwardChunk.java index b516ea64..014657a2 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadAllForwardChunk.java +++ b/test/src/test/java/org/fuin/esc/test/ReadAllForwardChunk.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -66,7 +66,7 @@ public ReadAllForwardChunk() { /** * Constructor for manual creation. - * + * * @param events * Events. */ @@ -82,7 +82,7 @@ public ReadAllForwardChunk(@Nullable final String... events) { /** * Constructor for manual creation. - * + * * @param events * Events. */ @@ -96,7 +96,7 @@ public ReadAllForwardChunk(@Nullable final List events) { /** * Returns a list of expected events. - * + * * @return Event list. */ public final List getEvents() { @@ -147,7 +147,7 @@ public boolean equals(final Object obj) { } private static void addEvent(final List events, - final String eventId) { + final String eventId) { if (eventId != null && UUIDStrValidator.isValid(eventId)) { final CommonEvent ce = new SimpleCommonEvent(new EventId(eventId), BookAddedEvent.TYPE, new BookAddedEvent("Any", "John Doe")); diff --git a/test/src/test/java/org/fuin/esc/test/ReadAllForwardCommand.java b/test/src/test/java/org/fuin/esc/test/ReadAllForwardCommand.java index 81d6f1c0..80b34d85 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadAllForwardCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadAllForwardCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -56,7 +56,7 @@ public final class ReadAllForwardCommand implements TestCommand { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param start @@ -67,8 +67,8 @@ public final class ReadAllForwardCommand implements TestCommand { * Expected chunks. */ public ReadAllForwardCommand(@NotNull final String streamName, - final long start, final int chunkSize, - @NotNull final List chunks) { + final long start, final int chunkSize, + @NotNull final List chunks) { super(); this.streamName = streamName; this.start = start; diff --git a/test/src/test/java/org/fuin/esc/test/ReadBackwardCommand.java b/test/src/test/java/org/fuin/esc/test/ReadBackwardCommand.java index 5fa63303..cc8afedd 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadBackwardCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadBackwardCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -94,7 +94,7 @@ public ReadBackwardCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param start @@ -111,8 +111,8 @@ public ReadBackwardCommand() { * Expected events. */ public ReadBackwardCommand(@NotNull final String streamName, final long start, final int count, - final long fromEventNumber, final long nextEventNumber, final boolean endOfStream, - @Nullable final String... events) { + final long fromEventNumber, final long nextEventNumber, final boolean endOfStream, + @Nullable final String... events) { super(); this.streamName = streamName; this.start = start; @@ -191,10 +191,9 @@ public final String getFailureDescription() { return EscTestUtils.createExceptionFailureMessage(streamId.asString(), actualException); } if (actualSlice == null) { - return "[" + streamId + "] expected " + expectedSlice.toDebugString() + ", but was: null"; + return "[" + streamId + "] expected " + expectedSlice + ", but was: null"; } - return "[" + streamId + "] expected " + expectedSlice.toDebugString() + ", but was: " - + actualSlice.toDebugString(); + return "[" + streamId + "] expected " + expectedSlice + ", but was: " + actualSlice; } @Override diff --git a/test/src/test/java/org/fuin/esc/test/ReadBackwardExceptionCommand.java b/test/src/test/java/org/fuin/esc/test/ReadBackwardExceptionCommand.java index fd54b99c..ee47711b 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadBackwardExceptionCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadBackwardExceptionCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -63,7 +63,7 @@ public ReadBackwardExceptionCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param start @@ -76,7 +76,7 @@ public ReadBackwardExceptionCommand() { * The exception message that is expected, an empty string or "-". */ public ReadBackwardExceptionCommand(@NotNull final String streamName, final long start, final int count, - final String expectedException, final String expectedMessage) { + final String expectedException, final String expectedMessage) { super(); this.streamName = streamName; this.start = start; diff --git a/test/src/test/java/org/fuin/esc/test/ReadEventCommand.java b/test/src/test/java/org/fuin/esc/test/ReadEventCommand.java index ad8c8573..4580a38c 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadEventCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadEventCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -24,7 +24,6 @@ import org.fuin.esc.api.EventStore; import org.fuin.esc.api.SimpleStreamId; import org.fuin.esc.api.StreamId; -import org.fuin.esc.spi.Event; import org.fuin.esc.test.examples.BookAddedEvent; import org.fuin.utils4j.TestCommand; @@ -71,7 +70,7 @@ public ReadEventCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to read. * @param eventNumber @@ -82,8 +81,8 @@ public ReadEventCommand() { * The exception that is expected, an empty string or "-". */ public ReadEventCommand(@NotNull final String streamName, - final long eventNumber, final String expectedEventXml, - final String expectedException) { + final long eventNumber, final String expectedEventXml, + final String expectedException) { super(); this.streamName = streamName; this.eventNumber = eventNumber; diff --git a/test/src/test/java/org/fuin/esc/test/ReadForwardCommand.java b/test/src/test/java/org/fuin/esc/test/ReadForwardCommand.java index 2f3510e4..16973c20 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadForwardCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadForwardCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -94,7 +94,7 @@ public ReadForwardCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param start @@ -111,8 +111,8 @@ public ReadForwardCommand() { * Expected events. */ public ReadForwardCommand(@NotNull final String streamName, final long start, final int count, - final long fromEventNumber, final long nextEventNumber, final boolean endOfStream, - @Nullable final String... events) { + final long fromEventNumber, final long nextEventNumber, final boolean endOfStream, + @Nullable final String... events) { super(); this.streamName = streamName; this.start = start; @@ -191,10 +191,9 @@ public final String getFailureDescription() { return EscTestUtils.createExceptionFailureMessage(streamId.asString(), actualException); } if (actualSlice == null) { - return "[" + streamId + "] expected " + expectedSlice.toDebugString() + ", but was: null"; + return "[" + streamId + "] expected " + expectedSlice + ", but was: null"; } - return "[" + streamId + "] expected " + expectedSlice.toDebugString() + ", but was: " - + actualSlice.toDebugString(); + return "[" + streamId + "] expected " + expectedSlice + ", but was: " + actualSlice; } @Override diff --git a/test/src/test/java/org/fuin/esc/test/ReadForwardExceptionCommand.java b/test/src/test/java/org/fuin/esc/test/ReadForwardExceptionCommand.java index 2ba0d476..31bd935f 100644 --- a/test/src/test/java/org/fuin/esc/test/ReadForwardExceptionCommand.java +++ b/test/src/test/java/org/fuin/esc/test/ReadForwardExceptionCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -62,7 +62,7 @@ public ReadForwardExceptionCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param start @@ -75,7 +75,7 @@ public ReadForwardExceptionCommand() { * The exception message that is expected, an empty string or "-". */ public ReadForwardExceptionCommand(@NotNull final String streamName, final long start, final int count, - final String expectedException, final String expectedMessage) { + final String expectedException, final String expectedMessage) { super(); this.streamName = streamName; this.start = start; diff --git a/test/src/test/java/org/fuin/esc/test/Slice.java b/test/src/test/java/org/fuin/esc/test/Slice.java index 14cb1518..3a21daf7 100644 --- a/test/src/test/java/org/fuin/esc/test/Slice.java +++ b/test/src/test/java/org/fuin/esc/test/Slice.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -31,8 +31,8 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.fuin.esc.api.CommonEvent; import org.fuin.esc.api.StreamEventsSlice; -import org.fuin.esc.spi.Event; -import org.fuin.objects4j.common.Immutable; + +import javax.annotation.concurrent.Immutable; /** * A slice of data from a stream. @@ -64,7 +64,7 @@ protected Slice() { /** * Constructor with all data. - * + * * @param fromEventNumber * The starting point (represented as a sequence number) of the * read. @@ -77,7 +77,7 @@ protected Slice() { * Determines whether or not this is the end of the stream. */ public Slice(final long fromEventNumber, final List events, - final long nextEventNumber, final boolean endOfStream) { + final long nextEventNumber, final boolean endOfStream) { this.fromEventNumber = fromEventNumber; if (events == null || events.size() == 0) { @@ -92,7 +92,7 @@ public Slice(final long fromEventNumber, final List events, /** * Returns the starting point (represented as a sequence number) of the read * operation. - * + * * @return Event number. */ public long getFromEventNumber() { @@ -101,7 +101,7 @@ public long getFromEventNumber() { /** * Returns the events read. - * + * * @return Unmodifiable list of events. */ @NotNull @@ -111,7 +111,7 @@ public List getEvents() { /** * Returns the next event number that can be read. - * + * * @return Next event number. */ public long getNextEventNumber() { @@ -121,22 +121,21 @@ public long getNextEventNumber() { /** * Returns a boolean representing whether or not this is the end of the * stream. - * + * * @return TRUE if this is the end of the stream, else FALSE. */ public boolean isEndOfStream() { return endOfStream; } - // CHECKSTYLE:OFF Generated code @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + (endOfStream ? 1231 : 1237); - result = prime * result + (int) (fromEventNumber ^ (fromEventNumber >>> 32)); - result = prime * result + (int) (nextEventNumber ^ (nextEventNumber >>> 32)); + result = prime * result + (int) (fromEventNumber ^ (fromEventNumber >>> 32)); + result = prime * result + (int) (nextEventNumber ^ (nextEventNumber >>> 32)); result = prime * result + ((events == null) ? 0 : Arrays.hashCode(events.toArray())); return result; @@ -172,7 +171,6 @@ public final boolean equals(Object obj) { return true; } - // CHECKSTYLE:ON @Override public String toString() { @@ -185,10 +183,10 @@ public String toString() { /** * Creates a slice from a stream event slice. - * + * * @param sel * Slice to copy. - * + * * @return Copied information with changed type. */ public static Slice valueOf(final StreamEventsSlice sel) { diff --git a/test/src/test/java/org/fuin/esc/test/SliceTest.java b/test/src/test/java/org/fuin/esc/test/SliceTest.java index b6702ecb..4ae01aab 100644 --- a/test/src/test/java/org/fuin/esc/test/SliceTest.java +++ b/test/src/test/java/org/fuin/esc/test/SliceTest.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -28,9 +28,8 @@ import jakarta.xml.bind.annotation.adapters.XmlAdapter; import org.fuin.esc.api.EventId; -import org.fuin.esc.spi.Data; +import org.fuin.esc.jaxb.Data; import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.Event; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,7 +41,6 @@ /** * Tests the {@link Slice} class. */ -// CHECKSTYLE:OFF Test public class SliceTest extends AbstractXmlTest { private static final EventId ID = new EventId(); @@ -138,8 +136,8 @@ public final void testMarshalUnmarshalEquals() throws Exception { } private XmlAdapter[] createXmlAdapter() { - return new XmlAdapter[] {}; + return new XmlAdapter[]{}; } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/Slices.java b/test/src/test/java/org/fuin/esc/test/Slices.java index eb706306..4a0f2bf4 100644 --- a/test/src/test/java/org/fuin/esc/test/Slices.java +++ b/test/src/test/java/org/fuin/esc/test/Slices.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -50,7 +50,7 @@ public Slices() { /** * Constructor with all data. - * + * * @param slices * The slices read. The list is internally copied to avoid */ @@ -61,7 +61,7 @@ public Slices(final List slices) { /** * Appends slices to the list. - * + * * @param slices * Slices to add. */ @@ -73,7 +73,7 @@ public void append(final List slices) { /** * Appends slices to the list. - * + * * @param slices * Slices to add. */ @@ -85,7 +85,7 @@ public void append(final Slice... slices) { /** * Returns the slices read. - * + * * @return Unmodifiable list of slices. */ @NotNull diff --git a/test/src/test/java/org/fuin/esc/test/StreamExistsCommand.java b/test/src/test/java/org/fuin/esc/test/StreamExistsCommand.java index 47439044..16f2847a 100644 --- a/test/src/test/java/org/fuin/esc/test/StreamExistsCommand.java +++ b/test/src/test/java/org/fuin/esc/test/StreamExistsCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -56,7 +56,7 @@ public StreamExistsCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param shouldExist diff --git a/test/src/test/java/org/fuin/esc/test/StreamStateCommand.java b/test/src/test/java/org/fuin/esc/test/StreamStateCommand.java index aed39b6c..fdaa22f2 100644 --- a/test/src/test/java/org/fuin/esc/test/StreamStateCommand.java +++ b/test/src/test/java/org/fuin/esc/test/StreamStateCommand.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -63,7 +63,7 @@ public StreamStateCommand() { /** * Constructor for manual creation. - * + * * @param streamName * Uniquely identifies the stream to create. * @param expectedState @@ -72,7 +72,7 @@ public StreamStateCommand() { * The exception that is expected, an empty string or "-". */ public StreamStateCommand(@NotNull final String streamName, final String expectedState, - final String expectedException) { + final String expectedException) { super(); this.streamName = streamName; this.expectedState = expectedState; diff --git a/test/src/test/java/org/fuin/esc/test/TestContext.java b/test/src/test/java/org/fuin/esc/test/TestContext.java index 3da3bcb3..e7025890 100644 --- a/test/src/test/java/org/fuin/esc/test/TestContext.java +++ b/test/src/test/java/org/fuin/esc/test/TestContext.java @@ -17,12 +17,10 @@ public final class TestContext { /** * Constructor with mandatory data. - * - * @param currentEventStoreImplType - * Type name of the currently tested event store implementation. Will be used to prefix the stream names to avoid name - * clashes for multiple implementations for the same backend store. - * @param eventStore - * Event store to use. + * + * @param currentEventStoreImplType Type name of the currently tested event store implementation. Will be used to prefix the stream names to avoid name + * clashes for multiple implementations for the same backend store. + * @param eventStore Event store to use. */ public TestContext(@NotNull String currentEventStoreImplType, @NotNull EventStore eventStore) { super(); @@ -32,8 +30,8 @@ public TestContext(@NotNull String currentEventStoreImplType, @NotNull EventStor /** * Returns the type name of the currently tested event store implementation. Will be used to prefix the stream names to avoid name - * clashes for multiple implementations for the same backend store. - * + * clashes for multiple implementations for the same backend store. + * * @return Type name. */ public final String getCurrentEventStoreImplType() { @@ -42,13 +40,12 @@ public final String getCurrentEventStoreImplType() { /** * Returns the event store to use. - * + * * @return Event store. */ public final EventStore getEventStore() { return eventStore; } - - + } diff --git a/test/src/test/java/org/fuin/esc/test/TestFeatures.java b/test/src/test/java/org/fuin/esc/test/TestFeatures.java index 0d5335a6..36f82049 100644 --- a/test/src/test/java/org/fuin/esc/test/TestFeatures.java +++ b/test/src/test/java/org/fuin/esc/test/TestFeatures.java @@ -1,17 +1,17 @@ /** - * Copyright (C) 2015 Michael Schnell. All rights reserved. + * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ - * + *

* This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. - * + *

* This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. - * + *

* You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ @@ -35,33 +35,35 @@ import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; +import org.eclipse.yasson.FieldAccessStrategy; import org.fuin.esc.api.CommonEvent; import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.EventId; import org.fuin.esc.api.EventStore; import org.fuin.esc.api.ExpectedVersion; -import org.fuin.esc.api.JsonDeSerializer; import org.fuin.esc.api.SerializedDataType; import org.fuin.esc.api.SimpleCommonEvent; +import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; import org.fuin.esc.esgrpc.ESGrpcEventStore; +import org.fuin.esc.jaxb.Base64Data; +import org.fuin.esc.jaxb.EscEvent; +import org.fuin.esc.jaxb.EscEvents; +import org.fuin.esc.jaxb.EscMeta; +import org.fuin.esc.jaxb.XmlDeSerializer; import org.fuin.esc.jpa.JpaEventStore; +import org.fuin.esc.jsonb.EscJsonbUtils; +import org.fuin.esc.jsonb.JsonbDeSerializer; import org.fuin.esc.mem.InMemoryEventStore; -import org.fuin.esc.spi.Base64Data; -import org.fuin.esc.spi.EscEvent; -import org.fuin.esc.spi.EscEvents; -import org.fuin.esc.spi.EscMeta; -import org.fuin.esc.spi.Events; import org.fuin.esc.spi.TextDeSerializer; -import org.fuin.esc.spi.XmlDeSerializer; import org.fuin.esc.test.examples.BookAddedEvent; import org.fuin.esc.test.examples.MyMeta; import org.fuin.esc.test.jpa.TestIdStreamFactory; import org.fuin.utils4j.MultipleCommands; import org.fuin.utils4j.TestCommand; -import java.net.MalformedURLException; -import java.nio.charset.Charset; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -71,349 +73,378 @@ import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; -// CHECKSTYLE:OFF Test code + public class TestFeatures { - private TestContext testContext; - - private SimpleSerializerDeserializerRegistry registry; - - private TestCommand lastCommand; - - private EntityManagerFactory emf; - - private EntityManager em; - - private Connection connection; - - @Before - public void beforeFeature() throws MalformedURLException { - - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "changeit"); - credentialsProvider.setCredentials(AuthScope.ANY, credentials); - - // Use the property to select the correct implementation: - final String currentEventStoreImplType = System.getProperty(EscCucumber.SYSTEM_PROPERTY); - final EventStore eventStore; - if (currentEventStoreImplType.equals("mem")) { - eventStore = new InMemoryEventStore(Executors.newCachedThreadPool()); - } else if (currentEventStoreImplType.equals("eshttp") || currentEventStoreImplType.equals("jpa") - || currentEventStoreImplType.equals("esjc") || currentEventStoreImplType.equals("esgrpc")) { - final XmlDeSerializer xmlDeSer = new XmlDeSerializer(false, BookAddedEvent.class, MyMeta.class, - EscEvent.class, EscEvents.class, EscMeta.class, Base64Data.class); - final JsonDeSerializer jsonDeSer = new JsonDeSerializer(); - final TextDeSerializer textDeSer = new TextDeSerializer(); - registry = new SimpleSerializerDeserializerRegistry(); - registry.add(new SerializedDataType(BookAddedEvent.TYPE.asBaseType()), "application/xml", xmlDeSer); - registry.add(new SerializedDataType(MyMeta.TYPE.asBaseType()), "application/json", jsonDeSer); - registry.add(new SerializedDataType(Base64Data.TYPE.asBaseType()), "application/xml", xmlDeSer); - registry.add(new SerializedDataType(EscEvent.TYPE.asBaseType()), "application/xml", xmlDeSer); - registry.add(new SerializedDataType(EscEvents.TYPE.asBaseType()), "application/xml", xmlDeSer); - registry.add(new SerializedDataType(EscMeta.TYPE.asBaseType()), "application/xml", xmlDeSer); - registry.add(new SerializedDataType("TextEvent"), "text/plain", textDeSer); - if (currentEventStoreImplType.equals("jpa")) { - setupDb(); - eventStore = new JpaEventStore(em, new TestIdStreamFactory(), registry, registry); - } else if (currentEventStoreImplType.equals("esgrpc")) { - final EventStoreDBClientSettings setts = EventStoreDBConnectionString - .parseOrThrow("esdb://localhost:2113?tls=false"); - final EventStoreDBClient client = EventStoreDBClient.create(setts); - eventStore = new ESGrpcEventStore.Builder().eventStore(client).serDesRegistry(registry) - .targetContentType(EnhancedMimeType.create("application", "xml", Charset.forName("utf-8"))) - .build(); - } else { - throw new IllegalStateException("Unknown type: " + currentEventStoreImplType); - } - } else { - throw new IllegalStateException("Unknown type: " + currentEventStoreImplType); - } - eventStore.open(); - testContext = new TestContext(currentEventStoreImplType, eventStore); - lastCommand = null; - } - - @After - public void afterFeature() { - if (testContext != null) { - testContext.getEventStore().close(); - teardownDb(); - testContext = null; - } - if (lastCommand != null) { - throw new IllegalStateException("Last command was set, but not verified!"); - } - } - - @Then("^this should give the expected results$") - public void success() { - verifyThen(); - } - - @Then("^this should raise no exception$") - public void thenNoException() { - verifyThen(); - } - - @When("^the following deletes are executed$") - public void whenExecuteDeletes(final List commands) { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeWhen(command); - } - - @Given("^the following streams are created and a single event is appended to each$") - public void givenCreateStreamsAndAppendSomeEvent(final List streams) { - - final MultipleCommands command = new MultipleCommands(); - - for (int i = 1; i < streams.size(); i++) { - final String streamName = streams.get(i); - command.add(new CreateStreamCommand(streamName)); - final CommonEvent event = new SimpleCommonEvent(new EventId(), BookAddedEvent.TYPE, - new BookAddedEvent("Unknown", "John Doe")); - command.add(new AppendToStreamCommand(streamName, ExpectedVersion.ANY.getNo(), null, event)); - } - - command.init(testContext); - executeGiven(command); - - } - - @Given("^the following streams don't exist$") - public void givenStreamsDontExist(final List streams) { - final MultipleCommands command = new MultipleCommands(); - for (int i = 1; i < streams.size(); i++) { - final String streamName = streams.get(i); - command.add(new StreamExistsCommand(streamName, false)); - } - command.init(testContext); - executeGiven(command); - } - - @Then("^following streams should not exist$") - public void thenStreamsShouldNotExist(final List streams) { - final MultipleCommands command = new MultipleCommands(); - for (int i = 1; i < streams.size(); i++) { - final String streamName = streams.get(i); - command.add(new StreamExistsCommand(streamName, false)); - } - command.init(testContext); - executeThen(command); - } - - @Then("^reading forward from the following streams should raise the given exceptions$") - public void thenReadForwardException(final List commands) throws Exception { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeThen(command); - } - - @When("^I read forward from the following streams$") - public void whenReadForwardException(final List commands) { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeWhen(command); - } - - @When("^I read backward from the following streams$") - public void whenReadBackwardException(final List commands) { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeWhen(command); - } - - @Given("^the stream \"(.*?)\" does not exist$") - public void givenStreamDoesNotExist(final String streamName) { - final TestCommand command = new StreamExistsCommand(streamName, false); - command.init(testContext); - executeGiven(command); - } - - @When("^I append the following events in the given order$") - public void whenAppendEvents(final List commands) { - final MultipleCommands command = new MultipleCommands(); - for (final AppendToStreamCommand cmd : commands) { - command.add(cmd); - } - command.init(testContext); - executeWhen(command); - } - - @Then("^reading forward from stream should have the following results$") - public void thenReadForward(final List commands) throws Exception { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeThen(command); - } - - @Then("^reading backward from stream should have the following results$") - public void thenReadBackward(final List commands) throws Exception { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeThen(command); - } - - @When("^I append the following events to stream \"(.*?)\"$") - public void whenAppendXmlEvents(final String streamName, final String eventsXml) { - whenAppendXmlEvents(streamName, ExpectedVersion.ANY.getNo(), eventsXml); - } - - private void whenAppendXmlEvents(final String streamName, final long version, final String eventsXml) { - final Events events = unmarshal(eventsXml, Events.class); - final List commonEvents = events.asCommonEvents(createCtx()); - - final TestCommand command = new AppendToStreamCommand(streamName, version, null, commonEvents); - command.init(testContext); - executeWhen(command); - } - - @Then("^reading event (\\d+) from stream \"(.*?)\" should return the following event$") - public void thenReadXmlEvent(final long eventNumber, final String streamName, final String expectedEventXml) { - - final TestCommand command = new ReadEventCommand(streamName, eventNumber, expectedEventXml, null); - command.init(testContext); - executeThen(command); - - } - - @Then("^reading event (\\d+) from stream \"(.*?)\" should throw a \"(.*?)\"$") - public void thenReadingEventShouldThrow_a(long eventNumber, String streamName, String expectedException) { - final TestCommand command = new ReadEventCommand(streamName, eventNumber, null, expectedException); - command.init(testContext); - executeThen(command); - } - - @When("^the following state queries are executed$") - public void whenStateQueriesAreExecuted(final List commands) { - final TestCommand command = new MultipleCommands(commands); - command.init(testContext); - executeWhen(command); - } - - @Given("^the following streams exist$") - public void givenStreamsExist(final List streams) { - final MultipleCommands command = new MultipleCommands(); - for (int i = 1; i < streams.size(); i++) { - final String streamName = streams.get(i); - command.add(new StreamExistsCommand(streamName, true)); - } - command.init(testContext); - executeGiven(command); - - } - - @Then("^following streams should exist$") - public void thenStreamsShouldExist(final List streams) { - final MultipleCommands command = new MultipleCommands(); - for (int i = 1; i < streams.size(); i++) { - final String streamName = streams.get(i); - command.add(new StreamExistsCommand(streamName, true)); - } - command.init(testContext); - executeThen(command); - } - - @Then("^reading all events from stream \"(.*?)\" starting at position (\\d+) with chunk size (\\d+) should have the following results$") - public void thenReadingAllEventsFromStream(final String streamName, final long startAtEventNo, final int chunkSize, - final List expectedChunks) { - - final TestCommand command = new ReadAllForwardCommand(streamName, startAtEventNo, chunkSize, - expectedChunks); - command.init(testContext); - executeThen(command); - - } - - private void setupDb() { - try { - emf = Persistence.createEntityManagerFactory("testPU"); - em = emf.createEntityManager(); - final Map props = emf.getProperties(); - final boolean shutdown = Boolean.valueOf("" + props.get("esctest.shutdown")); - if (shutdown) { - final String connUrl = "" + props.get("esctest.url"); - final String connUsername = "" + props.get("esctest.user"); - final String connPassword = "" + props.get("esctest.pw"); - connection = DriverManager.getConnection(connUrl, connUsername, connPassword); - } - } catch (final SQLException ex) { - throw new RuntimeException(ex); - } - } - - private void teardownDb() { - if (em != null) { - em.close(); - } - if (emf != null) { - emf.close(); - } - try { - if (connection != null) { - connection.createStatement().execute("SHUTDOWN"); - } - } catch (final SQLException ex) { - throw new RuntimeException(ex); - } - } - - private void executeGiven(TestCommand command) { - beginTransaction(); - command.execute(); - endTransaction(); - command.verify(); - } - - private void executeWhen(TestCommand command) { - lastCommand = command; - beginTransaction(); - command.execute(); - endTransaction(); - } - - private void executeThen(TestCommand command) { - lastCommand = null; - beginTransaction(); - command.execute(); - endTransaction(); - command.verify(); - } - - private void verifyThen() { - if (lastCommand == null) { - throw new IllegalStateException("Last command was not set in the 'when' condition"); - } - lastCommand.verify(); - lastCommand = null; - } - - private void beginTransaction() { - if (em != null) { - em.getTransaction().begin(); - } - } - - private void endTransaction() { - if (em != null) { - final EntityTransaction transaction = em.getTransaction(); - if (transaction.isActive()) { - if (transaction.getRollbackOnly()) { - transaction.rollback(); - } else { - transaction.commit(); - } - } - } - } - - private JAXBContext createCtx() { - try { - return JAXBContext.newInstance(BookAddedEvent.class); - } catch (final JAXBException ex) { - throw new RuntimeException(ex); - } - } + private static final Class[] JAXB_CLASSES = new Class[]{ + BookAddedEvent.class, + EscEvent.class, + EscEvents.class, + EscMeta.class, + Base64Data.class + }; + + private TestContext testContext; + + private TestCommand lastCommand; + + private EntityManagerFactory emf; + + private EntityManager em; + + private Connection connection; + + @Before + public void beforeFeature() throws IOException { + + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "changeit"); + credentialsProvider.setCredentials(AuthScope.ANY, credentials); + + // Use the property to select the correct implementation: + final String currentEventStoreImplType = System.getProperty(EscCucumber.SYSTEM_PROPERTY); + final EventStore eventStore; + if (currentEventStoreImplType.equals("mem")) { + eventStore = new InMemoryEventStore(Executors.newCachedThreadPool()); + } else if (currentEventStoreImplType.equals("jpa") || currentEventStoreImplType.equals("esgrpc")) { + + final XmlDeSerializer xmlDeSer = new XmlDeSerializer(false, JAXB_CLASSES); + final SimpleSerializedDataTypeRegistry typeRegistry = createTypeRegistry(); + try (final JsonbDeSerializer jsonbDeSer = createJsonbDeSerializer()) { + jsonbDeSer.init(typeRegistry); + + final TextDeSerializer textDeSer = new TextDeSerializer(); + SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + registry.add(new SerializedDataType(BookAddedEvent.TYPE.asBaseType()), "application/xml", xmlDeSer); + registry.add(new SerializedDataType(MyMeta.TYPE.asBaseType()), "application/json", jsonbDeSer); + registry.add(new SerializedDataType(Base64Data.TYPE.asBaseType()), "application/xml", xmlDeSer); + registry.add(new SerializedDataType(EscEvent.TYPE.asBaseType()), "application/xml", xmlDeSer); + registry.add(new SerializedDataType(EscEvents.TYPE.asBaseType()), "application/xml", xmlDeSer); + registry.add(new SerializedDataType(EscMeta.TYPE.asBaseType()), "application/xml", xmlDeSer); + registry.add(new SerializedDataType("TextEvent"), "text/plain", textDeSer); + if (currentEventStoreImplType.equals("jpa")) { + setupDb(); + eventStore = new JpaEventStore(em, new TestIdStreamFactory(), registry, registry); + } else { + final EventStoreDBClientSettings setts = EventStoreDBConnectionString + .parseOrThrow("esdb://localhost:2113?tls=false"); + final EventStoreDBClient client = EventStoreDBClient.create(setts); + eventStore = new ESGrpcEventStore.Builder().eventStore(client).serDesRegistry(registry) + .targetContentType(EnhancedMimeType.create("application", "xml", StandardCharsets.UTF_8)) + .build(); + } + + } + + } else { + throw new IllegalStateException("Unknown type: " + currentEventStoreImplType); + } + eventStore.open(); + testContext = new TestContext(currentEventStoreImplType, eventStore); + lastCommand = null; + } + + @After + public void afterFeature() { + if (testContext != null) { + testContext.getEventStore().close(); + teardownDb(); + testContext = null; + } + if (lastCommand != null) { + throw new IllegalStateException("Last command was set, but not verified!"); + } + } + + @Then("^this should give the expected results$") + public void success() { + verifyThen(); + } + + @Then("^this should raise no exception$") + public void thenNoException() { + verifyThen(); + } + + @When("^the following deletes are executed$") + public void whenExecuteDeletes(final List commands) { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeWhen(command); + } + + @Given("^the following streams are created and a single event is appended to each$") + public void givenCreateStreamsAndAppendSomeEvent(final List streams) { + + final MultipleCommands command = new MultipleCommands(); + + for (int i = 1; i < streams.size(); i++) { + final String streamName = streams.get(i); + command.add(new CreateStreamCommand(streamName)); + final CommonEvent event = new SimpleCommonEvent(new EventId(), BookAddedEvent.TYPE, + new BookAddedEvent("Unknown", "John Doe")); + command.add(new AppendToStreamCommand(streamName, ExpectedVersion.ANY.getNo(), null, event)); + } + + command.init(testContext); + executeGiven(command); + + } + + @Given("^the following streams don't exist$") + public void givenStreamsDontExist(final List streams) { + final MultipleCommands command = new MultipleCommands(); + for (int i = 1; i < streams.size(); i++) { + final String streamName = streams.get(i); + command.add(new StreamExistsCommand(streamName, false)); + } + command.init(testContext); + executeGiven(command); + } + + @Then("^following streams should not exist$") + public void thenStreamsShouldNotExist(final List streams) { + final MultipleCommands command = new MultipleCommands(); + for (int i = 1; i < streams.size(); i++) { + final String streamName = streams.get(i); + command.add(new StreamExistsCommand(streamName, false)); + } + command.init(testContext); + executeThen(command); + } + + @Then("^reading forward from the following streams should raise the given exceptions$") + public void thenReadForwardException(final List commands) throws Exception { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeThen(command); + } + + @When("^I read forward from the following streams$") + public void whenReadForwardException(final List commands) { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeWhen(command); + } + + @When("^I read backward from the following streams$") + public void whenReadBackwardException(final List commands) { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeWhen(command); + } + + @Given("^the stream \"(.*?)\" does not exist$") + public void givenStreamDoesNotExist(final String streamName) { + final TestCommand command = new StreamExistsCommand(streamName, false); + command.init(testContext); + executeGiven(command); + } + + @When("^I append the following events in the given order$") + public void whenAppendEvents(final List commands) { + final MultipleCommands command = new MultipleCommands(); + for (final AppendToStreamCommand cmd : commands) { + command.add(cmd); + } + command.init(testContext); + executeWhen(command); + } + + @Then("^reading forward from stream should have the following results$") + public void thenReadForward(final List commands) throws Exception { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeThen(command); + } + + @Then("^reading backward from stream should have the following results$") + public void thenReadBackward(final List commands) throws Exception { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeThen(command); + } + + @When("^I append the following events to stream \"(.*?)\"$") + public void whenAppendXmlEvents(final String streamName, final String eventsXml) { + whenAppendXmlEvents(streamName, ExpectedVersion.ANY.getNo(), eventsXml); + } + + private void whenAppendXmlEvents(final String streamName, final long version, final String eventsXml) { + final Events events = unmarshal(eventsXml, Events.class); + final List commonEvents = events.asCommonEvents(createCtx()); + + final TestCommand command = new AppendToStreamCommand(streamName, version, null, commonEvents); + command.init(testContext); + executeWhen(command); + } + + @Then("^reading event (\\d+) from stream \"(.*?)\" should return the following event$") + public void thenReadXmlEvent(final long eventNumber, final String streamName, final String expectedEventXml) { + + final TestCommand command = new ReadEventCommand(streamName, eventNumber, expectedEventXml, null); + command.init(testContext); + executeThen(command); + + } + + @Then("^reading event (\\d+) from stream \"(.*?)\" should throw a \"(.*?)\"$") + public void thenReadingEventShouldThrow_a(long eventNumber, String streamName, String expectedException) { + final TestCommand command = new ReadEventCommand(streamName, eventNumber, null, expectedException); + command.init(testContext); + executeThen(command); + } + + @When("^the following state queries are executed$") + public void whenStateQueriesAreExecuted(final List commands) { + final TestCommand command = new MultipleCommands(commands); + command.init(testContext); + executeWhen(command); + } + + @Given("^the following streams exist$") + public void givenStreamsExist(final List streams) { + final MultipleCommands command = new MultipleCommands(); + for (int i = 1; i < streams.size(); i++) { + final String streamName = streams.get(i); + command.add(new StreamExistsCommand(streamName, true)); + } + command.init(testContext); + executeGiven(command); + + } + + @Then("^following streams should exist$") + public void thenStreamsShouldExist(final List streams) { + final MultipleCommands command = new MultipleCommands(); + for (int i = 1; i < streams.size(); i++) { + final String streamName = streams.get(i); + command.add(new StreamExistsCommand(streamName, true)); + } + command.init(testContext); + executeThen(command); + } + + @Then("^reading all events from stream \"(.*?)\" starting at position (\\d+) with chunk size (\\d+) should have the following results$") + public void thenReadingAllEventsFromStream(final String streamName, final long startAtEventNo, final int chunkSize, + final List expectedChunks) { + + final TestCommand command = new ReadAllForwardCommand(streamName, startAtEventNo, chunkSize, + expectedChunks); + command.init(testContext); + executeThen(command); + + } + + private void setupDb() { + try { + emf = Persistence.createEntityManagerFactory("testPU"); + em = emf.createEntityManager(); + final Map props = emf.getProperties(); + final boolean shutdown = Boolean.valueOf("" + props.get("esctest.shutdown")); + if (shutdown) { + final String connUrl = "" + props.get("esctest.url"); + final String connUsername = "" + props.get("esctest.user"); + final String connPassword = "" + props.get("esctest.pw"); + connection = DriverManager.getConnection(connUrl, connUsername, connPassword); + } + } catch (final SQLException ex) { + throw new RuntimeException(ex); + } + } + + private void teardownDb() { + if (em != null) { + em.close(); + } + if (emf != null) { + emf.close(); + } + try { + if (connection != null) { + connection.createStatement().execute("SHUTDOWN"); + } + } catch (final SQLException ex) { + throw new RuntimeException(ex); + } + } + + private void executeGiven(TestCommand command) { + beginTransaction(); + command.execute(); + endTransaction(); + command.verify(); + } + + private void executeWhen(TestCommand command) { + lastCommand = command; + beginTransaction(); + command.execute(); + endTransaction(); + } + + private void executeThen(TestCommand command) { + lastCommand = null; + beginTransaction(); + command.execute(); + endTransaction(); + command.verify(); + } + + private void verifyThen() { + if (lastCommand == null) { + throw new IllegalStateException("Last command was not set in the 'when' condition"); + } + lastCommand.verify(); + lastCommand = null; + } + + private void beginTransaction() { + if (em != null) { + em.getTransaction().begin(); + } + } + + private void endTransaction() { + if (em != null) { + final EntityTransaction transaction = em.getTransaction(); + if (transaction.isActive()) { + if (transaction.getRollbackOnly()) { + transaction.rollback(); + } else { + transaction.commit(); + } + } + } + } + + private JAXBContext createCtx() { + try { + return JAXBContext.newInstance(BookAddedEvent.class); + } catch (final JAXBException ex) { + throw new RuntimeException(ex); + } + } + + private static SimpleSerializedDataTypeRegistry createTypeRegistry() { + final SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + typeRegistry.add(EscMeta.SER_TYPE, EscMeta.class); + typeRegistry.add(EscEvent.SER_TYPE, EscEvent.class); + typeRegistry.add(EscEvents.SER_TYPE, EscEvents.class); + typeRegistry.add(Base64Data.SER_TYPE, Base64Data.class); + typeRegistry.add(BookAddedEvent.SER_TYPE, BookAddedEvent.class); + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + return typeRegistry; + } + + private static JsonbDeSerializer createJsonbDeSerializer() { + return JsonbDeSerializer.builder() + .withSerializers(EscJsonbUtils.createEscJsonbSerializers()) + .withDeserializers(EscJsonbUtils.createEscJsonbDeserializers()) + .withPropertyVisibilityStrategy(new FieldAccessStrategy()) + .withEncoding(StandardCharsets.UTF_8) + .build(); + } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/TestUtils.java b/test/src/test/java/org/fuin/esc/test/TestUtils.java index 070c1a0d..baf6edd9 100644 --- a/test/src/test/java/org/fuin/esc/test/TestUtils.java +++ b/test/src/test/java/org/fuin/esc/test/TestUtils.java @@ -30,13 +30,9 @@ public static boolean isExpectedType(final Class expectedClass, final Object /** * Determines if an exception has an expected type and message in a null-safe way. * - * @param expectedClass - * Expected exception type. - * @param expectedMessage - * Expected message. - * @param ex - * Exception to test. - * + * @param expectedClass Expected exception type. + * @param expectedMessage Expected message. + * @param ex Exception to test. * @return TRUE if the object is exactly of the same class and has the same message, else FALSE. */ public static boolean isExpectedException(final Class expectedClass, diff --git a/test/src/test/java/org/fuin/esc/test/examples/BookAddedEvent.java b/test/src/test/java/org/fuin/esc/test/examples/BookAddedEvent.java index e7253751..19d78b47 100644 --- a/test/src/test/java/org/fuin/esc/test/examples/BookAddedEvent.java +++ b/test/src/test/java/org/fuin/esc/test/examples/BookAddedEvent.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.examples; import jakarta.xml.bind.annotation.XmlElement; @@ -12,10 +11,14 @@ @XmlRootElement(name = "book-added-event") public class BookAddedEvent { - /** Never changing unique event type name. */ + /** + * Never changing unique event type name. + */ public static final TypeName TYPE = new TypeName("BookAddedEvent"); - - /** Unique name of the serialized type. */ + + /** + * Unique name of the serialized type. + */ public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); @XmlElement @@ -33,11 +36,9 @@ protected BookAddedEvent() { /** * Constructor with name and author. - * - * @param name - * Name. - * @param author - * Author. + * + * @param name Name. + * @param author Author. */ public BookAddedEvent(final String name, final String author) { super(); @@ -103,4 +104,4 @@ public final String toString() { } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/examples/EsGrpcJsonbExample.java b/test/src/test/java/org/fuin/esc/test/examples/EsGrpcJsonbExample.java index eb338326..2c1bab1a 100644 --- a/test/src/test/java/org/fuin/esc/test/examples/EsGrpcJsonbExample.java +++ b/test/src/test/java/org/fuin/esc/test/examples/EsGrpcJsonbExample.java @@ -1,149 +1,149 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.examples; -import java.net.MalformedURLException; -import java.nio.charset.Charset; - +import com.eventstore.dbclient.EventStoreDBClient; +import com.eventstore.dbclient.EventStoreDBClientSettings; +import com.eventstore.dbclient.EventStoreDBConnectionString; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.eclipse.yasson.FieldAccessStrategy; import org.fuin.esc.api.CommonEvent; +import org.fuin.esc.api.EnhancedMimeType; import org.fuin.esc.api.EventId; import org.fuin.esc.api.EventStore; import org.fuin.esc.api.ExpectedVersion; -import org.fuin.esc.api.SimpleCommonEvent; -import org.fuin.esc.api.SimpleStreamId; -import org.fuin.esc.api.StreamId; -import org.fuin.esc.esgrpc.ESGrpcEventStore; -import org.fuin.esc.api.EnhancedMimeType; -import org.fuin.esc.spi.EscEvent; -import org.fuin.esc.spi.EscEvents; -import org.fuin.esc.spi.EscMeta; -import org.fuin.esc.spi.EscSpiUtils; -import org.fuin.esc.api.JsonbDeSerializer; import org.fuin.esc.api.SerDeserializerRegistry; import org.fuin.esc.api.SerializedDataTypeRegistry; +import org.fuin.esc.api.SimpleCommonEvent; import org.fuin.esc.api.SimpleSerializedDataTypeRegistry; import org.fuin.esc.api.SimpleSerializerDeserializerRegistry; +import org.fuin.esc.api.SimpleStreamId; +import org.fuin.esc.api.StreamId; +import org.fuin.esc.esgrpc.ESGrpcEventStore; +import org.fuin.esc.jsonb.EscEvent; +import org.fuin.esc.jsonb.EscEvents; +import org.fuin.esc.jsonb.EscJsonbUtils; +import org.fuin.esc.jsonb.EscMeta; +import org.fuin.esc.jsonb.JsonbDeSerializer; -import com.eventstore.dbclient.EventStoreDBClient; -import com.eventstore.dbclient.EventStoreDBClientSettings; -import com.eventstore.dbclient.EventStoreDBConnectionString; +import java.net.MalformedURLException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * Event Store (https://geteventstore.com/) HTTP JSON-B example. */ public final class EsGrpcJsonbExample { - private EsGrpcJsonbExample() { - super(); - } - - private static SerializedDataTypeRegistry createTypeRegistry() { - - // Contains all types for usage with JSON-B - SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); - - // Base types always needed - typeRegistry.add(EscEvent.SER_TYPE, EscEvent.class); - typeRegistry.add(EscEvents.SER_TYPE, EscEvents.class); - typeRegistry.add(EscMeta.SER_TYPE, EscMeta.class); - // User defined types - typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); - typeRegistry.add(BookAddedEvent.SER_TYPE, BookAddedEvent.class); - - return typeRegistry; - } - - /** - * Creates a registry that connects the type with the appropriate serializer and - * de-serializer. - * - * @param typeRegistry Type registry (Mapping from type name to class). - * @param jsonbDeSer JSON-B serializer/deserializer to use. - * - * @return New registry instance. - */ - private static SerDeserializerRegistry createSerDeserializerRegistry(SerializedDataTypeRegistry typeRegistry, - JsonbDeSerializer jsonbDeSer) { - - SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); - - // Base types always needed - registry.add(EscEvents.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscEvent.SER_TYPE, "application/json", jsonbDeSer); - registry.add(EscMeta.SER_TYPE, "application/json", jsonbDeSer); - - // User defined types - registry.add(MyMeta.SER_TYPE, "application/json", jsonbDeSer); - registry.add(BookAddedEvent.SER_TYPE, "application/json", jsonbDeSer); - - jsonbDeSer.init(typeRegistry, registry, registry); - - return registry; - } - - private static JsonbDeSerializer createJsonbDeSerializer() { - return JsonbDeSerializer.builder().withSerializers(EscSpiUtils.createEscJsonbSerializers()) - .withDeserializers(EscSpiUtils.createEscJsonbDeserializers()) - .withPropertyVisibilityStrategy(new FieldAccessStrategy()).withEncoding(Charset.forName("utf-8")) - .build(); - } - - /** - * Main method. - * - * @param args Not used. - */ - public static void main(final String[] args) throws MalformedURLException { - - // Knows about all types for usage with JSON-B - SerializedDataTypeRegistry typeRegistry = createTypeRegistry(); - - // Does the actual marshalling/unmarshalling - JsonbDeSerializer jsonbDeSer = createJsonbDeSerializer(); - - // Registry connects the type with the appropriate serializer and de-serializer - SerDeserializerRegistry serDeserRegistry = createSerDeserializerRegistry(typeRegistry, jsonbDeSer); - - // Create an event store instance and open it - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "changeit"); - credentialsProvider.setCredentials(AuthScope.ANY, credentials); - - final EventStoreDBClientSettings setts = EventStoreDBConnectionString - .parseOrThrow("esdb://localhost:2113?tls=false"); - final EventStoreDBClient client = EventStoreDBClient.create(setts); - EventStore eventStore = new ESGrpcEventStore.Builder().eventStore(client).serDesRegistry(serDeserRegistry) - .targetContentType(EnhancedMimeType.create("application", "json", Charset.forName("utf-8"))).build(); - - eventStore.open(); - try { - - // Prepare - StreamId streamId = new SimpleStreamId("books-jsonb-example"); // Unique stream name + NO PROJECTION - EventId eventId = new EventId("c8af28d4-5544-4624-99ff-7fcf1a0c8cfe"); // Create a unique event ID - BookAddedEvent event = new BookAddedEvent("Shining", "Stephen King"); // Your event - CommonEvent commonEvent = new SimpleCommonEvent(eventId, BookAddedEvent.TYPE, event); // Combines user and - // general data - - // Append the event to the stream - eventStore.appendToStream(streamId, ExpectedVersion.NO_OR_EMPTY_STREAM.getNo(), commonEvent); - - // Read it from the stream - CommonEvent readEvent = eventStore.readEvent(streamId, 0); - - // Prints "BookAddedEvent c8af28d4-5544-4624-99ff-7fcf1a0c8cfe" - System.out.println(readEvent); - - } finally { - // Don't forget to close - eventStore.close(); - } - - } + private EsGrpcJsonbExample() { + super(); + } + + private static SerializedDataTypeRegistry createTypeRegistry() { + + // Contains all types for usage with JSON-B + SimpleSerializedDataTypeRegistry typeRegistry = new SimpleSerializedDataTypeRegistry(); + + // Base types always needed + typeRegistry.add(EscEvent.SER_TYPE, EscEvent.class); + typeRegistry.add(EscEvents.SER_TYPE, EscEvents.class); + typeRegistry.add(EscMeta.SER_TYPE, EscMeta.class); + // User defined types + typeRegistry.add(MyMeta.SER_TYPE, MyMeta.class); + typeRegistry.add(BookAddedEvent.SER_TYPE, BookAddedEvent.class); + + return typeRegistry; + } + + /** + * Creates a registry that connects the type with the appropriate serializer and + * de-serializer. + * + * @param typeRegistry Type registry (Mapping from type name to class). + * @param jsonbDeSer JSON-B serializer/deserializer to use. + * @return New registry instance. + */ + private static SerDeserializerRegistry createSerDeserializerRegistry(SerializedDataTypeRegistry typeRegistry, + JsonbDeSerializer jsonbDeSer) { + + SimpleSerializerDeserializerRegistry registry = new SimpleSerializerDeserializerRegistry(); + + // Base types always needed + registry.add(EscEvents.SER_TYPE, "application/json", jsonbDeSer); + registry.add(EscEvent.SER_TYPE, "application/json", jsonbDeSer); + registry.add(EscMeta.SER_TYPE, "application/json", jsonbDeSer); + + // User defined types + registry.add(MyMeta.SER_TYPE, "application/json", jsonbDeSer); + registry.add(BookAddedEvent.SER_TYPE, "application/json", jsonbDeSer); + + jsonbDeSer.init(typeRegistry, registry, registry); + + return registry; + } + + private static JsonbDeSerializer createJsonbDeSerializer() { + return JsonbDeSerializer.builder() + .withSerializers(EscJsonbUtils.createEscJsonbSerializers()) + .withDeserializers(EscJsonbUtils.createEscJsonbDeserializers()) + .withPropertyVisibilityStrategy(new FieldAccessStrategy()) + .withEncoding(StandardCharsets.UTF_8) + .build(); + } + + /** + * Main method. + * + * @param args Not used. + */ + public static void main(final String[] args) throws MalformedURLException { + + // Knows about all types for usage with JSON-B + SerializedDataTypeRegistry typeRegistry = createTypeRegistry(); + + // Does the actual marshalling/unmarshalling + JsonbDeSerializer jsonbDeSer = createJsonbDeSerializer(); + + // Registry connects the type with the appropriate serializer and de-serializer + SerDeserializerRegistry serDeserRegistry = createSerDeserializerRegistry(typeRegistry, jsonbDeSer); + + // Create an event store instance and open it + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "changeit"); + credentialsProvider.setCredentials(AuthScope.ANY, credentials); + + final EventStoreDBClientSettings setts = EventStoreDBConnectionString + .parseOrThrow("esdb://localhost:2113?tls=false"); + final EventStoreDBClient client = EventStoreDBClient.create(setts); + EventStore eventStore = new ESGrpcEventStore.Builder().eventStore(client).serDesRegistry(serDeserRegistry) + .targetContentType(EnhancedMimeType.create("application", "json", Charset.forName("utf-8"))).build(); + + eventStore.open(); + try { + + // Prepare + StreamId streamId = new SimpleStreamId("books-jsonb-example"); // Unique stream name + NO PROJECTION + EventId eventId = new EventId("c8af28d4-5544-4624-99ff-7fcf1a0c8cfe"); // Create a unique event ID + BookAddedEvent event = new BookAddedEvent("Shining", "Stephen King"); // Your event + CommonEvent commonEvent = new SimpleCommonEvent(eventId, BookAddedEvent.TYPE, event); // Combines user and + // general data + + // Append the event to the stream + eventStore.appendToStream(streamId, ExpectedVersion.NO_OR_EMPTY_STREAM.getNo(), commonEvent); + + // Read it from the stream + CommonEvent readEvent = eventStore.readEvent(streamId, 0); + + // Prints "BookAddedEvent c8af28d4-5544-4624-99ff-7fcf1a0c8cfe" + System.out.println(readEvent); + + } finally { + // Don't forget to close + eventStore.close(); + } + + } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/examples/InMemoryExample.java b/test/src/test/java/org/fuin/esc/test/examples/InMemoryExample.java index 955aeb7e..e8a1a0f4 100644 --- a/test/src/test/java/org/fuin/esc/test/examples/InMemoryExample.java +++ b/test/src/test/java/org/fuin/esc/test/examples/InMemoryExample.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.examples; import org.fuin.esc.api.*; @@ -17,9 +16,8 @@ private InMemoryExample() { /** * Main method. - * - * @param args - * Not used. + * + * @param args Not used. */ public static void main(final String[] args) { @@ -35,7 +33,7 @@ public static void main(final String[] args) { TypeName eventType = new TypeName("BookAddedEvent");// Define unique event type (name of the event) BookAddedEvent event = new BookAddedEvent("Shining", "Stephen King"); // Your event CommonEvent commonEvent = new SimpleCommonEvent(eventId, eventType, event); // Combines user and general data - + // Append the event to the stream eventStore.appendToStream(streamId, ExpectedVersion.NO_OR_EMPTY_STREAM.getNo(), commonEvent); diff --git a/test/src/test/java/org/fuin/esc/test/examples/MyMeta.java b/test/src/test/java/org/fuin/esc/test/examples/MyMeta.java index c273c55e..049bf98b 100644 --- a/test/src/test/java/org/fuin/esc/test/examples/MyMeta.java +++ b/test/src/test/java/org/fuin/esc/test/examples/MyMeta.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.examples; import jakarta.annotation.Nullable; @@ -17,12 +16,16 @@ public final class MyMeta implements Serializable { private static final long serialVersionUID = 100L; - /** Unique name of the event. */ + /** + * Unique name of the event. + */ public static final TypeName TYPE = new TypeName("MyMeta"); - /** Unique name of the serialized type. */ + /** + * Unique name of the serialized type. + */ public static final SerializedDataType SER_TYPE = new SerializedDataType(TYPE.asBaseType()); - + @XmlElement(name = "user") private String user; @@ -35,9 +38,8 @@ protected MyMeta() { /** * Constructor with all mandatory data. - * - * @param user - * User ID. + * + * @param user User ID. */ public MyMeta(@Nullable final String user) { super(); @@ -46,7 +48,7 @@ public MyMeta(@Nullable final String user) { /** * Returns the user. - * + * * @return User ID. */ public final String getUser() { @@ -89,4 +91,4 @@ public final String toString() { } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/jpa/TestIdStreamFactory.java b/test/src/test/java/org/fuin/esc/test/jpa/TestIdStreamFactory.java index 5d588b79..98dcfcde 100644 --- a/test/src/test/java/org/fuin/esc/test/jpa/TestIdStreamFactory.java +++ b/test/src/test/java/org/fuin/esc/test/jpa/TestIdStreamFactory.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.jpa; import org.fuin.esc.api.StreamId; @@ -24,4 +23,4 @@ public JpaStream createStream(final StreamId streamId) { } } -// CHECKSTYLE:ON + diff --git a/test/src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java b/test/src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java index 2c23412d..810ae401 100644 --- a/test/src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java +++ b/test/src/test/java/org/fuin/esc/test/performance/EsHttpPerformance.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package org.fuin.esc.test.performance; import java.io.IOException; @@ -15,10 +14,8 @@ private EsHttpPerformance() { /** * Main method. - * - * @param args - * Not used. - * + * + * @param args Not used. * @throws IOException Error reading console input. */ public static void main(final String[] args) throws IOException { @@ -140,8 +137,8 @@ private static void waitForInput(final String message) throws IOException { while ((char) System.in.read() != 'c') { // Do it again } - + } } -// CHECKSTYLE:ON + diff --git a/test/src/test/resources/META-INF/persistence.xml b/test/src/test/resources/META-INF/persistence.xml index af9e0bb4..0d98554d 100644 --- a/test/src/test/resources/META-INF/persistence.xml +++ b/test/src/test/resources/META-INF/persistence.xml @@ -1,41 +1,41 @@ + xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> - + - org.hibernate.jpa.HibernatePersistenceProvider + org.hibernate.jpa.HibernatePersistenceProvider - org.fuin.esc.jpa.JpaEvent - org.fuin.esc.jpa.JpaStream - org.fuin.esc.jpa.JpaProjection - org.fuin.esc.jpa.JpaData - org.fuin.esc.jpa.NoParamsEvent - org.fuin.esc.jpa.NoParamsStream + org.fuin.esc.jpa.JpaEvent + org.fuin.esc.jpa.JpaStream + org.fuin.esc.jpa.JpaProjection + org.fuin.esc.jpa.JpaData + org.fuin.esc.jpa.NoParamsEvent + org.fuin.esc.jpa.NoParamsStream - true + true - - - - - - - - - + + + + + + + + + - - - - - + + + + + - + - + diff --git a/test/src/test/resources/features/append-event.feature b/test/src/test/resources/features/append-event.feature index b0c18796..97fa522a 100644 --- a/test/src/test/resources/features/append-event.feature +++ b/test/src/test/resources/features/append-event.feature @@ -1,20 +1,20 @@ Feature: Append events -Scenario: Append single again + Scenario: Append single again Given the following streams don't exist - | Stream Name | - | AppendSingleAgain | + | Stream Name | + | AppendSingleAgain | And I append the following events in the given order - | Stream Name | Expected Version | Event Id | Expected Exception | - | AppendSingleAgain | NO_OR_EMPTY_STREAM | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | + | Stream Name | Expected Version | Event Id | Expected Exception | + | AppendSingleAgain | NO_OR_EMPTY_STREAM | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | When I append the following events in the given order - | Stream Name | Expected Version | Event Id | Expected Exception | - | AppendSingleAgain | NO_OR_EMPTY_STREAM | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | - | AppendSingleAgain | ANY | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | - | AppendSingleAgain | 0 | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | + | Stream Name | Expected Version | Event Id | Expected Exception | + | AppendSingleAgain | NO_OR_EMPTY_STREAM | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | + | AppendSingleAgain | ANY | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | + | AppendSingleAgain | 0 | e62b7f2f-5cad-4188-9c0b-e94b01df11b1 | - | Then this should raise no exception - Scenario: Append multiple again + Scenario: Append multiple again Given the stream "AppendMultipleAgain" does not exist And I append the following events to stream "AppendMultipleAgain" """ @@ -39,19 +39,19 @@ Scenario: Append single again """ Then this should raise no exception - - Scenario: Wrong expected version + + Scenario: Wrong expected version Given the following streams don't exist - | Stream Name | - | WrongExpectedVersion | + | Stream Name | + | WrongExpectedVersion | And I append the following events in the given order - | Stream Name | Expected Version | Event Id | Expected Exception | - | WrongExpectedVersion | NO_OR_EMPTY_STREAM | f98c7eb9-a29a-4c6c-999b-be6d6e4b51b3 | - | - | WrongExpectedVersion | 0 | 853f86e2-881c-4647-99f2-d579f280561f | - | - | WrongExpectedVersion | 1 | a45ea42f-0825-440b-8ddf-9d1aaebd627a | - | + | Stream Name | Expected Version | Event Id | Expected Exception | + | WrongExpectedVersion | NO_OR_EMPTY_STREAM | f98c7eb9-a29a-4c6c-999b-be6d6e4b51b3 | - | + | WrongExpectedVersion | 0 | 853f86e2-881c-4647-99f2-d579f280561f | - | + | WrongExpectedVersion | 1 | a45ea42f-0825-440b-8ddf-9d1aaebd627a | - | When I append the following events in the given order - | Stream Name | Expected Version | Event Id | Expected Exception | - | WrongExpectedVersion | 1 | c58d47d0-9d56-4d47-8889-3b0932b16054 | WrongExpectedVersionException | + | Stream Name | Expected Version | Event Id | Expected Exception | + | WrongExpectedVersion | 1 | c58d47d0-9d56-4d47-8889-3b0932b16054 | WrongExpectedVersionException | Then this should give the expected results \ No newline at end of file diff --git a/test/src/test/resources/features/delete-stream.feature b/test/src/test/resources/features/delete-stream.feature index 09bbf837..13ed44d1 100644 --- a/test/src/test/resources/features/delete-stream.feature +++ b/test/src/test/resources/features/delete-stream.feature @@ -1,106 +1,106 @@ Feature: Delete a stream -Scenario: Non existing once + Scenario: Non existing once Given the following streams don't exist - | Stream Name | - | NameDoesNotMatter1 | - | NameDoesNotMatter2 | - | NameDoesNotMatter3 | - | NameDoesNotMatter4 | - | NameDoesNotMatter5 | - | NameDoesNotMatter6 | + | Stream Name | + | NameDoesNotMatter1 | + | NameDoesNotMatter2 | + | NameDoesNotMatter3 | + | NameDoesNotMatter4 | + | NameDoesNotMatter5 | + | NameDoesNotMatter6 | When the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | NameDoesNotMatter1 | true | ANY | - | - | NameDoesNotMatter2 | true | NO_OR_EMPTY_STREAM | - | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | NameDoesNotMatter1 | true | ANY | - | + | NameDoesNotMatter2 | true | NO_OR_EMPTY_STREAM | - | # | NameDoesNotMatter3 | false | ANY | - | # | NameDoesNotMatter4 | false | NO_OR_EMPTY_STREAM | - | - | NameDoesNotMatter5 | true | 1 | WrongExpectedVersionException | - | NameDoesNotMatter6 | false | 1 | WrongExpectedVersionException | + | NameDoesNotMatter5 | true | 1 | WrongExpectedVersionException | + | NameDoesNotMatter6 | false | 1 | WrongExpectedVersionException | Then this should give the expected results -Scenario: Hard non existing twice + Scenario: Hard non existing twice Given the following streams don't exist - | Stream Name | - | NonExistingHardDeleteTwice | + | Stream Name | + | NonExistingHardDeleteTwice | And the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | NonExistingHardDeleteTwice | true | ANY | - | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | NonExistingHardDeleteTwice | true | ANY | - | When the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | NonExistingHardDeleteTwice | true | ANY | StreamDeletedException | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | NonExistingHardDeleteTwice | true | ANY | StreamDeletedException | Then this should give the expected results - -Scenario: Already existing + + Scenario: Already existing Given the following streams are created and a single event is appended to each - | Stream Name | - | DeleteExisting1 | - | DeleteExisting2 | - | DeleteExisting3 | - | DeleteExisting4 | - | DeleteExisting5 | - | DeleteExisting6 | - | DeleteExisting7 | - | DeleteExisting8 | + | Stream Name | + | DeleteExisting1 | + | DeleteExisting2 | + | DeleteExisting3 | + | DeleteExisting4 | + | DeleteExisting5 | + | DeleteExisting6 | + | DeleteExisting7 | + | DeleteExisting8 | When the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | DeleteExisting1 | true | ANY | - | - | DeleteExisting2 | true | NO_OR_EMPTY_STREAM | WrongExpectedVersionException | - | DeleteExisting2 | false | ANY | - | - | DeleteExisting4 | false | NO_OR_EMPTY_STREAM | WrongExpectedVersionException | - | DeleteExisting5 | true | 0 | - | - | DeleteExisting6 | false | 0 | - | - | DeleteExisting7 | true | 1 | WrongExpectedVersionException | - | DeleteExisting8 | false | 1 | WrongExpectedVersionException | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | DeleteExisting1 | true | ANY | - | + | DeleteExisting2 | true | NO_OR_EMPTY_STREAM | WrongExpectedVersionException | + | DeleteExisting2 | false | ANY | - | + | DeleteExisting4 | false | NO_OR_EMPTY_STREAM | WrongExpectedVersionException | + | DeleteExisting5 | true | 0 | - | + | DeleteExisting6 | false | 0 | - | + | DeleteExisting7 | true | 1 | WrongExpectedVersionException | + | DeleteExisting8 | false | 1 | WrongExpectedVersionException | Then this should give the expected results -Scenario: Read after delete - Given the following streams are created and a single event is appended to each - | Stream Name | - | ReadAfterHardDelete | - | ReadAfterSoftDelete | + Scenario: Read after delete + Given the following streams are created and a single event is appended to each + | Stream Name | + | ReadAfterHardDelete | + | ReadAfterSoftDelete | When the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | ReadAfterHardDelete | true | ANY | - | - | ReadAfterSoftDelete | false | ANY | - | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | ReadAfterHardDelete | true | ANY | - | + | ReadAfterSoftDelete | false | ANY | - | Then this should give the expected results And following streams should not exist - | Stream Name | - | ReadAfterHardDelete | - | ReadAfterSoftDelete | + | Stream Name | + | ReadAfterHardDelete | + | ReadAfterSoftDelete | And reading forward from the following streams should raise the given exceptions - | Stream Name | Start | Count | Expected Exception | - | ReadAfterHardDelete | 1 | 1 | StreamDeletedException | - | ReadAfterSoftDelete | 1 | 1 | StreamNotFoundException | + | Stream Name | Start | Count | Expected Exception | + | ReadAfterHardDelete | 1 | 1 | StreamDeletedException | + | ReadAfterSoftDelete | 1 | 1 | StreamNotFoundException | -Scenario: Delete after delete - Given the following streams are created and a single event is appended to each - | Stream Name | - | DeleteAfterHardDelete1 | - | DeleteAfterHardDelete2 | - | DeleteAfterHardDelete3 | - | DeleteAfterHardDelete4 | - | DeleteAfterSoftDelete1 | - | DeleteAfterSoftDelete2 | - | DeleteAfterSoftDelete3 | - | DeleteAfterSoftDelete4 | + Scenario: Delete after delete + Given the following streams are created and a single event is appended to each + | Stream Name | + | DeleteAfterHardDelete1 | + | DeleteAfterHardDelete2 | + | DeleteAfterHardDelete3 | + | DeleteAfterHardDelete4 | + | DeleteAfterSoftDelete1 | + | DeleteAfterSoftDelete2 | + | DeleteAfterSoftDelete3 | + | DeleteAfterSoftDelete4 | When the following deletes are executed - | Stream Name | Hard Delete | Expected Version | Expected Exception | - | DeleteAfterHardDelete1 | true | ANY | - | - | DeleteAfterHardDelete2 | true | ANY | - | - | DeleteAfterHardDelete3 | true | ANY | - | - | DeleteAfterHardDelete4 | true | ANY | - | - | DeleteAfterSoftDelete1 | false | ANY | - | - | DeleteAfterSoftDelete2 | false | ANY | - | - | DeleteAfterSoftDelete3 | false | ANY | - | - | DeleteAfterSoftDelete4 | false | ANY | - | - | DeleteAfterHardDelete1 | true | ANY | StreamDeletedException | - | DeleteAfterHardDelete2 | false | ANY | StreamDeletedException | - | DeleteAfterHardDelete3 | true | 0 | StreamDeletedException | - | DeleteAfterHardDelete4 | false | 0 | StreamDeletedException | - | DeleteAfterSoftDelete1 | true | ANY | - | - | DeleteAfterSoftDelete2 | false | ANY | - | - | DeleteAfterSoftDelete3 | true | 0 | - | - | DeleteAfterSoftDelete4 | false | 0 | - | + | Stream Name | Hard Delete | Expected Version | Expected Exception | + | DeleteAfterHardDelete1 | true | ANY | - | + | DeleteAfterHardDelete2 | true | ANY | - | + | DeleteAfterHardDelete3 | true | ANY | - | + | DeleteAfterHardDelete4 | true | ANY | - | + | DeleteAfterSoftDelete1 | false | ANY | - | + | DeleteAfterSoftDelete2 | false | ANY | - | + | DeleteAfterSoftDelete3 | false | ANY | - | + | DeleteAfterSoftDelete4 | false | ANY | - | + | DeleteAfterHardDelete1 | true | ANY | StreamDeletedException | + | DeleteAfterHardDelete2 | false | ANY | StreamDeletedException | + | DeleteAfterHardDelete3 | true | 0 | StreamDeletedException | + | DeleteAfterHardDelete4 | false | 0 | StreamDeletedException | + | DeleteAfterSoftDelete1 | true | ANY | - | + | DeleteAfterSoftDelete2 | false | ANY | - | + | DeleteAfterSoftDelete3 | true | 0 | - | + | DeleteAfterSoftDelete4 | false | 0 | - | Then this should give the expected results \ No newline at end of file diff --git a/test/src/test/resources/features/read-event.feature b/test/src/test/resources/features/read-event.feature index d6be8bde..cc327754 100644 --- a/test/src/test/resources/features/read-event.feature +++ b/test/src/test/resources/features/read-event.feature @@ -1,6 +1,6 @@ Feature: Read a single event -Scenario: Same type append and read + Scenario: Same type append and read Given the stream "AppendSameAndRead" does not exist When I append the following events to stream "AppendSameAndRead" """ @@ -30,8 +30,8 @@ Scenario: Same type append and read """ - - Scenario: Different type append and read + + Scenario: Different type append and read Given the stream "AppendDiffAndRead" does not exist When I append the following events to stream "AppendDiffAndRead" """ diff --git a/test/src/test/resources/features/read-stream-backward.feature b/test/src/test/resources/features/read-stream-backward.feature index 71b1a242..ac3144a6 100644 --- a/test/src/test/resources/features/read-stream-backward.feature +++ b/test/src/test/resources/features/read-stream-backward.feature @@ -1,40 +1,40 @@ Feature: Read a stream backward -Scenario: Illegal start or count + Scenario: Illegal start or count When I read backward from the following streams - | Stream Name | Start | Count | Expected Exception | Expected Message | - | NameDoesNotMatter | -1 | 1 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'start' is 0, but was: -1 | - | NameDoesNotMatter | 1 | 0 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'count' is 1, but was: 0 | + | Stream Name | Start | Count | Expected Exception | Expected Message | + | NameDoesNotMatter | -1 | 1 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'start' is 0, but was: -1 | + | NameDoesNotMatter | 1 | 0 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'count' is 1, but was: 0 | Then this should give the expected results -Scenario: Read non existing + Scenario: Read non existing Given the following streams don't exist - | Stream Name | - | NameDoesNotMatter | + | Stream Name | + | NameDoesNotMatter | When I read backward from the following streams - | Stream Name | Start | Count | Expected Exception | - | NameDoesNotMatter | 1 | 1 | StreamNotFoundException | + | Stream Name | Start | Count | Expected Exception | + | NameDoesNotMatter | 1 | 1 | StreamNotFoundException | Then this should give the expected results -Scenario: Append and read single + Scenario: Append and read single Given the stream "AppendSingleBackward" does not exist When I append the following events in the given order - | Stream Name | Expected Version | Event Id | - | AppendSingleBackward | NO_OR_EMPTY_STREAM | a3d80db0-f35e-45f0-817f-648d07ad7391 | + | Stream Name | Expected Version | Event Id | + | AppendSingleBackward | NO_OR_EMPTY_STREAM | a3d80db0-f35e-45f0-817f-648d07ad7391 | Then reading backward from stream should have the following results - | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | - | AppendSingleBackward | 0 | 1 | 0 | 0 | true | a3d80db0-f35e-45f0-817f-648d07ad7391 | + | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | + | AppendSingleBackward | 0 | 1 | 0 | 0 | true | a3d80db0-f35e-45f0-817f-648d07ad7391 | -Scenario: Append and read multiple + Scenario: Append and read multiple Given the stream "AppendMultipleBackward" does not exist When I append the following events in the given order - | Stream Name | Expected Version | Event Id | - | AppendMultipleBackward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | - | AppendMultipleBackward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | - | AppendMultipleBackward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | AppendMultipleBackward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | - | AppendMultipleBackward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | + | Stream Name | Expected Version | Event Id | + | AppendMultipleBackward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | + | AppendMultipleBackward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | + | AppendMultipleBackward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | AppendMultipleBackward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | + | AppendMultipleBackward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | Then reading backward from stream should have the following results - | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | - | AppendMultipleBackward | 4 | 3 | 4 | 1 | false | ce75244f-c3f6-44a0-a263-c94abf0ac480 | cf27403b-f701-4288-9668-6173e9dbce71 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | AppendMultipleBackward | 1 | 3 | 1 | 0 | true | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 26d53452-30a8-473b-b5cc-58650265dfb3 | - | + | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | + | AppendMultipleBackward | 4 | 3 | 4 | 1 | false | ce75244f-c3f6-44a0-a263-c94abf0ac480 | cf27403b-f701-4288-9668-6173e9dbce71 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | AppendMultipleBackward | 1 | 3 | 1 | 0 | true | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 26d53452-30a8-473b-b5cc-58650265dfb3 | - | diff --git a/test/src/test/resources/features/read-stream-forward.feature b/test/src/test/resources/features/read-stream-forward.feature index 6e1ceb4a..915257ee 100644 --- a/test/src/test/resources/features/read-stream-forward.feature +++ b/test/src/test/resources/features/read-stream-forward.feature @@ -1,65 +1,65 @@ Feature: Read a stream forward -Scenario: Illegal start or count + Scenario: Illegal start or count When I read forward from the following streams - | Stream Name | Start | Count | Expected Exception | Expected Message | - | NameDoesNotMatter | -1 | 1 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'start' is 0, but was: -1 | - | NameDoesNotMatter | 1 | 0 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'count' is 1, but was: 0 | + | Stream Name | Start | Count | Expected Exception | Expected Message | + | NameDoesNotMatter | -1 | 1 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'start' is 0, but was: -1 | + | NameDoesNotMatter | 1 | 0 | org.fuin.objects4j.common.ConstraintViolationException | Min value of argument 'count' is 1, but was: 0 | Then this should give the expected results -Scenario: Read non existing + Scenario: Read non existing Given the following streams don't exist - | Stream Name | - | NameDoesNotMatter | + | Stream Name | + | NameDoesNotMatter | When I read forward from the following streams - | Stream Name | Start | Count | Expected Exception | - | NameDoesNotMatter | 1 | 1 | StreamNotFoundException | + | Stream Name | Start | Count | Expected Exception | + | NameDoesNotMatter | 1 | 1 | StreamNotFoundException | Then this should give the expected results -Scenario: Append and read single + Scenario: Append and read single Given the stream "AppendSingleForward" does not exist When I append the following events in the given order - | Stream Name | Expected Version | Event Id | - | AppendSingleForward | NO_OR_EMPTY_STREAM | a3d80db0-f35e-45f0-817f-648d07ad7391 | + | Stream Name | Expected Version | Event Id | + | AppendSingleForward | NO_OR_EMPTY_STREAM | a3d80db0-f35e-45f0-817f-648d07ad7391 | Then reading forward from stream should have the following results - | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | - | AppendSingleForward | 0 | 1 | 0 | 1 | false | a3d80db0-f35e-45f0-817f-648d07ad7391 | - | AppendSingleForward | 1 | 1 | 1 | 1 | true | - | + | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | + | AppendSingleForward | 0 | 1 | 0 | 1 | false | a3d80db0-f35e-45f0-817f-648d07ad7391 | + | AppendSingleForward | 1 | 1 | 1 | 1 | true | - | -Scenario: Append and read multiple + Scenario: Append and read multiple Given the stream "AppendMultipleForward" does not exist When I append the following events in the given order - | Stream Name | Expected Version | Event Id | - | AppendMultipleForward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | - | AppendMultipleForward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | - | AppendMultipleForward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | AppendMultipleForward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | - | AppendMultipleForward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | + | Stream Name | Expected Version | Event Id | + | AppendMultipleForward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | + | AppendMultipleForward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | + | AppendMultipleForward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | AppendMultipleForward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | + | AppendMultipleForward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | Then reading forward from stream should have the following results - | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | - | AppendMultipleForward | 0 | 3 | 0 | 3 | false | 26d53452-30a8-473b-b5cc-58650265dfb3 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | AppendMultipleForward | 3 | 3 | 3 | 5 | true | cf27403b-f701-4288-9668-6173e9dbce71 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | + | Stream Name | Start | Count | Result From | Result Next | End Of Stream | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | + | AppendMultipleForward | 0 | 3 | 0 | 3 | false | 26d53452-30a8-473b-b5cc-58650265dfb3 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | AppendMultipleForward | 3 | 3 | 3 | 5 | true | cf27403b-f701-4288-9668-6173e9dbce71 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | -Scenario: Append and read all + Scenario: Append and read all Given the stream "AppendAllForward" does not exist When I append the following events in the given order - | Stream Name | Expected Version | Event Id | - | AppendAllForward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | - | AppendAllForward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | - | AppendAllForward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | AppendAllForward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | - | AppendAllForward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | + | Stream Name | Expected Version | Event Id | + | AppendAllForward | NO_OR_EMPTY_STREAM | 26d53452-30a8-473b-b5cc-58650265dfb3 | + | AppendAllForward | 0 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | + | AppendAllForward | 1 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | AppendAllForward | 2 | cf27403b-f701-4288-9668-6173e9dbce71 | + | AppendAllForward | 3 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | Then reading all events from stream "AppendAllForward" starting at position 0 with chunk size 3 should have the following results - | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | - | 26d53452-30a8-473b-b5cc-58650265dfb3 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | - | cf27403b-f701-4288-9668-6173e9dbce71 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | + | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | + | 26d53452-30a8-473b-b5cc-58650265dfb3 | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | + | cf27403b-f701-4288-9668-6173e9dbce71 | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | And reading all events from stream "AppendAllForward" starting at position 1 with chunk size 3 should have the following results - | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | - | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | cf27403b-f701-4288-9668-6173e9dbce71 | - | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | - | + | Result Event Id 1 | Result Event Id 2 | Result Event Id 3 | + | 6e4f3687-ccec-496b-8c22-c3848e6f2250 | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | cf27403b-f701-4288-9668-6173e9dbce71 | + | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | - | And reading all events from stream "AppendAllForward" starting at position 2 with chunk size 2 should have the following results - | Result Event Id 1 | Result Event Id 2 | - | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | cf27403b-f701-4288-9668-6173e9dbce71 | - | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | + | Result Event Id 1 | Result Event Id 2 | + | 2ce79b07-020c-4908-ad6f-cd63498d4c9f | cf27403b-f701-4288-9668-6173e9dbce71 | + | ce75244f-c3f6-44a0-a263-c94abf0ac480 | - | diff --git a/test/src/test/resources/features/stream-state.feature b/test/src/test/resources/features/stream-state.feature index e3eeff0f..eeced283 100644 --- a/test/src/test/resources/features/stream-state.feature +++ b/test/src/test/resources/features/stream-state.feature @@ -1,29 +1,29 @@ Feature: Stream state -Scenario: All states + Scenario: All states Given the stream "NameDoesNotMatter" does not exist And the following streams are created and a single event is appended to each - | Stream Name | - | StateExisting | - | StateHardDeleted | - | StateSoftDeleted | + | Stream Name | + | StateExisting | + | StateHardDeleted | + | StateSoftDeleted | And the following deletes are executed - | Stream Name | Hard Delete | Expected Version | - | StateHardDeleted | true | ANY | - | StateSoftDeleted | false | ANY | + | Stream Name | Hard Delete | Expected Version | + | StateHardDeleted | true | ANY | + | StateSoftDeleted | false | ANY | When the following state queries are executed - | Stream Name | Expected State | Expected Exception | - | NameDoesNotMatter | - | StreamNotFoundException | - | StateExisting | ACTIVE | - | - | StateHardDeleted | HARD_DELETED | - | - | StateSoftDeleted | - | StreamNotFoundException | + | Stream Name | Expected State | Expected Exception | + | NameDoesNotMatter | - | StreamNotFoundException | + | StateExisting | ACTIVE | - | + | StateHardDeleted | HARD_DELETED | - | + | StateSoftDeleted | - | StreamNotFoundException | Then this should give the expected results And following streams should exist - | Stream Name | - | StateExisting | + | Stream Name | + | StateExisting | And following streams should not exist - | Stream Name | - | NameDoesNotMatter | - | StateHardDeleted | - | StateSoftDeleted | + | Stream Name | + | NameDoesNotMatter | + | StateHardDeleted | + | StateSoftDeleted | \ No newline at end of file diff --git a/test/src/test/resources/logback.xml b/test/src/test/resources/logback.xml index e5b61a2b..c6c4252a 100644 --- a/test/src/test/resources/logback.xml +++ b/test/src/test/resources/logback.xml @@ -1,21 +1,21 @@ - - esc-test.log - - esc-test.%d{yyyy-MM-dd}.log - 30 - - true - - %d{yyyy.dd.MM HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - + + esc-test.log + + esc-test.%d{yyyy-MM-dd}.log + 30 + + true + + %d{yyyy.dd.MM HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + +