diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml deleted file mode 100644 index c99a896..0000000 --- a/.github/workflows/linux.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: linux - -on: - push: - branches: [ main, develop ] - pull_request: - branches: [ main, develop ] - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Set up JDK 11 - uses: actions/setup-java@v3 - with: - java-version: '11' - distribution: 'temurin' - - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - - name: Test with Gradle - run: ./gradlew test - - - name: Publish test results - uses: EnricoMi/publish-unit-test-result-action@v2 - if: always() - with: - files: '**/build/test-results/test/TEST-*.xml' - - - name: Add comments to a pull request - uses: mikepenz/action-junit-report@v3 - if: always() - with: - report_paths: '**/build/test-results/test/TEST-*.xml' \ No newline at end of file diff --git a/.github/workflows/windows-x64.yml b/.github/workflows/windows-x64.yml new file mode 100644 index 0000000..68e89b1 --- /dev/null +++ b/.github/workflows/windows-x64.yml @@ -0,0 +1,191 @@ +name: windows-x64 + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + +permissions: + contents: read + +jobs: + test: + runs-on: [ self-hosted, windows, x64 ] + + env: + JAVA_HOME: 'C:\jdk\v25.0.0' + + steps: + - uses: actions/checkout@v5 + + - name: Add Build Environments + run: | + "$env:JAVA_HOME\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Validate Project Version Policy + run: | + $projectVersion = (& .\gradlew.bat -q printProjectVersion --no-daemon).Trim() + $isSnapshotVersion = $projectVersion.EndsWith("-SNAPSHOT") + + if ("${{ github.event_name }}" -eq "pull_request") { + $targetBranch = "${{ github.base_ref }}" + } else { + $targetBranch = "${{ github.ref_name }}" + } + + if ($targetBranch -eq "main" -and $isSnapshotVersion) { + throw "Main branch requires a release version without -SNAPSHOT. Current version: $projectVersion" + } + + "PROJECT_VERSION=$projectVersion" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + - name: Build and Test + run: .\gradlew.bat clean test --no-daemon + + - name: Upload Unit Test Report + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: unit-test-report-${{ runner.os }}-${{ runner.arch }} + path: | + **/build/reports/tests/test/** + retention-days: 14 + + - name: Upload Gradle Problems Report + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: gradle-problems-report-${{ runner.os }}-${{ runner.arch }} + path: | + **/build/reports/problems/** + retention-days: 14 + + publish-snapshot: + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/develop' && success() }} + + needs: test + runs-on: [ self-hosted, windows, x64 ] + + env: + JAVA_HOME: 'C:\jdk\v25.0.0' + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_PASSWORD }} + + concurrency: + group: maven-central-publish-develop + cancel-in-progress: false + + steps: + - uses: actions/checkout@v5 + + - name: Add Build Environments + run: | + "$env:JAVA_HOME\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Validate Maven Central Secrets + run: | + if ([string]::IsNullOrWhiteSpace($env:MAVEN_USERNAME)) { + throw "Missing secret MAVEN_USERNAME." + } + + if ([string]::IsNullOrWhiteSpace($env:MAVEN_PASSWORD)) { + throw "Missing secret MAVEN_PASSWORD." + } + + - name: Check Snapshot Publish Eligibility + id: snapshot-version + run: | + $projectVersion = (& .\gradlew.bat -q printProjectVersion --no-daemon).Trim() + + "project_version=$projectVersion" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + + if ($projectVersion.EndsWith("-SNAPSHOT")) { + "should_publish=true" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + } else { + Write-Host "Skipping snapshot publish because develop currently has release version: $projectVersion" + "should_publish=false" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + } + + - name: Publish Snapshot to Maven Central Portal + if: ${{ steps.snapshot-version.outputs.should_publish == 'true' }} + run: .\gradlew.bat clean publishToMavenCentral --no-daemon + + - name: Upload Maven Artifacts + if: ${{ always() && steps.snapshot-version.outputs.should_publish == 'true' }} + uses: actions/upload-artifact@v4 + with: + name: maven-upload-artifacts-${{ runner.os }}-${{ runner.arch }}-develop + path: | + build/libs/** + build/publications/** + build/centralPortal/** + if-no-files-found: ignore + retention-days: 7 + + publish-release: + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && success() }} + + needs: test + runs-on: [ self-hosted, windows, x64 ] + + env: + JAVA_HOME: 'C:\jdk\v25.0.0' + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MAVEN_SIGNING_KEY: ${{ secrets.MAVEN_SIGNING_KEY }} + MAVEN_SIGNING_PASSWORD: ${{ secrets.MAVEN_SIGNING_PASSWORD }} + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.MAVEN_SIGNING_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.MAVEN_SIGNING_PASSWORD }} + + concurrency: + group: maven-central-publish-main + cancel-in-progress: false + + steps: + - uses: actions/checkout@v5 + + - name: Add Build Environments + run: | + "$env:JAVA_HOME\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Validate Maven Central Secrets + run: | + if ([string]::IsNullOrWhiteSpace($env:MAVEN_USERNAME)) { + throw "Missing secret MAVEN_USERNAME." + } + + if ([string]::IsNullOrWhiteSpace($env:MAVEN_PASSWORD)) { + throw "Missing secret MAVEN_PASSWORD." + } + + if ([string]::IsNullOrWhiteSpace($env:MAVEN_SIGNING_KEY)) { + throw "Missing secret MAVEN_SIGNING_KEY." + } + + - name: Validate Release Publish Eligibility + run: | + $projectVersion = (& .\gradlew.bat -q printProjectVersion --no-daemon).Trim() + + if ($projectVersion.EndsWith("-SNAPSHOT")) { + throw "Main branch requires a release version without -SNAPSHOT. Current version: $projectVersion" + } + + - name: Publish Release to Maven Central Portal + run: .\gradlew.bat clean publishAndReleaseToMavenCentral --no-daemon + + - name: Upload Maven Artifacts + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: maven-upload-artifacts-${{ runner.os }}-${{ runner.arch }}-main + path: | + build/libs/** + build/publications/** + build/centralPortal/** + if-no-files-found: ignore + retention-days: 7 \ No newline at end of file diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml deleted file mode 100644 index 2e51093..0000000 --- a/.github/workflows/windows.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: windows - -on: - push: - branches: [ main, develop ] - pull_request: - branches: [ main, develop ] - -jobs: - build: - runs-on: windows-latest - - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Set up JDK 11 - uses: actions/setup-java@v3 - with: - java-version: '11' - distribution: 'temurin' - - - name: Test with Gradle - run: ./gradlew test - - - name: Publish test results - uses: EnricoMi/publish-unit-test-result-action/windows@v2 - if: always() - with: - files: '**/build/test-results/test/TEST-*.xml' - - - name: Add comments to a pull request - uses: mikepenz/action-junit-report@v3 - if: always() - with: - report_paths: '**/build/test-results/test/TEST-*.xml' \ No newline at end of file diff --git a/.gitignore b/.gitignore index 5dc6f0f..a34654a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,23 @@ # Ignore Gradle project-specific cache directory .gradle +.maven -# Ignore Gradle build output directory -build \ No newline at end of file +# Ignore IntelliJ personal files +*.iml +*.ipr +*.iws +.idea/libraries +.idea/misc.xml +.idea/workspace.xml +.idea/modules.xml +.idea/artifacts/ +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Ignore Build Directory +build/ \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_esotericsoftware_kryo_5_6_2.xml b/.idea/libraries/Gradle__com_esotericsoftware_kryo_5_6_2.xml deleted file mode 100644 index 456dced..0000000 --- a/.idea/libraries/Gradle__com_esotericsoftware_kryo_5_6_2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_esotericsoftware_minlog_1_3_1.xml b/.idea/libraries/Gradle__com_esotericsoftware_minlog_1_3_1.xml deleted file mode 100644 index 2be4681..0000000 --- a/.idea/libraries/Gradle__com_esotericsoftware_minlog_1_3_1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_esotericsoftware_reflectasm_1_11_9.xml b/.idea/libraries/Gradle__com_esotericsoftware_reflectasm_1_11_9.xml deleted file mode 100644 index ba1eb7a..0000000 --- a/.idea/libraries/Gradle__com_esotericsoftware_reflectasm_1_11_9.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_annotations_2_18_3.xml b/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_annotations_2_18_3.xml deleted file mode 100644 index f04493f..0000000 --- a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_annotations_2_18_3.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_core_2_18_3.xml b/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_core_2_18_3.xml deleted file mode 100644 index e04b20a..0000000 --- a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_core_2_18_3.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_databind_2_18_3.xml b/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_databind_2_18_3.xml deleted file mode 100644 index d4e311e..0000000 --- a/.idea/libraries/Gradle__com_fasterxml_jackson_core_jackson_databind_2_18_3.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_google_code_gson_gson_2_12_1.xml b/.idea/libraries/Gradle__com_google_code_gson_gson_2_12_1.xml deleted file mode 100644 index 51b0b16..0000000 --- a/.idea/libraries/Gradle__com_google_code_gson_gson_2_12_1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__com_google_errorprone_error_prone_annotations_2_36_0.xml b/.idea/libraries/Gradle__com_google_errorprone_error_prone_annotations_2_36_0.xml deleted file mode 100644 index 76a8b48..0000000 --- a/.idea/libraries/Gradle__com_google_errorprone_error_prone_annotations_2_36_0.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_apiguardian_apiguardian_api_1_1_2.xml b/.idea/libraries/Gradle__org_apiguardian_apiguardian_api_1_1_2.xml deleted file mode 100644 index 723874b..0000000 --- a/.idea/libraries/Gradle__org_apiguardian_apiguardian_api_1_1_2.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_jetbrains_annotations_24_1_0.xml b/.idea/libraries/Gradle__org_jetbrains_annotations_24_1_0.xml deleted file mode 100644 index e158c3b..0000000 --- a/.idea/libraries/Gradle__org_jetbrains_annotations_24_1_0.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_1.xml b/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_1.xml deleted file mode 100644 index d68ae47..0000000 --- a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_2.xml b/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_2.xml deleted file mode 100644 index 3e41cd8..0000000 --- a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_api_5_11_2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_engine_5_11_2.xml b/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_engine_5_11_2.xml deleted file mode 100644 index c0bfc87..0000000 --- a/.idea/libraries/Gradle__org_junit_jupiter_junit_jupiter_engine_5_11_2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_1.xml b/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_1.xml deleted file mode 100644 index 02c21d8..0000000 --- a/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_2.xml b/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_2.xml deleted file mode 100644 index 0249401..0000000 --- a/.idea/libraries/Gradle__org_junit_platform_junit_platform_commons_1_11_2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_junit_platform_junit_platform_engine_1_11_2.xml b/.idea/libraries/Gradle__org_junit_platform_junit_platform_engine_1_11_2.xml deleted file mode 100644 index 3a19239..0000000 --- a/.idea/libraries/Gradle__org_junit_platform_junit_platform_engine_1_11_2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_objenesis_objenesis_3_4.xml b/.idea/libraries/Gradle__org_objenesis_objenesis_3_4.xml deleted file mode 100644 index 57054e6..0000000 --- a/.idea/libraries/Gradle__org_objenesis_objenesis_3_4.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Gradle__org_opentest4j_opentest4j_1_3_0.xml b/.idea/libraries/Gradle__org_opentest4j_opentest4j_1_3_0.xml deleted file mode 100644 index feb67c9..0000000 --- a/.idea/libraries/Gradle__org_opentest4j_opentest4j_1_3_0.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index e4e37bb..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 737fa0f..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules/opack.main.iml b/.idea/modules/opack.main.iml deleted file mode 100644 index 5efd723..0000000 --- a/.idea/modules/opack.main.iml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules/opack.test.iml b/.idea/modules/opack.test.iml deleted file mode 100644 index 19edd23..0000000 --- a/.idea/modules/opack.test.iml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/opack.iml b/.idea/opack.iml deleted file mode 100644 index 3850624..0000000 --- a/.idea/opack.iml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index e96534f..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/README.md b/README.md index d67a8b9..9e95610 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ public class SomeObject { ```java public class ByteToBase64Transformer implements Transformer { @Override - public @Nullable Object serialize(@NotNull Opacker opacker, @NotNull Class originalType, @Nullable Object object) throws SerializeException { + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) throws SerializeException { if (object instanceof byte[]) { return Base64.getEncoder().encodeToString((byte[]) object); } @@ -231,7 +231,7 @@ public class ByteToBase64Transformer implements Transformer { } @Override - public @Nullable Object deserialize(@NotNull Opacker opacker, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { if (object instanceof String) { return Base64.getDecoder().decode((String) object); } @@ -261,16 +261,42 @@ public class SomeObject { } ``` -#### 4. Class Transformer +#### 4. Time Format + +```java +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +public class SomeObject { + // The below fields will serialize formatted using a given pattern + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private Date date; + + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private Calendar date; + + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private LocalTime date; + + @TimeFormat("yyyy-MM-dd") + private LocalDate date; + + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private LocalDateTime date; +} +``` + +#### 5. Class Transformer ```java public class AnimalTransformer implements Transformer { // Remove a `sound` from a serialized `Animal` @Override - public @Nullable Object serialize(@NotNull Opacker opacker, @NotNull Class originalType, @Nullable Object object) throws SerializeException { + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) throws SerializeException { if (object instanceof Animal) { Animal animal = (Animal) object; - OpackValue opackValue = opacker.serialize(animal); + OpackValue opackValue = context.getOpacker().serialize(animal); if (opackValue instanceof OpackObject) { OpackObject opackObject = (OpackObject) opackValue; @@ -284,11 +310,11 @@ public class AnimalTransformer implements Transformer { // Restore `sound` from `Animal` before deserialization @Override - public @Nullable Object deserialize(@NotNull Opacker opacker, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { if (object instanceof OpackObject) { if (Animal.class.isAssignableFrom(goalType)) { OpackObject opackObject = (OpackObject) object; - Animal animal = (Animal) opacker.deserialize(goalType, opackObject); + Animal animal = (Animal) context.getOpacker().deserialize(goalType, opackObject); animal.setSound(animal.bark()); } } @@ -325,7 +351,7 @@ public class SomeObject { } ``` -#### 5. Handling Opack Value +#### 6. Handling Opack Value ```java public class Usage { diff --git a/build.gradle b/build.gradle index 4ab97ac..b1776a5 100644 --- a/build.gradle +++ b/build.gradle @@ -20,89 +20,21 @@ * limitations under the License. */ plugins { - id 'java' - id "signing" - id "maven" + id 'java-library' + id 'com.vanniktech.maven.publish' version '0.37.0' } -group 'com.realtimetech' -archivesBaseName = "opack" -version = "0.2.1" - -compileJava.options.encoding = 'UTF-8' +group = 'com.realtimetech' +version = '0.2.2-SNAPSHOT' tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' + options.release = 11 } -tasks.register('javadocJar', Jar) { - archiveClassifier = 'javadoc' - from javadoc -} - -tasks.register('sourcesJar', Jar) { - archiveClassifier = 'sources' - from sourceSets.main.allSource -} - -artifacts { - archives javadocJar, sourcesJar -} - -signing { - sign configurations.archives -} - -uploadArchives { - repositories { - mavenDeployer { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - - repository(url: "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") { - authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword')) - } - - snapshotRepository(url: "https://s01.oss.sonatype.org/content/repositories/snapshots/") { - authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword')) - } - - pom.project { - name 'opack' - packaging 'jar' - description 'A object serialize and deserialize, encode and decode library' - url 'https://github.com/realtimetech-solution/opack' - - scm { - connection "scm:git:https://github.com/realtimetech-solution/opack" - developerConnection "scm:git:ssh://github.com/realtimetech-solution/opack.git" - url "https://github.com/realtimetech-solution/opack" - } - - licenses { - license { - name 'The Apache License, Version 2.0' - url 'https://www.apache.org/licenses/LICENSE-2.0.txt' - } - } - - developers { - developer { - id "realtimetech" - name "RealtimeTech" - } - developer { - id "devjeonghwan" - name "Jeonghwan Park" - email = "dev.parkjeonghwan@gmail.com" - } - developer { - id "rodamin" - name "Soyeon Kim" - email = "epals8962@realtimetech.co.kr" - } - } - } - } +tasks.register('printProjectVersion') { + doLast { + println project.version } } @@ -113,16 +45,64 @@ repositories { dependencies { implementation 'org.jetbrains:annotations:24.1.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.1' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.11.2' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.1' + testImplementation platform('org.junit:junit-bom:5.11.2') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' // For performance test - testImplementation group: 'com.google.code.gson', name: 'gson', version: '2.12.1' - testImplementation group: 'com.esotericsoftware', name: 'kryo', version: '5.6.2' - testImplementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.18.3' + testImplementation 'com.google.code.gson:gson:2.12.1' + testImplementation 'com.esotericsoftware:kryo:5.6.2' + testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.18.3' } test { useJUnitPlatform() + + jvmArgs '--add-opens=java.base/java.time=ALL-UNNAMED', + '--add-opens=java.base/java.util=ALL-UNNAMED' +} + +mavenPublishing { + publishToMavenCentral() + signAllPublications() + + coordinates(project.group.toString(), project.name, project.version.toString()) + + pom { + name = 'opack' + description = 'An object serialization, deserialization, encoding, and decoding library' + inceptionYear = '2021' + url = 'https://github.com/realtimetech-solution/opack' + + licenses { + license { + name = 'The Apache License, Version 2.0' + url = 'https://www.apache.org/licenses/LICENSE-2.0.txt' + distribution = 'https://www.apache.org/licenses/LICENSE-2.0.txt' + } + } + + developers { + developer { + id = 'realtimetech' + name = 'RealtimeTech' + } + developer { + id = 'devjeonghwan' + name = 'Jeonghwan Park' + email = 'dev.parkjeonghwan@gmail.com' + } + developer { + id = 'rodamin' + name = 'Soyeon Kim' + email = 'epals8962@realtimetech.co.kr' + } + } + + scm { + connection = 'scm:git:https://github.com/realtimetech-solution/opack.git' + developerConnection = 'scm:git:ssh://git@github.com/realtimetech-solution/opack.git' + url = 'https://github.com/realtimetech-solution/opack' + } + } } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180..61285a6 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 442d913..19a6bde 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 744e882..adff685 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,114 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MSYS* | MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd3..c4bdd3a 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,32 +59,33 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/com/realtimetech/opack/Opacker.java b/src/main/java/com/realtimetech/opack/Opacker.java index faaf47d..2c5c076 100644 --- a/src/main/java/com/realtimetech/opack/Opacker.java +++ b/src/main/java/com/realtimetech/opack/Opacker.java @@ -38,9 +38,8 @@ import com.realtimetech.opack.transformer.impl.reflection.ClassTransformer; import com.realtimetech.opack.transformer.impl.time.CalendarTransformer; import com.realtimetech.opack.transformer.impl.time.DateTransformer; -import com.realtimetech.opack.transformer.impl.time.java8.LocalDateTimeTransformer; -import com.realtimetech.opack.transformer.impl.time.java8.LocalDateTransformer; -import com.realtimetech.opack.transformer.impl.time.java8.LocalTimeTransformer; +import com.realtimetech.opack.transformer.impl.time.java8.*; +import com.realtimetech.opack.transformer.impl.uuid.UUIDTransformer; import com.realtimetech.opack.util.OpackArrayConverter; import com.realtimetech.opack.util.ReflectionUtil; import com.realtimetech.opack.util.structure.FastStack; @@ -54,9 +53,7 @@ import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; +import java.time.*; import java.util.*; public class Opacker { @@ -186,13 +183,13 @@ public static final class Context { private @Nullable CapturedType superType; - private @Nullable CapturedType.FieldProperty currentFieldProperty; + private @Nullable CapturedType.FieldProperty fieldProperty; public Context(@NotNull Opacker opacker) { this.opacker = opacker; this.superType = null; - this.currentFieldProperty = null; + this.fieldProperty = null; } public @NotNull Opacker getOpacker() { @@ -207,17 +204,21 @@ public void setSuperType(@Nullable CapturedType superType) { this.superType = superType; } - public @Nullable CapturedType.FieldProperty getCurrentFieldProperty() { - return this.currentFieldProperty; + public @Nullable CapturedType.FieldProperty getFieldProperty() { + return this.fieldProperty; } - public void setCurrentFieldProperty(@Nullable CapturedType.FieldProperty currentFieldProperty) { - this.currentFieldProperty = currentFieldProperty; + public void setFieldProperty(@Nullable CapturedType.FieldProperty fieldProperty) { + this.fieldProperty = fieldProperty; } void clear() { this.superType = null; - this.currentFieldProperty = null; + this.fieldProperty = null; + } + + public @NotNull String getPositionString() { + return "{" + "superType=" + superType + ", fieldProperty=" + fieldProperty + '}'; } } @@ -279,6 +280,11 @@ public enum State { this.typeCapturer.registerPredefinedTransformer(LocalDate.class, LocalDateTransformer.class, true); this.typeCapturer.registerPredefinedTransformer(LocalTime.class, LocalTimeTransformer.class, true); this.typeCapturer.registerPredefinedTransformer(LocalDateTime.class, LocalDateTimeTransformer.class, true); + this.typeCapturer.registerPredefinedTransformer(OffsetTime.class, OffsetTimeTransformer.class, true); + this.typeCapturer.registerPredefinedTransformer(OffsetDateTime.class, OffsetDateTimeTransformer.class, true); + this.typeCapturer.registerPredefinedTransformer(ZonedDateTime.class, ZonedDateTimeTransformer.class, true); + + this.typeCapturer.registerPredefinedTransformer(UUID.class, UUIDTransformer.class, true); this.typeCapturer.registerPredefinedTransformer(Class.class, ClassTransformer.class, true); } catch (InstantiationException exception) { @@ -426,7 +432,7 @@ public enum State { if (this.overlapSet.contains(object)) { if (!this.enableConvertRecursiveDependencyToNull) { - throw new SerializeException("Recursive dependencies are not serializable."); + throw new SerializeException("Recursive dependencies are not serializable. " + this.context.getPositionString()); } return null; @@ -439,7 +445,7 @@ public enum State { return opackValue; } catch (TypeCaptureException exception) { - throw new SerializeException("Can't capture " + baseType.getName() + " class information.", exception); + throw new SerializeException("Can't capture " + baseType.getName() + " class information. " + this.context.getPositionString(), exception); } } @@ -460,7 +466,7 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { OpackArray opackArray = (OpackArray) opackValue; int length = Array.getLength(object); - this.context.setCurrentFieldProperty(null); + this.context.setFieldProperty(null); for (int index = 0; index < length; index++) { Object element = ReflectionUtil.getArrayItem(object, index); @@ -479,7 +485,7 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { Object element = fieldProperty.get(object); Class fieldType = fieldProperty.getType(); - this.context.setCurrentFieldProperty(fieldProperty); + this.context.setFieldProperty(fieldProperty); if (fieldProperty.isWithType()) { element = TypeWrapper.wrapObject(this.context, element); @@ -490,13 +496,15 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { } if (element != null) { - opackObject.put(fieldProperty.getName(), this.prepareObjectSerialize(fieldType, element)); + Class baseType = fieldProperty.isWithType() ? element.getClass() : fieldType; + + opackObject.put(fieldProperty.getName(), this.prepareObjectSerialize(baseType, element)); } else { opackObject.put(fieldProperty.getName(), null); } } catch (IllegalAccessException exception) { - throw new SerializeException("Can't get " + fieldProperty.getName() + " field data in " + capturedType.getType().getSimpleName() + ".", exception); + throw new SerializeException("Can't get " + fieldProperty.getName() + " field data in " + capturedType.getType().getSimpleName() + ". " + this.context.getPositionString(), exception); } } } @@ -566,6 +574,18 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { */ private synchronized @Nullable Object prepareObjectDeserialize(@NotNull Class goalType, @NotNull Object object, boolean withType, @Nullable Transformer fieldTransformer) throws DeserializeException { try { + if (withType) { + if (fieldTransformer != null) { + object = fieldTransformer.deserialize(this.context, goalType, object); + + if (object == null) { + return null; + } + } + + return TypeWrapper.unwrapObject(this.context, object); + } + CapturedType capturedType = this.typeCapturer.get(goalType); Transformer[] transformers = capturedType.getTransformers(); @@ -586,14 +606,6 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { } } - if (withType) { - object = TypeWrapper.unwrapObject(this.context, object); - - if (object == null) { - return null; - } - } - /* Early stopping */ @@ -644,7 +656,7 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { targetObject = Array.newInstance(goalType.getComponentType(), opackArray.length()); } else { - throw new DeserializeException("Target class is array. but, object is not OpackArray."); + throw new DeserializeException("Deserialize target class is array. but, object(" + object + ") is not OpackArray. " + this.context.getPositionString()); } } else { if (object instanceof OpackObject) { @@ -657,7 +669,7 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { throw new DeserializeException("Can't create instance using unsafe method.", exception); } } else { - throw new DeserializeException("Target class is object. but, object is not OpackObject."); + throw new DeserializeException("Deserialize target class is object. but, object(" + object + ") is not OpackObject. " + this.context.getPositionString()); } } @@ -669,10 +681,10 @@ private void executeSerializeStack(int endOfStack) throws SerializeException { } else if (goalType.isAssignableFrom(object.getClass())) { return object; } else { - throw new DeserializeException("Found object, stack corruption."); + throw new DeserializeException("Failed to convert object(" + object + ") to the specified goal type: " + goalType.getName() + ". This could be due to a missing Transformer. " + this.context.getPositionString()); } } catch (TypeCaptureException exception) { - throw new DeserializeException("Can't capture " + goalType.getName() + " class information.", exception); + throw new DeserializeException("Can't capture " + goalType.getName() + " class information. " + this.context.getPositionString(), exception); } } @@ -694,7 +706,7 @@ private void executeDeserializeStack(int endOfStack) throws DeserializeException Class componentType = object.getClass().getComponentType(); int length = opackArray.length(); - this.context.setCurrentFieldProperty(null); + this.context.setFieldProperty(null); for (int index = 0; index < length; index++) { Object element = opackArray.get(index); @@ -721,14 +733,14 @@ private void executeDeserializeStack(int endOfStack) throws DeserializeException Class fieldType = fieldProperty.getType(); Class actualFieldType = fieldProperty.getField().getType(); - this.context.setCurrentFieldProperty(fieldProperty); + this.context.setFieldProperty(fieldProperty); if (opackObject.containsKey(propertyName)) { element = opackObject.get(propertyName); } else if (fieldProperty.getDefaultValueProvider() != null) { element = fieldProperty.getDefaultValueProvider().provide(this.context, object, fieldProperty); } else { - throw new DeserializeException("Missing " + fieldProperty.getName() + " fieldProperty value of for " + capturedType.getType().getSimpleName() + " in given opack value."); + throw new DeserializeException("Missing " + fieldProperty.getName() + " field property value of for " + capturedType.getType().getSimpleName() + " in given opack value. " + this.context.getPositionString()); } Object propertyValue = null; @@ -743,7 +755,7 @@ private void executeDeserializeStack(int endOfStack) throws DeserializeException fieldProperty.set(object, propertyValue); } catch (IllegalAccessException | IllegalArgumentException exception) { - throw new DeserializeException("Can't set " + fieldProperty.getName() + " field in " + capturedType.getType().getSimpleName() + ".", exception); + throw new DeserializeException("Can't set " + fieldProperty.getName() + " field in " + capturedType.getType().getSimpleName() + ". " + this.context.getPositionString(), exception); } } } diff --git a/src/main/java/com/realtimetech/opack/capture/CapturedType.java b/src/main/java/com/realtimetech/opack/capture/CapturedType.java index 8fb24db..eb2f1ad 100644 --- a/src/main/java/com/realtimetech/opack/capture/CapturedType.java +++ b/src/main/java/com/realtimetech/opack/capture/CapturedType.java @@ -27,11 +27,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; +import java.util.*; public final class CapturedType { public static final class FieldProperty { @@ -39,6 +39,7 @@ public static final class FieldProperty { private final @NotNull String name; private final @NotNull Class type; private final @NotNull Class @NotNull [] genericTypes; + private final @NotNull Map, Annotation[]> annotations; private final boolean withType; private final @Nullable Transformer transformer; @@ -65,6 +66,19 @@ public FieldProperty(@NotNull Field field, @Nullable String name, @Nullable Clas this.genericTypes = genericTypes.toArray(new Class[0]); + Map, List> annotations = new HashMap<>(); + for (Annotation annotation : this.field.getAnnotations()) { + if (!annotations.containsKey(annotation.annotationType())) { + annotations.put(annotation.annotationType(), new LinkedList()); + } + annotations.get(annotation.annotationType()).add(annotation); + } + + this.annotations = new HashMap<>(); + for (Map.Entry, List> entry : annotations.entrySet()) { + this.annotations.put(entry.getKey(), entry.getValue().toArray(new Annotation[0])); + } + this.withType = withType; this.transformer = transformer; @@ -87,6 +101,29 @@ public FieldProperty(@NotNull Field field, @Nullable String name, @Nullable Clas return genericTypes; } + public @Nullable Class getGenericType(int index) { + if (index < 0 || index >= genericTypes.length) { + return null; + } + + return genericTypes[index]; + } + + public @NotNull Map, Annotation[]> getAnnotations() { + return annotations; + } + + @SuppressWarnings("unchecked") + public @NotNull T @Nullable [] getAnnotations(Class annotationType) { + return (T[]) annotations.get(annotationType); + } + + @SuppressWarnings("unchecked") + public @Nullable T getAnnotation(Class annotationType) { + Annotation[] annotations = this.annotations.get(annotationType); + return annotations != null && annotations.length > 0 ? (T) annotations[0] : null; + } + public boolean isWithType() { return withType; } diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/list/ListTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/list/ListTransformer.java index 4096b09..a91e9cd 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/list/ListTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/list/ListTransformer.java @@ -81,9 +81,8 @@ public class ListTransformer extends DataStructureTransformer { List list = (List) ReflectionUtil.createInstance(goalType); Class genericType = null; - if (context.getCurrentFieldProperty() != null) { - Class[] genericTypes = context.getCurrentFieldProperty().getGenericTypes(); - genericType = genericTypes.length > 0 ? genericTypes[0] : null; + if (context.getFieldProperty() != null) { + genericType = context.getFieldProperty().getGenericType(0); } for (int index = 0; index < opackArray.length(); index++) { diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/map/MapTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/map/MapTransformer.java index bac2d4a..f6ebba7 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/map/MapTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/map/MapTransformer.java @@ -87,10 +87,9 @@ public class MapTransformer extends DataStructureTransformer { Class keyGenericType = null; Class valueGenericType = null; - if (context.getCurrentFieldProperty() != null) { - Class[] genericTypes = context.getCurrentFieldProperty().getGenericTypes(); - keyGenericType = genericTypes.length > 0 ? genericTypes[0] : null; - valueGenericType = genericTypes.length > 1 ? genericTypes[1] : null; + if (context.getFieldProperty() != null) { + keyGenericType = context.getFieldProperty().getGenericType(0); + valueGenericType = context.getFieldProperty().getGenericType(1); } for (Map.Entry element : opackObject.entrySet()) { diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/CalendarTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/CalendarTransformer.java index a4b7306..a9d9cdb 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/time/CalendarTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/CalendarTransformer.java @@ -23,10 +23,15 @@ package com.realtimetech.opack.transformer.impl.time; import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.capture.CapturedType; +import com.realtimetech.opack.exception.DeserializeException; import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @@ -42,7 +47,18 @@ public class CalendarTransformer implements Transformer { @Override public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { if (object instanceof Calendar) { - return ((Calendar) object).getTime().getTime(); + Calendar calendar = (Calendar) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return new SimpleDateFormat(timeFormat.value()).format(calendar.getTime()); + } + } + + return calendar.getTime().getTime(); } return object; @@ -57,8 +73,25 @@ public class CalendarTransformer implements Transformer { * @return the deserialized value */ @Override - public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { - if (object instanceof Long) { + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { + if (object instanceof String) { + Calendar calendar = Calendar.getInstance(); + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + try { + calendar.setTime(new SimpleDateFormat(timeFormat.value()).parse((String) object)); + } catch (ParseException parseException) { + throw new DeserializeException(parseException); + } + + return calendar; + } + } + } else if (object instanceof Long) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date((Long) object)); diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/DateTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/DateTransformer.java index 8ffcd76..8304f08 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/time/DateTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/DateTransformer.java @@ -23,10 +23,15 @@ package com.realtimetech.opack.transformer.impl.time; import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.capture.CapturedType; +import com.realtimetech.opack.exception.DeserializeException; import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.Date; public class DateTransformer implements Transformer { @@ -41,7 +46,18 @@ public class DateTransformer implements Transformer { @Override public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { if (object instanceof Date) { - return ((Date) object).getTime(); + Date date = (Date) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return new SimpleDateFormat(timeFormat.value()).format(date); + } + } + + return date.getTime(); } return object; @@ -54,10 +70,25 @@ public class DateTransformer implements Transformer { * @param goalType the goal type to deserialize * @param object the object to be deserialized * @return the deserialized value + * @throws DeserializeException if a problem occurs during deserializing */ @Override - public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { - if (object instanceof Long) { + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { + if (object instanceof String) { + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + try { + return new SimpleDateFormat(timeFormat.value()).parse((String) object); + } catch (ParseException parseException) { + throw new DeserializeException(parseException); + } + } + } + } else if (object instanceof Long) { return new Date((Long) object); } diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/annotation/TimeFormat.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/annotation/TimeFormat.java new file mode 100644 index 0000000..cad44e6 --- /dev/null +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/annotation/TimeFormat.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2025 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.transformer.impl.time.annotation; + +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Fields annotated with @TimeFormat("pattern") will be serialized and deserialized using a given time format + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ + ElementType.FIELD, +}) +public @interface TimeFormat { + /** + * @return the time format pattern to be used when serialize or deserialize + */ + @NotNull String value(); +} \ No newline at end of file diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTimeTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTimeTransformer.java index a182dd5..b3d3a7a 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTimeTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTimeTransformer.java @@ -23,12 +23,15 @@ package com.realtimetech.opack.transformer.impl.time.java8; import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.capture.CapturedType; import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import com.realtimetech.opack.value.OpackArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; public class LocalDateTimeTransformer implements Transformer { /** @@ -43,6 +46,15 @@ public class LocalDateTimeTransformer implements Transformer { public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { if (object instanceof LocalDateTime) { LocalDateTime localDateTime = (LocalDateTime) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return localDateTime.format(DateTimeFormatter.ofPattern(timeFormat.value())); + } + } return OpackArray.createWithArrayObject( new int[]{ @@ -70,7 +82,18 @@ public class LocalDateTimeTransformer implements Transformer { */ @Override public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { - if (object instanceof OpackArray) { + if (object instanceof String) { + String string = (String) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return LocalDateTime.parse(string, DateTimeFormatter.ofPattern(timeFormat.value())); + } + } + } else if (object instanceof OpackArray) { OpackArray opackArray = (OpackArray) object; if (opackArray.length() == 7) { diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTransformer.java index a3db74f..fe549bd 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalDateTransformer.java @@ -23,12 +23,15 @@ package com.realtimetech.opack.transformer.impl.time.java8; import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.capture.CapturedType; import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import com.realtimetech.opack.value.OpackArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; public class LocalDateTransformer implements Transformer { /** @@ -43,6 +46,15 @@ public class LocalDateTransformer implements Transformer { public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { if (object instanceof LocalDate) { LocalDate localDate = (LocalDate) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return localDate.format(DateTimeFormatter.ofPattern(timeFormat.value())); + } + } return OpackArray.createWithArrayObject( new int[]{ @@ -66,7 +78,18 @@ public class LocalDateTransformer implements Transformer { */ @Override public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { - if (object instanceof OpackArray) { + if (object instanceof String) { + String string = (String) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return LocalDate.parse(string, DateTimeFormatter.ofPattern(timeFormat.value())); + } + } + } else if (object instanceof OpackArray) { OpackArray opackArray = (OpackArray) object; if (opackArray.length() == 3) { diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalTimeTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalTimeTransformer.java index 0ae76d7..4c2bde8 100644 --- a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalTimeTransformer.java +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/LocalTimeTransformer.java @@ -23,12 +23,15 @@ package com.realtimetech.opack.transformer.impl.time.java8; import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.capture.CapturedType; import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import com.realtimetech.opack.value.OpackArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.LocalTime; +import java.time.format.DateTimeFormatter; public class LocalTimeTransformer implements Transformer { /** @@ -43,6 +46,15 @@ public class LocalTimeTransformer implements Transformer { public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { if (object instanceof LocalTime) { LocalTime localTime = (LocalTime) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return localTime.format(DateTimeFormatter.ofPattern(timeFormat.value())); + } + } return OpackArray.createWithArrayObject( new int[]{ @@ -67,7 +79,18 @@ public class LocalTimeTransformer implements Transformer { */ @Override public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { - if (object instanceof OpackArray) { + if (object instanceof String) { + String string = (String) object; + CapturedType.FieldProperty fieldProperty = context.getFieldProperty(); + + if (fieldProperty != null) { + TimeFormat timeFormat = fieldProperty.getField().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + return LocalTime.parse(string, DateTimeFormatter.ofPattern(timeFormat.value())); + } + } + } else if (object instanceof OpackArray) { OpackArray opackArray = (OpackArray) object; if (opackArray.length() == 4) { diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetDateTimeTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetDateTimeTransformer.java new file mode 100644 index 0000000..2857124 --- /dev/null +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetDateTimeTransformer.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2022 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.transformer.impl.time.java8; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +public class OffsetDateTimeTransformer implements Transformer { + /** + * Serialize specific value to opack value + * + * @param context the opacker context + * @param originalType the original type + * @param object the object to be serialized + * @return the opack value + */ + @Override + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { + if (object instanceof OffsetDateTime) { + OffsetDateTime offsetDateTime = (OffsetDateTime) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return offsetDateTime.format(dateTimeFormatter); + } + + return object; + } + + /** + * Deserialize opack value + * + * @param context the opacker context + * @param goalType the goal type to deserialize + * @param object the object to be deserialized + * @return the deserialized value + */ + @Override + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { + if (object instanceof String) { + String string = (String) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return OffsetDateTime.parse(string, dateTimeFormatter); + } + + return object; + } +} diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetTimeTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetTimeTransformer.java new file mode 100644 index 0000000..e61393c --- /dev/null +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/OffsetTimeTransformer.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2022 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.transformer.impl.time.java8; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.time.OffsetTime; +import java.time.format.DateTimeFormatter; + +public class OffsetTimeTransformer implements Transformer { + /** + * Serialize specific value to opack value + * + * @param context the opacker context + * @param originalType the original type + * @param object the object to be serialized + * @return the opack value + */ + @Override + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { + if (object instanceof OffsetTime) { + OffsetTime offsetTime = (OffsetTime) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return offsetTime.format(dateTimeFormatter); + } + + return object; + } + + /** + * Deserialize opack value + * + * @param context the opacker context + * @param goalType the goal type to deserialize + * @param object the object to be deserialized + * @return the deserialized value + */ + @Override + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { + if (object instanceof String) { + String string = (String) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return OffsetTime.parse(string, dateTimeFormatter); + } + + return object; + } +} diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/ZonedDateTimeTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/ZonedDateTimeTransformer.java new file mode 100644 index 0000000..6bb0653 --- /dev/null +++ b/src/main/java/com/realtimetech/opack/transformer/impl/time/java8/ZonedDateTimeTransformer.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2022 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.transformer.impl.time.java8; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.transformer.Transformer; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class ZonedDateTimeTransformer implements Transformer { + /** + * Serialize specific value to opack value + * + * @param context the opacker context + * @param originalType the original type + * @param object the object to be serialized + * @return the opack value + */ + @Override + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) { + if (object instanceof ZonedDateTime) { + ZonedDateTime zonedDateTime = (ZonedDateTime) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return zonedDateTime.format(dateTimeFormatter); + } + + return object; + } + + /** + * Deserialize opack value + * + * @param context the opacker context + * @param goalType the goal type to deserialize + * @param object the object to be deserialized + * @return the deserialized value + */ + @Override + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) { + if (object instanceof String) { + String string = (String) object; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + + if (context.getFieldProperty() != null) { + TimeFormat timeFormat = context.getFieldProperty().getAnnotation(TimeFormat.class); + + if (timeFormat != null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat.value()); + } + } + + return ZonedDateTime.parse(string, dateTimeFormatter); + } + + return object; + } +} diff --git a/src/main/java/com/realtimetech/opack/transformer/impl/uuid/UUIDTransformer.java b/src/main/java/com/realtimetech/opack/transformer/impl/uuid/UUIDTransformer.java new file mode 100644 index 0000000..a338df4 --- /dev/null +++ b/src/main/java/com/realtimetech/opack/transformer/impl/uuid/UUIDTransformer.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2025 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.transformer.impl.uuid; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.exception.DeserializeException; +import com.realtimetech.opack.exception.SerializeException; +import com.realtimetech.opack.transformer.Transformer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +public class UUIDTransformer implements Transformer { + /** + * Serialize specific value to opack value + * + * @param context the opacker context + * @param originalType the original type + * @param object the object to be serialized + * @return the opack value + * @throws SerializeException if a problem occurs during serializing + */ + @Override + public @Nullable Object serialize(@NotNull Opacker.Context context, @NotNull Class originalType, @Nullable Object object) throws SerializeException { + if (object instanceof UUID) { + return ((UUID) object).toString(); + } + + return object; + } + + /** + * Deserialize opack value + * + * @param context the opacker context + * @param goalType the goal type to deserialize + * @param object the object to be deserialized + * @return the deserialized value + * @throws DeserializeException if a problem occurs during deserializing + */ + @Override + public @Nullable Object deserialize(@NotNull Opacker.Context context, @NotNull Class goalType, @Nullable Object object) throws DeserializeException { + if (object instanceof String) { + return UUID.fromString(String.valueOf(object)); + } + + return object; + } +} diff --git a/src/main/java/com/realtimetech/opack/util/ReflectionUtil.java b/src/main/java/com/realtimetech/opack/util/ReflectionUtil.java index facfc78..73f2419 100644 --- a/src/main/java/com/realtimetech/opack/util/ReflectionUtil.java +++ b/src/main/java/com/realtimetech/opack/util/ReflectionUtil.java @@ -28,6 +28,8 @@ import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.lang.reflect.*; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.LinkedList; import java.util.List; @@ -145,6 +147,10 @@ private static abstract class Allocator { return number.doubleValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); + } else if (type == BigInteger.class) { + return BigInteger.valueOf(number.longValue()); + } else if (type == BigDecimal.class) { + return BigDecimal.valueOf(number.doubleValue()); } } else if (objectType == Boolean.class) { if (type == boolean.class || type == Boolean.class) { diff --git a/src/test/java/com/realtimetech/opack/test/OpackAssert.java b/src/test/java/com/realtimetech/opack/test/OpackAssert.java index 1a6d2ac..a7f3f8a 100644 --- a/src/test/java/com/realtimetech/opack/test/OpackAssert.java +++ b/src/test/java/com/realtimetech/opack/test/OpackAssert.java @@ -30,9 +30,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.file.Path; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; +import java.time.*; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -163,6 +161,18 @@ static void assertSingleValue(Object originalObject, Object targetObject) throws if (!originalObject.equals(targetObject)) { OpackAssert.throwException(originalObject, targetObject); } + } else if (originalObject instanceof OffsetDateTime) { + if (!((OffsetDateTime) originalObject).isEqual((OffsetDateTime) targetObject)) { + OpackAssert.throwException(originalObject, targetObject); + } + } else if (originalObject instanceof OffsetTime) { + if (!((OffsetTime) originalObject).isEqual((OffsetTime) targetObject)) { + OpackAssert.throwException(originalObject, targetObject); + } + } else if (originalObject instanceof ZonedDateTime) { + if (!((ZonedDateTime) originalObject).isEqual((ZonedDateTime) targetObject)) { + OpackAssert.throwException(originalObject, targetObject); + } } else if ((originalObject instanceof File && targetObject instanceof File) || (originalObject instanceof Path && targetObject instanceof Path) || (originalObject instanceof Date && targetObject instanceof Date) || diff --git a/src/test/java/com/realtimetech/opack/test/RandomUtil.java b/src/test/java/com/realtimetech/opack/test/RandomUtil.java index cac2ce5..d12d52b 100644 --- a/src/test/java/com/realtimetech/opack/test/RandomUtil.java +++ b/src/test/java/com/realtimetech/opack/test/RandomUtil.java @@ -24,7 +24,9 @@ import org.jetbrains.annotations.NotNull; +import java.math.BigDecimal; import java.util.Random; +import java.util.UUID; public class RandomUtil { private static final long SEED = 3783655506793900820L; @@ -38,6 +40,10 @@ public static int nextInt(int bound) { return RANDOM.nextInt(bound); } + public static int nextInt(int min, int max) { + return RANDOM.nextInt(max - min) + min; + } + public static float nextFloat() { return RANDOM.nextFloat(); } @@ -50,7 +56,37 @@ public static double nextDouble() { return RANDOM.nextDouble(); } + public static double nextDouble(double min, double max) { + return RANDOM.nextDouble() * (max - min) + min; + } + public static long nextLong() { return RANDOM.nextLong(); } + + public static @NotNull String randomAlphabetic(int length) { + StringBuilder builder = new StringBuilder(length); + for (int i = 0; i < length; i++) { + builder.append((char) (RANDOM.nextInt(26) + 'a')); + } + return builder.toString(); + } + + public static @NotNull String randomAlphanumeric(int length) { + StringBuilder builder = new StringBuilder(length); + for (int i = 0; i < length; i++) { + builder.append((char) (RANDOM.nextInt(122 - 48) + 48)); + } + return builder.toString(); + } + + public static @NotNull UUID nextUUID() { + long mostSignificantBits = RANDOM.nextLong(); + long leastSignificantBits = RANDOM.nextLong(); + return new UUID(mostSignificantBits, leastSignificantBits); + } + + public static @NotNull BigDecimal randomBigDecimal() { + return BigDecimal.valueOf(nextDouble()); + } } diff --git a/src/test/java/com/realtimetech/opack/test/opacker/annotation/AnnotationWithTypeMapTest.java b/src/test/java/com/realtimetech/opack/test/opacker/annotation/AnnotationWithTypeMapTest.java new file mode 100644 index 0000000..e7010c1 --- /dev/null +++ b/src/test/java/com/realtimetech/opack/test/opacker/annotation/AnnotationWithTypeMapTest.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2026 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.test.opacker.annotation; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.annotation.WithType; +import com.realtimetech.opack.codec.json.JsonCodec; +import com.realtimetech.opack.exception.DecodeException; +import com.realtimetech.opack.exception.DeserializeException; +import com.realtimetech.opack.exception.EncodeException; +import com.realtimetech.opack.exception.SerializeException; +import com.realtimetech.opack.test.OpackAssert; +import com.realtimetech.opack.value.OpackValue; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; + +public class AnnotationWithTypeMapTest { + @SuppressWarnings("ALL") + public static class WithTypeMapClass { + @WithType + private Map hashMap; + + @WithType + private Map linkedHashMap; + + @WithType + private Map treeMap; + + public WithTypeMapClass() { + this.hashMap = new HashMap<>(); + this.hashMap.put("string", "hash-map"); + this.hashMap.put("number", 1L); + + this.linkedHashMap = new LinkedHashMap<>(); + this.linkedHashMap.put("string", "linked-hash-map"); + this.linkedHashMap.put("number", 2L); + + this.treeMap = new TreeMap<>(); + this.treeMap.put("string", "tree-map"); + this.treeMap.put("number", 3L); + } + } + + @Test + public void testOpackRoundTrip() throws SerializeException, DeserializeException, OpackAssert.AssertException { + for (boolean enableWrapMapElementType : new boolean[]{false, true}) { + Opacker opacker = Opacker.Builder.create() + .setEnableWrapMapElementType(enableWrapMapElementType) + .build(); + WithTypeMapClass originalObject = new WithTypeMapClass(); + + OpackValue serialized = opacker.serialize(originalObject); + assert serialized != null; + WithTypeMapClass deserialized = opacker.deserialize(WithTypeMapClass.class, serialized); + + OpackAssert.assertEquals(originalObject, deserialized); + } + } + + @Test + public void testJsonRoundTrip() throws SerializeException, DeserializeException, EncodeException, DecodeException, OpackAssert.AssertException { + JsonCodec jsonCodec = JsonCodec.Builder.create().build(); + + for (boolean enableWrapMapElementType : new boolean[]{false, true}) { + Opacker opacker = Opacker.Builder.create() + .setEnableWrapMapElementType(enableWrapMapElementType) + .build(); + WithTypeMapClass originalObject = new WithTypeMapClass(); + + OpackValue serialized = opacker.serialize(originalObject); + assert serialized != null; + String encoded = jsonCodec.encode(serialized); + OpackValue decoded = jsonCodec.decode(encoded); + WithTypeMapClass deserialized = opacker.deserialize(WithTypeMapClass.class, decoded); + + OpackAssert.assertEquals(originalObject, deserialized); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/realtimetech/opack/test/opacker/other/JavaJsonBenchmarkTest.java b/src/test/java/com/realtimetech/opack/test/opacker/other/JavaJsonBenchmarkTest.java new file mode 100644 index 0000000..e35741d --- /dev/null +++ b/src/test/java/com/realtimetech/opack/test/opacker/other/JavaJsonBenchmarkTest.java @@ -0,0 +1,514 @@ +/* + * Copyright (C) 2025 REALTIMETECH All Rights Reserved + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.realtimetech.opack.test.opacker.other; + +import com.realtimetech.opack.Opacker; +import com.realtimetech.opack.annotation.Type; +import com.realtimetech.opack.exception.DeserializeException; +import com.realtimetech.opack.exception.SerializeException; +import com.realtimetech.opack.test.OpackAssert; +import com.realtimetech.opack.test.RandomUtil; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; +import com.realtimetech.opack.value.OpackValue; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.*; + +public class JavaJsonBenchmarkTest { + public static class Clients { + @Type(ArrayList.class) + private List clients; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Clients)) { + return false; + } + + Clients that = (Clients) o; + + return Objects.equals(clients, that.clients); + } + + @Override + public int hashCode() { + return Objects.hashCode(clients); + } + + @Override + public String toString() { + return "Clients{" + "clients=" + clients + '}'; + } + + public List getClients() { + return clients; + } + + public void setClients(List clients) { + this.clients = clients; + } + + public static final class Client { + private long id; + private int index; + private UUID guid; + private boolean isActive; + private BigDecimal balance; + private String picture; + private int age; + private EyeColor eyeColor; + private String name; + private String gender; + private String company; + private String[] emails; + private long[] phones; + private String address; + private String about; + @TimeFormat("yyyy-MM-dd") + private LocalDate registered; + private double latitude; + private double longitude; + @Type(ArrayList.class) + private List tags; + @Type(ArrayList.class) + private List partners; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Client)) { + return false; + } + + Client client = (Client) o; + + return index == client.index && + isActive == client.isActive && + age == client.age && + Math.abs(Double.doubleToLongBits(client.latitude) - Double.doubleToLongBits(latitude)) < 3 && + Math.abs(Double.doubleToLongBits(client.longitude) - Double.doubleToLongBits(longitude)) < 3 && + Objects.equals(id, client.id) && + Objects.equals(guid, client.guid) && + balance.compareTo(client.balance) == 0 && + Objects.equals(picture, client.picture) && + Objects.equals(eyeColor, client.eyeColor) && + Objects.equals(name, client.name) && + Objects.equals(gender, client.gender) && + Objects.equals(company, client.company) && + Arrays.equals(emails, client.emails) && + Arrays.equals(phones, client.phones) && + Objects.equals(address, client.address) && + Objects.equals(about, client.about) && + Objects.equals(registered, client.registered) && + Objects.equals(tags, client.tags) && + Objects.equals(partners, client.partners); + } + + @Override + public int hashCode() { + return Objects.hash(id, index, guid, isActive, balance, picture, age, eyeColor, name, gender, company, + Arrays.hashCode(emails), Arrays.hashCode(phones), address, about, registered, tags, partners); + } + + private String toStr(long[] nums) { + StringBuilder sb = new StringBuilder(); + sb.append('['); + boolean first = true; + for (long l : nums) { + if (first) first = false; + else sb.append(','); + sb.append(l); + } + sb.append(']'); + return sb.toString(); + } + + @Override + public String toString() { + return "JsonDataObj{" + "id=" + id + ", index=" + index + ", guid=" + guid + ", isActive=" + isActive + ", balance=" + balance + ", picture=" + picture + ", age=" + age + ", eyeColor=" + eyeColor + ", name=" + name + ", gender=" + gender + ", company=" + company + ", emails=" + (emails != null ? Arrays.asList(emails) : null) + ", phones=" + toStr(phones) + ", address=" + address + ", about=" + about + ", registered=" + registered + ", latitude=" + latitude + ", longitude=" + longitude + ", tags=" + tags + ", partners=" + partners + '}'; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public UUID getGuid() { + return guid; + } + + public void setGuid(UUID guid) { + this.guid = guid; + } + + public boolean getIsActive() { + return isActive; + } + + public void setIsActive(boolean isActive) { + this.isActive = isActive; + } + + public BigDecimal getBalance() { + return balance; + } + + public void setBalance(BigDecimal balance) { + this.balance = balance; + } + + public String getPicture() { + return picture; + } + + public void setPicture(String picture) { + this.picture = picture; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public EyeColor getEyeColor() { + return eyeColor; + } + + public void setEyeColor(EyeColor eyeColor) { + this.eyeColor = eyeColor; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String[] getEmails() { + return emails; + } + + public void setEmails(String[] emails) { + this.emails = emails; + } + + public long[] getPhones() { + return phones; + } + + public void setPhones(long[] phones) { + this.phones = phones; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getAbout() { + return about; + } + + public void setAbout(String about) { + this.about = about; + } + + public LocalDate getRegistered() { + return registered; + } + + public void setRegistered(LocalDate registered) { + this.registered = registered; + } + + public double getLatitude() { + return latitude; + } + + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public List getPartners() { + return partners; + } + + public void setPartners(List partners) { + this.partners = partners; + } + } + + public enum EyeColor { + BROWN, + BLUE, + GREEN; + + public static EyeColor fromNumber(int i) { + if (i == 0) return BROWN; + if (i == 1) return BLUE; + return GREEN; + } + } + + public static final class Partner { + private long id; + private String name; + private OffsetDateTime since; + + public Partner() { + } + + public static Partner create(long id, String name, OffsetDateTime since) { + Partner partner = new Partner(); + partner.id = id; + partner.name = name; + partner.since = since; + return partner; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Partner)) { + return false; + } + + Partner partner = (Partner) o; + + return id == partner.id && + Objects.equals(since, partner.since) && + Objects.equals(name, partner.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, since, name); + } + + @Override + public String toString() { + return "Partner{" + "id=" + id + ", name=" + name + ", since=" + since + '}'; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public OffsetDateTime getSince() { + return since; + } + + public void setSince(OffsetDateTime since) { + this.since = since; + } + } + } + + public static void fillClients(Clients clients, int size) { + clients.setClients(new ArrayList<>()); + + for (int i = 0; i < size; i++) { + appendClient(clients); + } + } + + private static int appendClient(Clients uc) { + int expectedSize = 2; // {} + + Clients.Client u = new Clients.Client(); + u.setId(Math.abs(RandomUtil.nextLong())); + expectedSize += 9 + Long.toString(u.getId()).length(); // ,'id':'' + u.setIndex(RandomUtil.nextInt(0, Integer.MAX_VALUE)); + expectedSize += 11 + Integer.toString(u.getIndex()).length(); // ,'index':'' + u.setGuid(RandomUtil.nextUUID()); + expectedSize += 10 + 36; // ,'guid':'' + u.setIsActive(RandomUtil.nextInt(0, 2) == 1); + expectedSize += 17 + (u.getIsActive() ? 4 : 5); // ,'isActive':'' + u.setBalance(RandomUtil.randomBigDecimal()); + expectedSize += 16 + u.getBalance().toPlainString().length(); // ,'balance':'' + u.setPicture(RandomUtil.randomAlphanumeric(100)); + expectedSize += 16 + u.getPicture().length(); // ,'picture':'' + u.setAge(RandomUtil.nextInt(0, 100)); + expectedSize += 9 + Integer.toString(u.getAge()).length(); // ,'age':'' + u.setEyeColor(Clients.EyeColor.fromNumber(RandomUtil.nextInt(3))); + expectedSize += 17 + u.getEyeColor().name().length(); // ,'eyeColor':'' + u.setName(RandomUtil.randomAlphanumeric(20)); + expectedSize += 10 + u.getName().length(); // ,'name':'' + u.setGender(RandomUtil.randomAlphanumeric(20)); + expectedSize += 12 + u.getGender().length(); // ,'gender':'' + u.setCompany(RandomUtil.randomAlphanumeric(20)); + expectedSize += 13 + u.getCompany().length(); // ,'company':'' + u.setEmails(new String[]{ + RandomUtil.randomAlphabetic(RandomUtil.nextInt(100)), + RandomUtil.randomAlphabetic(RandomUtil.nextInt(100)), + RandomUtil.randomAlphabetic(RandomUtil.nextInt(100)) + }); + int calcSize = 0; + for (String e : u.getEmails()) { + calcSize += 3 + e.length(); + } + expectedSize += 11 + calcSize; // ,'email':'' + u.setPhones(new long[]{ + RandomUtil.nextInt(10), + RandomUtil.nextInt(10), + RandomUtil.nextInt(10), + RandomUtil.nextInt(10) + }); + calcSize = 0; + for (long p : u.getPhones()) { + calcSize += 1 + Long.toString(p).length(); + } + expectedSize += 11 + calcSize; // ,'phone':'' + u.setAddress(RandomUtil.randomAlphanumeric(20)); + expectedSize += 13 + u.getAddress().length(); // ,'address':'' + u.setAbout(RandomUtil.randomAlphanumeric(20)); + expectedSize += 11 + u.getAbout().length(); // ,'about':'' + u.setRegistered(LocalDate.of(1900 + RandomUtil.nextInt(110), 1 + RandomUtil.nextInt(12), 1 + RandomUtil.nextInt(28))); + expectedSize += 16 + 10; // ,'registered':'' + u.setLatitude(RandomUtil.nextDouble(0, 90)); + expectedSize += 14 + Double.toString(u.getLatitude()).length(); // ,'latitude':'' + u.setLongitude(RandomUtil.nextDouble(0, 180)); + expectedSize += 15 + Double.toString(u.getLongitude()).length(); // ,'longitude':'' + + u.setTags(new ArrayList<>()); + expectedSize += 10; // ,'tags':[] + int nTags = RandomUtil.nextInt(0, 50); + for (int i = 0; i < nTags; i++) { + String t = RandomUtil.randomAlphanumeric(10); + u.getTags().add(t); + expectedSize += t.length(); // '', + } + + int nPartners = RandomUtil.nextInt(0, 30); + u.setPartners(new ArrayList<>()); + expectedSize += 13; // ,'partners':[] + for (int i = 0; i < nPartners; i++) { + long id = RandomUtil.nextLong(); + String name = RandomUtil.randomAlphabetic(30); + OffsetDateTime at = OffsetDateTime.of( + 1900 + RandomUtil.nextInt(110), + 1 + RandomUtil.nextInt(12), + 1 + RandomUtil.nextInt(28), + RandomUtil.nextInt(24), + RandomUtil.nextInt(60), + RandomUtil.nextInt(60), + RandomUtil.nextInt(1000000000), + ZoneOffset.UTC + ); + u.getPartners().add(Clients.Partner.create(id, name, at)); + expectedSize += Long.toString(id).length() + name.length() + 50; // {'id':'','name':'','since':''}, + } + + uc.getClients().add(u); + + return expectedSize; + } + + @Test + public void test() throws SerializeException, DeserializeException, OpackAssert.AssertException { + Clients clients = new Clients(); + fillClients(clients, 8); + + Opacker opacker = Opacker.Builder.create().build(); + + OpackValue serialized = opacker.serialize(clients); + assert serialized != null; + Clients deserialized = opacker.deserialize(Clients.class, serialized); + + OpackAssert.assertEquals(clients, deserialized); + } +} \ No newline at end of file diff --git a/src/test/java/com/realtimetech/opack/test/opacker/transform/time/Java8TimeTransformTest.java b/src/test/java/com/realtimetech/opack/test/opacker/transform/time/Java8TimeTransformTest.java index f20166c..866e7a2 100644 --- a/src/test/java/com/realtimetech/opack/test/opacker/transform/time/Java8TimeTransformTest.java +++ b/src/test/java/com/realtimetech/opack/test/opacker/transform/time/Java8TimeTransformTest.java @@ -26,12 +26,11 @@ import com.realtimetech.opack.exception.DeserializeException; import com.realtimetech.opack.exception.SerializeException; import com.realtimetech.opack.test.OpackAssert; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import com.realtimetech.opack.value.OpackValue; import org.junit.jupiter.api.Test; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; +import java.time.*; public class Java8TimeTransformTest { @SuppressWarnings("ALL") @@ -40,10 +39,45 @@ public static class Java8TimeTransformClass { private LocalTime localTime; private LocalDateTime localDateTime; + private OffsetTime offsetTime; + private OffsetDateTime offsetDateTime; + private ZonedDateTime zonedDateTime; + public Java8TimeTransformClass() { this.localDate = LocalDate.now(); this.localTime = LocalTime.now(); this.localDateTime = LocalDateTime.now(); + + this.offsetTime = OffsetTime.now(); + this.offsetDateTime = OffsetDateTime.now(); + this.zonedDateTime = ZonedDateTime.now(); + } + } + + @SuppressWarnings("ALL") + public static class Java8TimeTransformWithFormatClass { + @TimeFormat("yyyy-MM-dd") + private LocalDate localDate; + @TimeFormat("HH:mm:ss.SSSSSSSSS") + private LocalTime localTime; + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private LocalDateTime localDateTime; + + @TimeFormat("HH:mm:ss.SSSSSSSSSXXXZ") + private OffsetTime offsetTime; + @TimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXZ") + private OffsetDateTime offsetDateTime; + @TimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXZ") + private ZonedDateTime zonedDateTime; + + public Java8TimeTransformWithFormatClass() { + this.localDate = LocalDate.now(); + this.localTime = LocalTime.now(); + this.localDateTime = LocalDateTime.now(); + + this.offsetTime = OffsetTime.now(); + this.offsetDateTime = OffsetDateTime.now(); + this.zonedDateTime = ZonedDateTime.now(); } } @@ -58,4 +92,16 @@ public void test() throws SerializeException, DeserializeException, OpackAssert. OpackAssert.assertEquals(originalObject, deserialized); } + + @Test + public void test_with_format() throws SerializeException, DeserializeException, OpackAssert.AssertException { + Opacker opacker = Opacker.Builder.create().build(); + Java8TimeTransformWithFormatClass originalObject = new Java8TimeTransformWithFormatClass(); + + OpackValue serialized = opacker.serialize(originalObject); + assert serialized != null; + Java8TimeTransformWithFormatClass deserialized = opacker.deserialize(Java8TimeTransformWithFormatClass.class, serialized); + + OpackAssert.assertEquals(originalObject, deserialized); + } } diff --git a/src/test/java/com/realtimetech/opack/test/opacker/transform/time/TimeTransformTest.java b/src/test/java/com/realtimetech/opack/test/opacker/transform/time/TimeTransformTest.java index 6127764..c0915ae 100644 --- a/src/test/java/com/realtimetech/opack/test/opacker/transform/time/TimeTransformTest.java +++ b/src/test/java/com/realtimetech/opack/test/opacker/transform/time/TimeTransformTest.java @@ -26,6 +26,7 @@ import com.realtimetech.opack.exception.DeserializeException; import com.realtimetech.opack.exception.SerializeException; import com.realtimetech.opack.test.OpackAssert; +import com.realtimetech.opack.transformer.impl.time.annotation.TimeFormat; import com.realtimetech.opack.value.OpackValue; import org.junit.jupiter.api.Test; @@ -46,6 +47,21 @@ public TimeTransformClass() { } } + @SuppressWarnings("ALL") + public static class TimeTransformWithFormatClass { + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private Date date; + @TimeFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS") + private Calendar calendar; + + public TimeTransformWithFormatClass() { + this.date = new Date(); + + this.calendar = Calendar.getInstance(); + this.calendar.setTime(new Date()); + } + } + @Test public void test() throws SerializeException, DeserializeException, OpackAssert.AssertException { Opacker opacker = Opacker.Builder.create().build(); @@ -57,4 +73,16 @@ public void test() throws SerializeException, DeserializeException, OpackAssert. OpackAssert.assertEquals(originalObject, deserialized); } + + @Test + public void test_with_format() throws SerializeException, DeserializeException, OpackAssert.AssertException { + Opacker opacker = Opacker.Builder.create().build(); + TimeTransformWithFormatClass originalObject = new TimeTransformWithFormatClass(); + + OpackValue serialized = opacker.serialize(originalObject); + assert serialized != null; + TimeTransformWithFormatClass deserialized = opacker.deserialize(TimeTransformWithFormatClass.class, serialized); + + OpackAssert.assertEquals(originalObject, deserialized); + } }