diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 22777bbd7..ff79cf711 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -17,6 +17,9 @@ jobs: test: uses: ./.github/workflows/test.yml + scan: + uses: ./.github/workflows/scan.yml + pull-request: needs: test name: Pull request success diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 605c7706a..cec6c6661 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,11 +33,8 @@ jobs: - uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' - cache: 'gradle' - - name: Validate Gradle wrapper - uses: gradle/actions/wrapper-validation@v3 - - uses: gradle/actions/setup-gradle@v3 + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 - name: Push to registry ${{ matrix.publish_target }} run: | set -xev @@ -68,11 +65,8 @@ jobs: - uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' - cache: 'gradle' - - name: Validate Gradle wrapper - uses: gradle/actions/wrapper-validation@v3 - - uses: gradle/actions/setup-gradle@v3 + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 - name: Build the dependencies needed for the image run: ./gradlew :fabric-chaincode-docker:copyAllDeps - name: Set up QEMU diff --git a/.github/workflows/scan.yml b/.github/workflows/scan.yml new file mode 100644 index 000000000..3bf42b58f --- /dev/null +++ b/.github/workflows/scan.yml @@ -0,0 +1,33 @@ +name: "Scheduled vulnerability scan" + +on: + workflow_call: + inputs: + ref: + description: Branch, tag or SHA to scan. + type: string + required: false + default: "" + +permissions: + contents: read + +jobs: + osv-scanner: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: stable + cache: false + - name: Scan + run: make scan diff --git a/.github/workflows/scheduled-scan.yml b/.github/workflows/scheduled-scan.yml index c303b270e..cfbe56870 100644 --- a/.github/workflows/scheduled-scan.yml +++ b/.github/workflows/scheduled-scan.yml @@ -9,13 +9,18 @@ permissions: contents: read jobs: - osv-scanner: + latest-release-version: + name: Get latest release tag runs-on: ubuntu-latest + outputs: + tag_name: ${{ steps.tag-name.outputs.value }} steps: - - uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: stable - - name: Scan - run: make scan + - id: tag-name + run: echo "value=$(curl --location --silent --fail "https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/latest" | jq --raw-output '.tag_name')" >> "${GITHUB_OUTPUT}" + + scan: + name: Scan ${{ needs.latest-release-version.outputs.tag_name }} + needs: latest-release-version + uses: ./.github/workflows/scan.yml + with: + ref: ${{ needs.latest-release-version.outputs.tag_name }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3e0579863..942cc24f0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,7 +7,7 @@ name: Test on: workflow_call: inputs: - checkout-ref: + ref: default: '' required: false type: string @@ -18,14 +18,12 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: ${{ inputs.checkout-ref }} + ref: ${{ inputs.ref }} - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 - - name: Validate Gradle wrapper - uses: gradle/actions/wrapper-validation@v3 - - uses: gradle/actions/setup-gradle@v3 + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 - name: Build and Unit test run: ./gradlew :fabric-chaincode-shim:build @@ -34,11 +32,12 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: ${{ inputs.checkout-ref }} + ref: ${{ inputs.ref }} - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 - name: Populate chaincode with latest java-version run: | ./gradlew -I $GITHUB_WORKSPACE/fabric-chaincode-integration-test/chaincodebootstrap.gradle -PchaincodeRepoDir=$GITHUB_WORKSPACE/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/repository publishShimPublicationToFabricRepository @@ -58,7 +57,6 @@ jobs: run: | peer version weft --version - - uses: gradle/actions/setup-gradle@v3 - name: Integration Tests run: ./gradlew :fabric-chaincode-integration-test:build @@ -67,11 +65,11 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: ${{ inputs.checkout-ref }} + ref: ${{ inputs.ref }} - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 - - uses: gradle/actions/setup-gradle@v3 + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 - name: Build Docker image run: ./gradlew :fabric-chaincode-docker:buildImage diff --git a/.gitignore b/.gitignore index 1e8499436..6512bbc64 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,8 @@ **/bin/ /build/ build/* +settings-gradle.lockfile +config/ _cfg repository diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8f6248367..d872b5bc1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ We use our own forks and [Github Flow](https://guides.github.com/introduction/fl ## Coding Style -Please to try to be consistent with the rest of the code and conform to checkstyle rules where they are provided. +Please to try to be consistent with the rest of the code and conform to checkstyle rules where they are provided. [Spotless](https://github.com/diffplug/spotless) is used to enforce code formatting. You can run `./gradlew spotlessApply` to apply the mandated code formatting to the codebase before submitting changes to avoid failing the build with formatting violations. ## Code of Conduct Guidelines diff --git a/MAINTAINERS.md b/MAINTAINERS.md index afe228274..4cf93e413 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -1,25 +1,23 @@ -Maintainers -=========== +# Maintainers +| Name | GitHub | Chat | email | +| ------------ | ----------------------------------------------------- | --------------- | -------------------------- | +| Dave Enyeart | [denyeart](https://github.com/denyeart) | denyeart | | +| Mark Lewis | [bestbeforetoday](https://github.com/bestbeforetoday) | bestbeforetoday | | -| Name | GitHub | Chat | email | -|---------------------------|------------------|-----------------|---------------------------| -| Artem Barger | c0rwin | c0rwin | bartem@il.ibm.com | -| Matthew B White | mbwhite | mbwhite | whitemat@uk.ibm.com | -| Mark Lewis | bestbeforetoday | bestbeforetoday | Mark.S.Lewis@outlook.com | +# Retired Maintainers -Retired Maintainers -=================== - -| Name | GitHub | Chat | email | -|---------------------------|------------------|---------------|---------------------------| -| James Taylor | jt-nti | jtonline | jamest@uk.ibm.com | -| Gari Singh | mastersingh24 | mastersingh24 | gari.r.singh@gmail.com | -| Gennady Laventman | gennadylaventman | gennadyl | gennady@il.ibm.com | -| Jim Zhang | jimthematrix | jimthematrix | jim\_the\_matrix@hotmail.com | -| Luis Sanchez | sanchezl | sanchezl | sanchezl@us.ibm.com | -| Srinivasan Muralidharan | muralisrini | muralisr | srinivasan.muralidharan99@gmail.com | -| Yacov Manevich | yacovm | yacovm | yacovm@il.ibm.com | +| Name | GitHub | Chat | email | +| ----------------------- | ------------------------------------------------------- | ------------- | ------------------------------------- | +| Artem Barger | [c0rwin](https://github.com/c0rwin) | c0rwin | | +| Matthew B White | [mbwhite](https://github.com/mbwhite) | mbwhite | | +| James Taylor | [jt-nti](https://github.com/jt-nti) | jtonline | | +| Gari Singh | [mastersingh24](https://github.com/mastersingh24) | mastersingh24 | | +| Gennady Laventman | [gennadylaventman](https://github.com/gennadylaventman) | gennadyl | | +| Jim Zhang | [jimthematrix](https://github.com/jimthematrix) | jimthematrix | | +| Luis Sanchez | [sanchezl](https://github.com/sanchezl) | sanchezl | | +| Srinivasan Muralidharan | [muralisrini](https://github.com/muralisrini) | muralisr | | +| Yacov Manevich | [yacovm](https://github.com/yacovm) | yacovm | | Also: Please see the [Release Manager section](https://github.com/hyperledger/fabric/blob/main/MAINTAINERS.md) diff --git a/build.gradle b/build.gradle index 762de3e15..654a4d7f5 100644 --- a/build.gradle +++ b/build.gradle @@ -6,12 +6,13 @@ plugins { id "com.github.ben-manes.versions" version "0.51.0" + id "com.diffplug.spotless" version "6.25.0" } -version = '2.5.4' +version = '2.5.5' -// If the nightly property is set, then this is the scheduled main +// If the nightly property is set, then this is the scheduled main // build - and we should publish this to artifactory // // Use the .dev. format to match Maven convention @@ -23,47 +24,67 @@ if (properties.containsKey('NIGHTLY')) { } allprojects { + apply plugin: "com.diffplug.spotless" + repositories { mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url "https://www.jitpack.io" } } + + spotless { + format 'misc', { + target '*.gradle', '.gitattributes', '.gitignore' + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + } + } } subprojects { apply plugin: 'java' - apply plugin: 'maven-publish' + apply plugin: "maven-publish" group = 'org.hyperledger.fabric-chaincode-java' version = rootProject.version java { - sourceCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } compileJava { if (javaCompiler.get().metadata.languageVersion.canCompileOrRun(10)) { - options.release = 8 + options.release = 11 } } dependencies { implementation 'commons-cli:commons-cli:1.9.0' implementation 'commons-logging:commons-logging:1.3.4' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.11.0' - - testImplementation 'org.hamcrest:hamcrest-library:3.0' - testImplementation 'org.mockito:mockito-core:5.13.0' - testImplementation 'uk.org.webcompere:system-stubs-jupiter:2.1.6' + testImplementation platform('org.junit:junit-bom:5.11.3') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testImplementation 'org.assertj:assertj-core:3.26.3' + testImplementation 'org.mockito:mockito-core:5.14.2' + testImplementation 'uk.org.webcompere:system-stubs-jupiter:2.1.7' + + testImplementation 'org.hamcrest:hamcrest-library:3.0' } test { useJUnitPlatform() } + spotless { + java { + removeUnusedImports() + palantirJavaFormat('2.50.0').formatJavadoc(true) + formatAnnotations() + } + } } task printVersionName() { diff --git a/ci/checkstyle/checkstyle.xml b/ci/checkstyle/checkstyle.xml deleted file mode 100644 index 14ee8c152..000000000 --- a/ci/checkstyle/checkstyle.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ci/checkstyle/java-copyright-header.txt b/ci/checkstyle/java-copyright-header.txt deleted file mode 100644 index 5bc18a3d1..000000000 --- a/ci/checkstyle/java-copyright-header.txt +++ /dev/null @@ -1,5 +0,0 @@ -^/\*$ -^ \* Copyright \d\d\d\d .*? All Rights Reserved\.$ -^ \*$ -^ \* SPDX-License-Identifier: Apache-2\.0$ -^ \*/$ \ No newline at end of file diff --git a/examples/fabric-contract-example-maven/pom.xml b/examples/fabric-contract-example-maven/pom.xml index ae33ca510..b022d5aa4 100644 --- a/examples/fabric-contract-example-maven/pom.xml +++ b/examples/fabric-contract-example-maven/pom.xml @@ -12,7 +12,7 @@ UTF-8 - 2.5.3 + 2.5.4 1.3.14 diff --git a/fabric-chaincode-docker/Dockerfile b/fabric-chaincode-docker/Dockerfile index 144af8951..d8ae42298 100644 --- a/fabric-chaincode-docker/Dockerfile +++ b/fabric-chaincode-docker/Dockerfile @@ -1,5 +1,7 @@ -FROM eclipse-temurin:11-jdk as builder -ENV DEBIAN_FRONTEND=noninteractive +ARG JAVA_IMAGE=eclipse-temurin:21-jdk + +FROM ${JAVA_IMAGE} AS builder +ENV DEBIAN_FRONTEND=noninteractive # Build tools RUN apt-get update \ @@ -10,10 +12,11 @@ RUN curl -s "https://get.sdkman.io" | bash SHELL ["/bin/bash", "-c"] -RUN source /root/.sdkman/bin/sdkman-init.sh; sdk install gradle 8.6 -RUN source /root/.sdkman/bin/sdkman-init.sh; sdk install maven 3.9.6 +RUN source /root/.sdkman/bin/sdkman-init.sh \ + && sdk install gradle 8.11.1 \ + && sdk install maven 3.9.9 -FROM eclipse-temurin:11-jdk as dependencies +FROM ${JAVA_IMAGE} AS dependencies COPY --from=builder /root/.sdkman/candidates/gradle/current /usr/bin/gradle COPY --from=builder /root/.sdkman/candidates/maven/current /usr/bin/maven @@ -25,12 +28,10 @@ ENV PATH="/usr/bin/maven/bin:/usr/bin/maven/:/usr/bin/gradle:/usr/bin/gradle/bin ADD build/distributions/ /root/ #Creating folders structure -RUN mkdir -p /root/chaincode-java/chaincode/src -RUN mkdir -p /root/chaincode-java/chaincode/build/out +RUN mkdir -p /root/chaincode-java/chaincode/src /root/chaincode-java/chaincode/build/out #Making scripts runnable -RUN chmod +x /root/chaincode-java/start -RUN chmod +x /root/chaincode-java/build.sh +RUN chmod +x /root/chaincode-java/start /root/chaincode-java/build.sh # Build protos and shim jar and installing them to maven local and gradle cache WORKDIR /root/chaincode-java/shim-src @@ -40,20 +41,22 @@ RUN gradle \ fabric-chaincode-shim:publishToMavenLocal \ -x javadoc \ -x test \ - -x checkstyleMain \ - -x checkstyleTest + -x pmdMain \ + -x pmdTest \ + -x spotlessCheck WORKDIR /root/chaincode-java # Run the Gradle and Maven commands to generate the wrapper variants # of each tool #Gradle doesn't run without settings.gradle file, so create one -RUN touch settings.gradle -RUN gradle wrapper -RUN mvn -N io.takari:maven:wrapper +RUN touch settings.gradle \ + && gradle wrapper \ + && ./gradlew --version \ + && mvn -N wrapper:wrapper # Creating final javaenv image which will include all required # dependencies to build and compile java chaincode -FROM eclipse-temurin:11-jdk +FROM ${JAVA_IMAGE} RUN apt-get update \ && apt-get -y install zip unzip \ @@ -66,6 +69,7 @@ SHELL ["/bin/bash", "-c"] # Copy setup scripts, and the cached dependencies COPY --from=dependencies /root/chaincode-java /root/chaincode-java +COPY --from=dependencies /root/.gradle /root/.gradle COPY --from=dependencies /root/.m2 /root/.m2 WORKDIR /root/chaincode-java diff --git a/fabric-chaincode-docker/build.gradle b/fabric-chaincode-docker/build.gradle index acba46784..e5ba5d6c4 100644 --- a/fabric-chaincode-docker/build.gradle +++ b/fabric-chaincode-docker/build.gradle @@ -65,6 +65,5 @@ task copyAllDeps(type: Copy) { task buildImage(type: DockerBuildImage) { dependsOn copyAllDeps inputDir = project.file('Dockerfile').parentFile - images = ['hyperledger/fabric-javaenv', 'hyperledger/fabric-javaenv:2.5', 'hyperledger/fabric-javaenv:amd64-2.5.4', 'hyperledger/fabric-javaenv:amd64-latest'] + images = ['hyperledger/fabric-javaenv', 'hyperledger/fabric-javaenv:2.5', 'hyperledger/fabric-javaenv:amd64-2.5.5', 'hyperledger/fabric-javaenv:amd64-latest'] } - diff --git a/fabric-chaincode-integration-test/.gitignore b/fabric-chaincode-integration-test/.gitignore index 04cc8e939..32a86ea45 100644 --- a/fabric-chaincode-integration-test/.gitignore +++ b/fabric-chaincode-integration-test/.gitignore @@ -1,3 +1,4 @@ repository _cfg *.tar.gz +log.txt diff --git a/fabric-chaincode-integration-test/build.gradle b/fabric-chaincode-integration-test/build.gradle index 08d1524e8..9d2b1fc73 100644 --- a/fabric-chaincode-integration-test/build.gradle +++ b/fabric-chaincode-integration-test/build.gradle @@ -8,7 +8,7 @@ dependencies { test { // Always run tests, even when nothing changed. dependsOn 'cleanTest' - + // Show test results. testLogging { events "passed", "skipped", "failed" @@ -16,7 +16,7 @@ dependencies { showCauses true showStandardStreams true exceptionFormat "full" - + } } diff --git a/fabric-chaincode-integration-test/chaincodebootstrap.gradle b/fabric-chaincode-integration-test/chaincodebootstrap.gradle index 67b9b238c..fce50a3e4 100644 --- a/fabric-chaincode-integration-test/chaincodebootstrap.gradle +++ b/fabric-chaincode-integration-test/chaincodebootstrap.gradle @@ -9,4 +9,4 @@ allprojects { } } } -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/contracts/bare-gradle/build.gradle b/fabric-chaincode-integration-test/src/contracts/bare-gradle/build.gradle index a3a4016af..b5ea23f8a 100644 --- a/fabric-chaincode-integration-test/src/contracts/bare-gradle/build.gradle +++ b/fabric-chaincode-integration-test/src/contracts/bare-gradle/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'com.github.johnrengelman.shadow' version '5.2.0' + id 'com.gradleup.shadow' version '8.3.5' id 'java' } @@ -7,7 +7,12 @@ group 'org.hyperledger.fabric-chaincode-java' version '1.0-SNAPSHOT' java { - sourceCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +compileJava { + options.compilerArgs.addAll(['--release', '11']) } repositories { @@ -19,14 +24,14 @@ repositories { } dependencies { - implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.4' + implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.5' implementation 'org.hyperledger.fabric:fabric-protos:0.3.3' } shadowJar { - baseName = 'chaincode' - version = null - classifier = null + archiveBaseName = 'chaincode' + archiveVersion = '' + archiveClassifier = '' mergeServiceFiles() manifest { diff --git a/fabric-chaincode-integration-test/src/contracts/bare-maven/pom.xml b/fabric-chaincode-integration-test/src/contracts/bare-maven/pom.xml index 72a0feecd..9740748dd 100644 --- a/fabric-chaincode-integration-test/src/contracts/bare-maven/pom.xml +++ b/fabric-chaincode-integration-test/src/contracts/bare-maven/pom.xml @@ -7,12 +7,12 @@ - 8 + 11 UTF-8 UTF-8 - 2.5.4 + 2.5.5 diff --git a/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/build.gradle b/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/build.gradle index 84b7f8570..a8d488c30 100644 --- a/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/build.gradle +++ b/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/build.gradle @@ -1,19 +1,18 @@ plugins { - id 'com.github.johnrengelman.shadow' version '8.1.1' + id 'com.gradleup.shadow' version '8.3.5' id 'java' } group 'org.hyperledger.fabric-chaincode-java' -version '1.0-SNAPSHOT' +version '' java { - sourceCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } compileJava { - if (javaCompiler.get().metadata.languageVersion.canCompileOrRun(10)) { - options.release = 8 - } + options.compilerArgs.addAll(['--release', '11']) } repositories { @@ -25,7 +24,7 @@ repositories { } dependencies { - implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.4' + implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.5' implementation 'org.hyperledger.fabric:fabric-protos:0.3.3' } diff --git a/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/gradle/wrapper/gradle-wrapper.properties b/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/gradle/wrapper/gradle-wrapper.properties index a80b22ce5..e2847c820 100644 --- a/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/gradle/wrapper/gradle-wrapper.properties +++ b/fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/build.gradle b/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/build.gradle index b78f40187..b128a4c85 100644 --- a/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/build.gradle +++ b/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'com.github.johnrengelman.shadow' version '8.1.1' + id 'com.gradleup.shadow' version '8.3.5' id 'java' } @@ -7,13 +7,12 @@ group 'org.hyperledger.fabric-chaincode-java' version '1.0-SNAPSHOT' java { - sourceCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } compileJava { - if (javaCompiler.get().metadata.languageVersion.canCompileOrRun(10)) { - options.release = 8 - } + options.compilerArgs.addAll(['--release', '11']) } repositories { @@ -25,7 +24,7 @@ repositories { } dependencies { - implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.4' + implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:2.5.5' implementation 'org.hyperledger.fabric:fabric-protos:0.3.3' implementation 'commons-logging:commons-logging:1.2' implementation 'com.google.code.gson:gson:2.10.1' diff --git a/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/gradle/wrapper/gradle-wrapper.properties b/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/gradle/wrapper/gradle-wrapper.properties index a80b22ce5..e2847c820 100644 --- a/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/gradle/wrapper/gradle-wrapper.properties +++ b/fabric-chaincode-integration-test/src/contracts/fabric-shim-api/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.jar b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.jar index bf82ff01c..7967f30dd 100644 Binary files a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.jar and b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.jar differ diff --git a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.properties b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.properties index dc3affce3..9548abd8e 100644 --- a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.properties +++ b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/.mvn/wrapper/maven-wrapper.properties @@ -6,7 +6,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an @@ -14,5 +14,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar +wrapperVersion=3.3.2 +distributionType=bin +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar diff --git a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw index 41c0f0c23..5e9618cac 100755 --- a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw +++ b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven Start Up Batch script +# Apache Maven Wrapper startup batch script, version 3.3.2 # # Required ENV vars: # ------------------ @@ -27,284 +27,306 @@ # # Optional ENV vars # ----------------- -# M2_HOME - location of maven2's installed home dir # MAVEN_OPTS - parameters passed to the Java VM when running Maven # e.g. to debug Maven itself, use # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 # MAVEN_SKIP_RC - flag to disable loading of mavenrc files # ---------------------------------------------------------------------------- -if [ -z "$MAVEN_SKIP_RC" ] ; then +if [ -z "$MAVEN_SKIP_RC" ]; then - if [ -f /etc/mavenrc ] ; then + if [ -f /usr/local/etc/mavenrc ]; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ]; then . /etc/mavenrc fi - if [ -f "$HOME/.mavenrc" ] ; then + if [ -f "$HOME/.mavenrc" ]; then . "$HOME/.mavenrc" fi fi # OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; +cygwin=false +darwin=false mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)" + export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home" + export JAVA_HOME fi - ;; + fi + ;; esac -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) fi fi -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - 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 - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - # For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +if $cygwin; then + [ -n "$JAVA_HOME" ] \ + && JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] \ + && CLASSPATH=$(cygpath --path --unix "$CLASSPATH") fi # For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +if $mingw; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] \ + && JAVA_HOME="$( + cd "$JAVA_HOME" || ( + echo "cannot cd into $JAVA_HOME." >&2 + exit 1 + ) + pwd + )" fi if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "$javaExecutable" : '\([^ ]*\)')" = "no" ]; then # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin; then + javaHome="$(dirname "$javaExecutable")" + javaExecutable="$(cd "$javaHome" && pwd -P)/javac" else - javaExecutable="`readlink -f \"$javaExecutable\"`" + javaExecutable="$(readlink -f "$javaExecutable")" fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` + javaHome="$(dirname "$javaExecutable")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') JAVA_HOME="$javaHome" export JAVA_HOME fi fi fi -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="$( + \unset -f command 2>/dev/null + \command -v java + )" fi fi -if [ ! -x "$JAVACMD" ] ; then +if [ ! -x "$JAVACMD" ]; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1 fi -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." >&2 fi -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" >&2 return 1 fi basedir="$1" wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then basedir=$wdir break fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` + wdir=$( + cd "$wdir/.." || exit 1 + pwd + ) fi # end of workaround done - echo "${basedir}" + printf '%s' "$( + cd "$basedir" || exit 1 + pwd + )" } # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' <"$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" fi } -BASE_DIR=`find_maven_basedir "$(pwd)"` +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") if [ -z "$BASE_DIR" ]; then - exit 1; + exit 1 fi +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + ########################################################################################## # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in wrapperUrl) + wrapperUrl="$safeValue" + break + ;; + esac + done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" + elif command -v curl >/dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi fi + fi fi ########################################################################################## # End of extension ########################################################################################## -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in wrapperSha256Sum) + wrapperSha256Sum=$value + break + ;; + esac +done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum >/dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c >/dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c >/dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi fi + MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` + [ -n "$JAVA_HOME" ] \ + && JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] \ + && CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] \ + && MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") fi # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +# shellcheck disable=SC2086 # safe args exec "$JAVACMD" \ $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw.cmd b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw.cmd index 86115719e..1204076a9 100644 --- a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw.cmd +++ b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/mvnw.cmd @@ -1,182 +1,206 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. >&2 +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. >&2 +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/pom.xml b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/pom.xml index 7484f7c1a..f9e592382 100644 --- a/fabric-chaincode-integration-test/src/contracts/wrapper-maven/pom.xml +++ b/fabric-chaincode-integration-test/src/contracts/wrapper-maven/pom.xml @@ -7,12 +7,12 @@ - 8 + 11 UTF-8 UTF-8 - 2.5.4 + 2.5.5 diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/contractinstall/ContractInstallTest.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/contractinstall/ContractInstallTest.java index 881ac8cda..f63dc8b69 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/contractinstall/ContractInstallTest.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/contractinstall/ContractInstallTest.java @@ -5,40 +5,35 @@ */ package org.hyperleder.fabric.shim.integration.contractinstall; -import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; import org.hyperleder.fabric.shim.integration.util.FabricState; import org.hyperleder.fabric.shim.integration.util.InvokeHelper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -/** - * Basic Java Chaincode Test - * - */ +/** Basic Java Chaincode Test */ public class ContractInstallTest { - @BeforeAll + @BeforeAll public static void setUp() throws Exception { FabricState.getState().start(); - } - @Test - public void TestInstall(){ + @Test + public void testInstall() { - InvokeHelper helper = InvokeHelper.newHelper("baregradlecc","sachannel"); + InvokeHelper helper = InvokeHelper.newHelper("baregradlecc", "sachannel"); String text = helper.invoke("org1", "whoami"); assertThat(text, containsString("BareGradle")); - - helper = InvokeHelper.newHelper("baremaven","sachannel"); + + helper = InvokeHelper.newHelper("baremaven", "sachannel"); text = helper.invoke("org1", "whoami"); assertThat(text, containsString("BareMaven")); - - helper = InvokeHelper.newHelper("wrappermaven","sachannel"); + + helper = InvokeHelper.newHelper("wrappermaven", "sachannel"); text = helper.invoke("org1", "whoami"); - assertThat(text, containsString("WrapperMaven")); + assertThat(text, containsString("WrapperMaven")); } - -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/ledgertests/LedgerIntegrationTest.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/ledgertests/LedgerIntegrationTest.java index 20a1825e1..815ab88ca 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/ledgertests/LedgerIntegrationTest.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/ledgertests/LedgerIntegrationTest.java @@ -4,34 +4,29 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.ledgertests; -import static org.hamcrest.core.StringContains.containsString; + import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; import org.hyperleder.fabric.shim.integration.util.FabricState; import org.hyperleder.fabric.shim.integration.util.InvokeHelper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -/** - * Basic Java Chaincode Test - * - */ +/** Basic Java Chaincode Test */ public class LedgerIntegrationTest { - @BeforeAll + @BeforeAll public static void setUp() throws Exception { - FabricState.getState().start(); } - @Test - public void TestLedgers(){ - InvokeHelper helper = InvokeHelper.newHelper("ledgercc","sachannel"); - + @Test + public void testLedgers() { + InvokeHelper helper = InvokeHelper.newHelper("ledgercc", "sachannel"); + String text = helper.invoke("org1", "accessLedgers"); assertThat(text, containsString("success")); - } - } diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SACCIntegrationTest.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SACCIntegrationTest.java index 50b27c45d..93923ac65 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SACCIntegrationTest.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SACCIntegrationTest.java @@ -4,37 +4,34 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.shimtests; -import static org.hamcrest.core.StringContains.containsString; + import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; import org.hyperleder.fabric.shim.integration.util.FabricState; import org.hyperleder.fabric.shim.integration.util.InvokeHelper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -/** - * Basic Java Chaincode Test - * - */ +/** Basic Java Chaincode Test */ public class SACCIntegrationTest { @BeforeAll public static void setUp() throws Exception { - FabricState.getState().start(); - + FabricState.getState().start(); } - @Test - public void TestLedger(){ + @Test + public void testLedger() { InvokeHelper helper = InvokeHelper.newHelper("shimcc", "sachannel"); String text = helper.invoke("org1", "putBulkStates"); assertThat(text, containsString("success")); - - text = helper.invoke("org1", "getByRange","key120","key170"); + + text = helper.invoke("org1", "getByRange", "key120", "key170"); assertThat(text, containsString("50")); - text = helper.invoke("org1", "getByRangePaged","key120","key170","10",""); + text = helper.invoke("org1", "getByRangePaged", "key120", "key170", "10", ""); System.out.println(text); assertThat(text, containsString("key130")); @@ -42,5 +39,4 @@ public void TestLedger(){ System.out.println(text); assertThat(text, containsString("org.hyperledger.fabric.metrics.impl.DefaultProvider")); } - } diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SBECCIntegrationTest.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SBECCIntegrationTest.java index 418cdbf7a..02ffb16c1 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SBECCIntegrationTest.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/shimtests/SBECCIntegrationTest.java @@ -5,9 +5,9 @@ */ package org.hyperleder.fabric.shim.integration.shimtests; -import static org.hamcrest.core.StringContains.containsString; -import static org.hamcrest.Matchers.not; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.StringContains.containsString; import org.hyperleder.fabric.shim.integration.util.FabricState; import org.hyperleder.fabric.shim.integration.util.InvokeHelper; @@ -19,12 +19,10 @@ public class SBECCIntegrationTest { @BeforeAll public static void setUp() throws Exception { FabricState.getState().start(); - - } @Test - public void RunSBE_pub_setget() { + public void runSBE_pub_setget() { final String mode = "pub"; final InvokeHelper helper = InvokeHelper.newHelper("shimcc", "sachannel"); @@ -61,7 +59,6 @@ public void RunSBE_pub_setget() { assertThat(text, containsString("org2MSP")); assertThat(text, containsString("org1MSP")); - text = helper.invoke("org1", "EndorsementCC:setval", mode, "val3"); assertThat(text, containsString("success")); @@ -85,11 +82,10 @@ public void RunSBE_pub_setget() { assertThat(text, containsString("success")); text = helper.invoke("org1", "EndorsementCC:recordExists", mode); assertThat(text, containsString("false")); - } - @Test - public void RunSBE_priv() { + @Test + public void runSBE_priv() { final String mode = "priv"; final InvokeHelper helper = InvokeHelper.newHelper("shimcc", "sachannel"); @@ -126,7 +122,6 @@ public void RunSBE_priv() { text = helper.invoke("org1", "EndorsementCC:listorgs", mode); assertThat(text, containsString("org2MSP")); assertThat(text, containsString("org1MSP")); - text = helper.invoke("org1", "EndorsementCC:setval", mode, "val3"); assertThat(text, containsString("success")); @@ -151,7 +146,5 @@ public void RunSBE_priv() { assertThat(text, containsString("success")); text = helper.invoke("org1", "EndorsementCC:recordExists", mode); assertThat(text, containsString("false")); - } - } diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Bash.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Bash.java index b135a48b5..2440e2242 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Bash.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Bash.java @@ -4,23 +4,20 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.util; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; -/** Represents the 'peer' cli command - * - * - * - */ +/** Represents the 'peer' cli command */ public final class Bash extends Command { - public static BashBuilder newBuilder(){ + public static BashBuilder newBuilder() { return new BashBuilder(); } - static public class BashBuilder extends Command.Builder { + public static class BashBuilder extends Command.Builder { String cmd; String orderer; String channel; @@ -28,7 +25,7 @@ static public class BashBuilder extends Command.Builder { boolean evaluate = false; int waitForEventTimeout; List args = new ArrayList(); - Map transientData; + Map transientData; public BashBuilder duplicate() { try { @@ -40,26 +37,25 @@ public BashBuilder duplicate() { } } - public BashBuilder cmd(String cmd){ + public BashBuilder cmd(String cmd) { this.cmd = cmd; return this; } - public BashBuilder cmdargs(String argsArray[]){ + public BashBuilder cmdargs(String argsArray[]) { this.args = Arrays.asList(argsArray); return this; } - public Bash build(Map additionalEnv){ + public Bash build(Map additionalEnv) { ArrayList list = new ArrayList<>(); list.add(cmd); - return new Bash(list,additionalEnv); + return new Bash(list, additionalEnv); } - - public Bash build(){ + public Bash build() { ArrayList list = new ArrayList<>(); list.add(cmd); @@ -71,9 +67,9 @@ public Bash build(){ Bash(List cmd) { super(cmd); - } + } - Bash(List cmd, Map env) { - super(cmd, env); + Bash(List cmd, Map env) { + super(cmd, env); } -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Command.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Command.java index a18a282ec..a4a759e89 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Command.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Command.java @@ -25,7 +25,7 @@ public class Command { protected final List cmd; protected final Map env = new HashMap<>(); - Command(List cmd, Map additionalEnv){ + Command(List cmd, Map additionalEnv) { this.cmd = cmd; this.env.putAll(additionalEnv); } @@ -40,16 +40,14 @@ public static final class Result { public int exitcode; } - /** - * Run but don't suppress the output being printed directly - */ + /** Run but don't suppress the output being printed directly */ public Result run() { return this.run(false); } /** * Run the command, and process the output to arrays for later parsing and checking - * + * * @param quiet true if the output should NOT be printed directly to System.out/System.err */ public Result run(boolean quiet) { @@ -60,22 +58,24 @@ public Result run(boolean quiet) { System.out.println("Running:" + this); try { - + processBuilder.redirectInput(Redirect.INHERIT); processBuilder.redirectErrorStream(true); - + Process process = processBuilder.start(); System.out.println("Started..... "); - CompletableFuture> soutFut = readOutStream(process.getInputStream(),quiet?null:System.out); - CompletableFuture> serrFut = readOutStream(process.getErrorStream(),quiet?null:System.err); + CompletableFuture> soutFut = + readOutStream(process.getInputStream(), quiet ? null : System.out); + CompletableFuture> serrFut = + readOutStream(process.getErrorStream(), quiet ? null : System.err); CompletableFuture resultFut = soutFut.thenCombine(serrFut, (stdout, stderr) -> { - // print to current stderr the stderr of process and return the stdout + // print to current stderr the stderr of process and return the stdout result.stderr = stderr; result.stdout = stdout; return result; - }); + }); result.exitcode = process.waitFor(); // get stdout once ready, blocking @@ -91,18 +91,19 @@ public Result run(boolean quiet) { /** * Collect the information from the executed process and add them to a result object - * + * * @param is * @param stream * @return Completable Future with the array list of the stdout/stderr */ CompletableFuture> readOutStream(InputStream is, PrintStream stream) { return CompletableFuture.supplyAsync(() -> { - try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) { + try (InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); ) { ArrayList res = new ArrayList<>(); String inputLine; while ((inputLine = br.readLine()) != null) { - if (stream!=null) stream.println(inputLine); + if (stream != null) stream.println(inputLine); res.add(inputLine); } return res; @@ -116,7 +117,7 @@ public String toString() { return "[" + String.join(" ", cmd) + "]"; } - static public class Builder implements Cloneable { + public static class Builder implements Cloneable { @SuppressWarnings("unchecked") public Builder duplicate() { try { diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Docker.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Docker.java index f500d3330..e24bed826 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Docker.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Docker.java @@ -4,17 +4,14 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.util; + import java.util.ArrayList; import java.util.List; -/** Represents the 'docker' cli command - * - * - * - */ +/** Represents the 'docker' cli command */ public final class Docker extends Command { - public static DockerBuilder newBuilder(){ + public static DockerBuilder newBuilder() { return new DockerBuilder(); } @@ -32,58 +29,55 @@ public DockerBuilder duplicate() { return null; } } - - public DockerBuilder script(String script){ + + public DockerBuilder script(String script) { this.script = script; return this; } - - public DockerBuilder channel(String channel){ + + public DockerBuilder channel(String channel) { this.channel = channel; return this; } - public DockerBuilder container(String container){ + public DockerBuilder container(String container) { this.container = container; return this; } - public DockerBuilder exec(){ + public DockerBuilder exec() { this.exec = true; return this; } - public Docker build(){ + public Docker build() { ArrayList list = new ArrayList<>(); list.add("docker"); - if(exec){ + if (exec) { list.add("exec"); - } - - if (container == null || container.isEmpty()){ + + if (container == null || container.isEmpty()) { throw new RuntimeException("container should be set"); } list.add(container); - - if (script == null || script.isEmpty()){ + + if (script == null || script.isEmpty()) { throw new RuntimeException("script should be set"); } list.add(script); - - if (channel == null || channel.isEmpty()){ + + if (channel == null || channel.isEmpty()) { throw new RuntimeException("channel should be set"); } list.add(channel); - return new Docker(list); } } - + Docker(List cmd) { - super(cmd); + super(cmd); } - -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/DockerCompose.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/DockerCompose.java index 3beaac556..50a2e8eb0 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/DockerCompose.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/DockerCompose.java @@ -4,71 +4,66 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.util; + import java.util.ArrayList; import java.util.List; -/** Represents the 'peer' cli command - * - * - * - */ +/** Represents the 'peer' cli command */ public final class DockerCompose extends Command { - public static DockerComposeBuilder newBuilder(){ + public static DockerComposeBuilder newBuilder() { return new DockerComposeBuilder(); } - - public static final class DockerComposeBuilder extends Command.Builder{ + + public static final class DockerComposeBuilder extends Command.Builder { String composeFile; boolean up = true; boolean detach = false; - public DockerComposeBuilder file(String composeFile){ + public DockerComposeBuilder file(String composeFile) { this.composeFile = composeFile; return this; } - + public DockerComposeBuilder duplicate() { return (DockerComposeBuilder) super.duplicate(); } - public DockerComposeBuilder up(){ + public DockerComposeBuilder up() { this.up = true; return this; } - - public DockerComposeBuilder detach(){ + + public DockerComposeBuilder detach() { this.detach = true; return this; } - - public DockerComposeBuilder down(){ + + public DockerComposeBuilder down() { this.up = false; return this; } - - public DockerCompose build(){ + + public DockerCompose build() { ArrayList list = new ArrayList<>(); list.add("docker-compose"); - if (composeFile!=null && !composeFile.isEmpty()) { + if (composeFile != null && !composeFile.isEmpty()) { list.add("-f"); list.add(composeFile); } - list.add(up?"up":"down"); - if (detach){ + list.add(up ? "up" : "down"); + if (detach) { list.add("-d"); } - return new DockerCompose(list); } } - + DockerCompose(List cmd) { - super(cmd); - super.env.put("COMPOSE_PROJECT_NAME","first-network"); + super(cmd); + super.env.put("COMPOSE_PROJECT_NAME", "first-network"); } - -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/FabricState.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/FabricState.java index 59909a2a1..f24f8b820 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/FabricState.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/FabricState.java @@ -9,29 +9,18 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.Semaphore; - import org.hyperleder.fabric.shim.integration.util.Bash.BashBuilder; public final class FabricState { - private static FabricState state; - - private static final Map channelStarted = new HashMap<>(); + private static final FabricState state = new FabricState(); - // sempaphore to protect access - private static final Semaphore flag = new Semaphore(1); + private boolean started = false; public static FabricState getState() { - if (state == null) { - state = new FabricState(); - } - return state; } - private boolean started = false; - public synchronized void start() { if (!this.started) { @@ -49,15 +38,14 @@ public Map orgEnv(String org) { Map env = new HashMap<>(); - env.put("CORE_PEER_MSPCONFIGPATH", - Paths.get(s, "src/test/resources/_cfg/_msp/" + org, org + "admin/msp").toString()); + env.put( + "CORE_PEER_MSPCONFIGPATH", + Paths.get(s, "src/test/resources/_cfg/_msp/" + org, org + "admin/msp") + .toString()); env.put("CORE_PEER_LOCALMSPID", org + "MSP"); env.put("CORE_PEER_ADDRESS", org + "peer-api.127-0-0-1.nip.io:8080"); - System.out.println(env); return env; - } - -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/InvokeHelper.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/InvokeHelper.java index 971cb2529..6d4915f80 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/InvokeHelper.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/InvokeHelper.java @@ -1,49 +1,47 @@ package org.hyperleder.fabric.shim.integration.util; -import org.hyperleder.fabric.shim.integration.util.Command.Result; -import org.hyperleder.fabric.shim.integration.util.Peer.PeerBuilder; - import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; +import org.hyperleder.fabric.shim.integration.util.Command.Result; +import org.hyperleder.fabric.shim.integration.util.Peer.PeerBuilder; public class InvokeHelper { - + private String ccname; private String channel; - + public static InvokeHelper newHelper(String ccname, String channel) { - + InvokeHelper ih = new InvokeHelper(); - + ih.ccname = ccname; ih.channel = channel; - + return ih; } - - public String invoke(String org, String... args){ - Map orgEnv = FabricState.getState().orgEnv(org); + + public String invoke(String org, String... args) { + Map orgEnv = FabricState.getState().orgEnv(org); PeerBuilder coreBuilder = Peer.newBuilder().ccname(ccname).channel(channel); Result r = coreBuilder.argsTx(args).build(orgEnv).run(); System.out.println(r.stdout); String text = r.stdout.stream() - .filter(line -> line.matches(".*chaincodeInvokeOrQuery.*")) - .collect(Collectors.joining(System.lineSeparator())) - .trim(); + .filter(line -> line.matches(".*chaincodeInvokeOrQuery.*")) + .collect(Collectors.joining(System.lineSeparator())) + .trim(); - if (!text.contains("result: status:200")){ + if (!text.contains("result: status:200")) { Command logsCommand = new Command(Arrays.asList("docker", "logs", "microfab"), orgEnv); logsCommand.run(); throw new RuntimeException(text); - } + } int payloadIndex = text.indexOf("payload:"); - if (payloadIndex>1){ - return text.substring(payloadIndex+9,text.length()-1); + if (payloadIndex > 1) { + return text.substring(payloadIndex + 9, text.length() - 1); } return "success"; } - } diff --git a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Peer.java b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Peer.java index 99c19111c..dbbc53ad9 100644 --- a/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Peer.java +++ b/fabric-chaincode-integration-test/src/test/java/org/hyperleder/fabric/shim/integration/util/Peer.java @@ -4,22 +4,18 @@ SPDX-License-Identifier: Apache-2.0 */ package org.hyperleder.fabric.shim.integration.util; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; - import org.json.JSONArray; import org.json.JSONObject; -/** Represents the 'peer' cli command - * - * - * - */ +/** Represents the 'peer' cli command */ public final class Peer extends Command { - public static PeerBuilder newBuilder(){ + public static PeerBuilder newBuilder() { return new PeerBuilder(); } @@ -31,7 +27,7 @@ public static final class PeerBuilder extends Command.Builder { boolean evaluate = false; int waitForEventTimeout; List args = new ArrayList(); - Map transientData; + Map transientData; public PeerBuilder duplicate() { try { @@ -43,64 +39,64 @@ public PeerBuilder duplicate() { } } - public PeerBuilder tlsArgs(String tlsArgs){ + public PeerBuilder tlsArgs(String tlsArgs) { this.tlsArgs = tlsArgs; return this; } - public PeerBuilder orderer(String orderer){ + public PeerBuilder orderer(String orderer) { this.orderer = orderer; return this; } - public PeerBuilder channel(String channel){ + public PeerBuilder channel(String channel) { this.channel = channel; return this; } - public PeerBuilder ccname(String ccname){ + public PeerBuilder ccname(String ccname) { this.ccname = ccname; return this; } - public PeerBuilder evaluate(){ + public PeerBuilder evaluate() { this.evaluate = true; return this; } - public PeerBuilder invoke(){ + public PeerBuilder invoke() { this.evaluate = false; return this; } - public PeerBuilder argsTx(List args){ + public PeerBuilder argsTx(List args) { this.args = args; return this; } - public PeerBuilder argsTx(String[] argsArray){ + public PeerBuilder argsTx(String[] argsArray) { this.args = Arrays.asList(argsArray); return this; } - public PeerBuilder transientData(Map transientData){ + public PeerBuilder transientData(Map transientData) { this.transientData = transientData; return this; } - public PeerBuilder waitForEvent(int seconds){ + public PeerBuilder waitForEvent(int seconds) { this.waitForEventTimeout = seconds; return this; } - public PeerBuilder waitForEvent(){ + public PeerBuilder waitForEvent() { this.waitForEvent(0); return this; } private String transientToString() { JSONObject json = new JSONObject(this.transientData); - return "'"+json.toString()+"'"; + return "'" + json.toString() + "'"; } private String argsToString() { @@ -110,57 +106,58 @@ private String argsToString() { return json.toString(); } - public Peer build(Map additionalEnv){ + public Peer build(Map additionalEnv) { ArrayList list = new ArrayList<>(); list.add("peer"); list.add("chaincode"); - list.add(evaluate?"query":"invoke"); + list.add(evaluate ? "query" : "invoke"); if (tlsArgs != null && !tlsArgs.isEmpty()) { list.add(tlsArgs); } - if (channel == null || channel.isEmpty()){ + if (channel == null || channel.isEmpty()) { throw new RuntimeException("Channel should be set"); } list.add("-C"); list.add(channel); - if (ccname == null || ccname.isEmpty()){ + if (ccname == null || ccname.isEmpty()) { throw new RuntimeException("Chaincode name should be set"); } list.add("-n"); list.add(ccname); - if (args == null || args.isEmpty()){ + if (args == null || args.isEmpty()) { throw new RuntimeException("Args should be set"); } list.add("-c"); list.add(argsToString()); - if (transientData != null && !transientData.isEmpty()){ + if (transientData != null && !transientData.isEmpty()) { list.add("--transient"); list.add(transientToString()); } - if (waitForEventTimeout>0){ + if (waitForEventTimeout > 0) { list.add("--waitForEvent --waitForEventTimeout"); - list.add(waitForEventTimeout+"s"); - } else if (waitForEventTimeout == 0 ){ + list.add(waitForEventTimeout + "s"); + } else if (waitForEventTimeout == 0) { list.add("--waitForEvent"); } + list.add("--orderer"); + list.add("orderer-api.127-0-0-1.nip.io:8080"); list.add("--peerAddresses"); list.add("org1peer-api.127-0-0-1.nip.io:8080"); list.add("--peerAddresses"); list.add("org2peer-api.127-0-0-1.nip.io:8080"); - return new Peer(list,additionalEnv); + return new Peer(list, additionalEnv); } } - - Peer(List cmd, Map additionalEnv) { - super(cmd,additionalEnv); + Peer(List cmd, Map additionalEnv) { + super(cmd, additionalEnv); } -} \ No newline at end of file +} diff --git a/fabric-chaincode-integration-test/src/test/resources/docker-compose-microfab.yaml b/fabric-chaincode-integration-test/src/test/resources/docker-compose-microfab.yaml index 1139861b6..79dfc2d7a 100644 --- a/fabric-chaincode-integration-test/src/test/resources/docker-compose-microfab.yaml +++ b/fabric-chaincode-integration-test/src/test/resources/docker-compose-microfab.yaml @@ -9,10 +9,10 @@ services: microfab: container_name: microfab - image: ibmcom/ibp-microfab + image: ghcr.io/hyperledger-labs/microfab tty: true environment: - - MICROFAB_CONFIG={"couchdb":false,"endorsing_organizations":[{"name":"org1"},{"name":"org2"}],"channels":[{"name":"sachannel","endorsing_organizations":["org1","org2"]}],"capability_level":"V2_0"} + - MICROFAB_CONFIG={"couchdb":false,"endorsing_organizations":[{"name":"org1"},{"name":"org2"}],"channels":[{"name":"sachannel","endorsing_organizations":["org1","org2"]}],"capability_level":"V2_5"} - FABRIC_LOGGING_SPEC=info ports: - 8080:8080 diff --git a/fabric-chaincode-integration-test/src/test/resources/scripts/mfsetup.sh b/fabric-chaincode-integration-test/src/test/resources/scripts/mfsetup.sh index bfed23327..8329c2708 100755 --- a/fabric-chaincode-integration-test/src/test/resources/scripts/mfsetup.sh +++ b/fabric-chaincode-integration-test/src/test/resources/scripts/mfsetup.sh @@ -11,7 +11,7 @@ mkdir -p "${CFG}" # using the IBM tagged version until labs workflow is updated docker rm -f microfab || true -export MICROFAB_CONFIG='{"couchdb":false,"endorsing_organizations":[{"name":"org1"},{"name":"org2"}],"channels":[{"name":"sachannel","endorsing_organizations":["org1","org2"]}],"capability_level":"V2_0"}' +export MICROFAB_CONFIG='{"couchdb":false,"endorsing_organizations":[{"name":"org1"},{"name":"org2"}],"channels":[{"name":"sachannel","endorsing_organizations":["org1","org2"]}],"capability_level":"V2_5"}' docker run --name microfab \ -d \ @@ -20,12 +20,10 @@ docker run --name microfab \ --rm \ -e MICROFAB_CONFIG="${MICROFAB_CONFIG}" \ -e FABRIC_LOGGING_SPEC=info \ - ibmcom/ibp-microfab + ghcr.io/hyperledger-labs/microfab +timeout 60s bash -c 'docker logs -f microfab | grep --max-count=1 "Microfab started"' - -sleep 10 - -curl -sSL http://console.localho.st:8080/ak/api/v1/components > $CFG/cfg.json +curl -sSL http://console.localho.st:8080/ak/api/v1/components > $CFG/cfg.json npx @hyperledger-labs/weft microfab -w $CFG/_wallets -p $CFG/_gateways -m $CFG/_msp -f --config $CFG/cfg.json # bring in the helper bash scripts @@ -33,40 +31,40 @@ npx @hyperledger-labs/weft microfab -w $CFG/_wallets -p $CFG/_gateways -m $CFG/_ function deployCC() { -## package the chaincode -packageChaincode + ## package the chaincode + packageChaincode -## Install chaincode on peer0.org1 and peer0.org2 -infoln "Installing chaincode on peer0.org1..." -installChaincode 1 -infoln "Install chaincode on peer0.org2..." -installChaincode 2 + ## Install chaincode on peer0.org1 and peer0.org2 + infoln "Installing chaincode on peer0.org1..." + installChaincode 1 + infoln "Install chaincode on peer0.org2..." + installChaincode 2 -## query whether the chaincode is installed -queryInstalled 1 + ## query whether the chaincode is installed + queryInstalled 1 -## approve the definition for org1 -approveForMyOrg 1 + ## approve the definition for org1 + approveForMyOrg 1 -## check whether the chaincode definition is ready to be committed -## expect org1 to have approved and org2 not to -checkCommitReadiness 1 "\"org1MSP\": true" "\"org2MSP\": false" -checkCommitReadiness 2 "\"org1MSP\": true" "\"org2MSP\": false" + ## check whether the chaincode definition is ready to be committed + ## expect org1 to have approved and org2 not to + checkCommitReadiness 1 "\"org1MSP\": true" "\"org2MSP\": false" + checkCommitReadiness 2 "\"org1MSP\": true" "\"org2MSP\": false" -## now approve also for org2 -approveForMyOrg 2 + ## now approve also for org2 + approveForMyOrg 2 -## check whether the chaincode definition is ready to be committed -## expect them both to have approved -checkCommitReadiness 1 "\"org1MSP\": true" "\"org2MSP\": true" -checkCommitReadiness 2 "\"org1MSP\": true" "\"org2MSP\": true" + ## check whether the chaincode definition is ready to be committed + ## expect them both to have approved + checkCommitReadiness 1 "\"org1MSP\": true" "\"org2MSP\": true" + checkCommitReadiness 2 "\"org1MSP\": true" "\"org2MSP\": true" -## now that we know for sure both orgs have approved, commit the definition -commitChaincodeDefinition 1 2 + ## now that we know for sure both orgs have approved, commit the definition + commitChaincodeDefinition 1 2 -## query on both orgs to see that the definition committed successfully -queryCommitted 1 -queryCommitted 2 + ## query on both orgs to see that the definition committed successfully + queryCommitted 1 + queryCommitted 2 } #./gradlew -I ./chaincode-init.gradle -PchaincodeRepoDir=$(realpath ./fabric-chaincode-integration-test/src/contracts/fabric-ledger-api/repository) publishShimPublicationToFabricRepository diff --git a/fabric-chaincode-shim/build.gradle b/fabric-chaincode-shim/build.gradle index ded8f870e..eff78a88c 100644 --- a/fabric-chaincode-shim/build.gradle +++ b/fabric-chaincode-shim/build.gradle @@ -8,22 +8,18 @@ plugins { id 'maven-publish' id 'jacoco' id 'signing' - id 'checkstyle' + id 'pmd' } -checkstyle { - toolVersion '10.18.1' - configFile file("../ci/checkstyle/checkstyle.xml") - configProperties = [root_dir: file("..") ] -} -checkstyleMain { - source ='src/main/java' -} -checkstyleMain.exclude("**/ChaincodeServerProperties.**") -checkstyleTest { - source ='src/test/java' +pmd { + toolVersion = '7.7.0' + ruleSetFiles = files('../pmd-ruleset.xml') + ruleSets = [] // explicitly set to empty to avoid using the default configuration + ignoreFailures = false } +pmdTest.enabled = false + configurations { runtimeClasspath { resolutionStrategy.activateDependencyLocking() @@ -46,17 +42,17 @@ tasks.withType(org.gradle.api.tasks.testing.Test) { dependencies { implementation platform('com.google.protobuf:protobuf-bom:3.25.5') - implementation platform('io.grpc:grpc-bom:1.68.0') + implementation platform('io.grpc:grpc-bom:1.68.1') implementation platform('io.opentelemetry:opentelemetry-bom:1.42.1') implementation 'org.hyperledger.fabric:fabric-protos:0.3.3' - implementation 'org.bouncycastle:bcpkix-jdk18on:1.78.1' - implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1' - implementation 'io.github.classgraph:classgraph:4.8.176' + implementation 'org.bouncycastle:bcpkix-jdk18on:1.79' + implementation 'org.bouncycastle:bcprov-jdk18on:1.79' + implementation 'io.github.classgraph:classgraph:4.8.179' implementation 'com.github.everit-org.json-schema:org.everit.json.schema:1.14.4' implementation 'org.json:json:20240303' implementation 'com.google.protobuf:protobuf-java-util' - + implementation 'io.grpc:grpc-netty-shaded' implementation 'io.grpc:grpc-protobuf' implementation 'io.grpc:grpc-stub' @@ -90,7 +86,7 @@ sourceSets { } jacoco { - toolVersion = "0.8.6" + toolVersion = "0.8.12" } jacocoTestReport { @@ -226,7 +222,7 @@ javadoc { source = sourceSets.main.allJava classpath = sourceSets.main.runtimeClasspath - + javadoc.options.addStringOption('Xdoclint:none', '-quiet') options.overview = "src/main/java/org/hyperledger/fabric/overview.html" } @@ -297,7 +293,7 @@ publishing { username = project.findProperty('ossrhUsername') password = project.findProperty('ossrhPassword') } - + } maven { diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logger.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logger.java index c8b0f9d66..35720635b 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logger.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logger.java @@ -11,17 +11,14 @@ import java.util.logging.Level; import java.util.logging.LogManager; -/** - * Logger class to use throughout the Contract Implementation. - * - */ +/** Logger class to use throughout the Contract Implementation. */ public class Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); // ensure that the parent logger is set - this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); + super.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } /** @@ -32,16 +29,12 @@ public static Logger getLogger(final String name) { return new Logger(name); } - /** - * @param msgSupplier - */ + /** @param msgSupplier */ public void debug(final Supplier msgSupplier) { log(Level.FINEST, msgSupplier); } - /** - * @param msg - */ + /** @param msg */ public void debug(final String msg) { log(Level.FINEST, msg); } @@ -52,21 +45,17 @@ public void debug(final String msg) { */ public static Logger getLogger(final Class class1) { // important to add the logger to the log manager - final Logger l = Logger.getLogger(class1.getName()); - LogManager.getLogManager().addLogger(l); - return l; + final Logger result = Logger.getLogger(class1.getName()); + LogManager.getLogManager().addLogger(result); + return result; } - /** - * @param message - */ + /** @param message */ public void error(final String message) { log(Level.SEVERE, message); } - /** - * @param msgSupplier - */ + /** @param msgSupplier */ public void error(final Supplier msgSupplier) { log(Level.SEVERE, msgSupplier); } @@ -92,5 +81,4 @@ public String formatError(final Throwable throwable) { return buffer.toString(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logging.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logging.java index b6369056a..0901d75e3 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logging.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/Logging.java @@ -7,39 +7,31 @@ import java.io.PrintWriter; import java.io.StringWriter; -import java.util.ArrayList; import java.util.Collections; +import java.util.List; +import java.util.Locale; import java.util.logging.Level; import java.util.logging.LogManager; /** * Assistance class to use when logging. * - * For chaincode/contract implementations please use java.util.logging or your - * own framework. All the Hyperledger Fabric code here is logged in loggers with - * names starting org.hyperledger + *

For chaincode/contract implementations please use java.util.logging or your own framework. All the Hyperledger + * Fabric code here is logged in loggers with names starting org.hyperledger * - * Control of this is via the environment variables - * 'CORE_CHAINCODE_LOGGING_LEVEL' this takes a string that matches the following - * Java.util.logging levels (case insensitive) - * - * CRITICAL, ERROR == Level.SEVERE, WARNING == Level.WARNING, INFO == Level.INFO - * NOTICE == Level.CONFIG, DEBUG == Level.FINEST + *

Control of this is via the environment variables 'CORE_CHAINCODE_LOGGING_LEVEL' this takes a string that matches + * the following Java.util.logging levels (case insensitive) * + *

CRITICAL, ERROR == Level.SEVERE, WARNING == Level.WARNING, INFO == Level.INFO NOTICE == Level.CONFIG, DEBUG == + * Level.FINEST */ public final class Logging { - /** - * Name of the Performance logger. - */ + /** Name of the Performance logger. */ public static final String PERFLOGGER = "org.hyperledger.Performance"; - /** Private Constructor. - * - */ - private Logging() { - - } + /** Private Constructor. */ + private Logging() {} /** * Formats a Throwable to a string with details of all the causes. @@ -59,11 +51,10 @@ public static String formatError(final Throwable throwable) { final Throwable cause = throwable.getCause(); if (cause != null) { buffer.append(".. caused by ..").append(System.lineSeparator()); - buffer.append(Logging.formatError(cause)); + buffer.append(formatError(cause)); } return buffer.toString(); - } /** @@ -77,32 +68,35 @@ public static void setLogLevel(final String newLevel) { final LogManager logManager = LogManager.getLogManager(); // slightly cumbersome approach - but the loggers don't have a 'get children' // so find those that have the correct stem. - final ArrayList allLoggers = Collections.list(logManager.getLoggerNames()); + final List allLoggers = Collections.list(logManager.getLoggerNames()); allLoggers.add("org.hyperledger"); - allLoggers.stream().filter(name -> name.startsWith("org.hyperledger")).map(name -> logManager.getLogger(name)).forEach(logger -> { - if (logger != null) { - logger.setLevel(l); - } - }); + allLoggers.stream() + .filter(name -> name.startsWith("org.hyperledger")) + .map(logManager::getLogger) + .forEach(logger -> { + if (logger != null) { + logger.setLevel(l); + } + }); } private static Level mapLevel(final String level) { if (level != null) { - switch (level.toUpperCase().trim()) { - case "ERROR": - case "CRITICAL": - return Level.SEVERE; - case "WARNING": - case "WARN": - return Level.WARNING; - case "INFO": - return Level.INFO; - case "NOTICE": - return Level.CONFIG; - case "DEBUG": - return Level.FINEST; - default: - return Level.INFO; + switch (level.toUpperCase(Locale.getDefault()).trim()) { + case "ERROR": + case "CRITICAL": + return Level.SEVERE; + case "WARNING": + case "WARN": + return Level.WARNING; + case "INFO": + return Level.INFO; + case "NOTICE": + return Level.CONFIG; + case "DEBUG": + return Level.FINEST; + default: + return Level.INFO; } } return Level.INFO; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ClientIdentity.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ClientIdentity.java index 078e0657f..2ce5cbbc1 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ClientIdentity.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ClientIdentity.java @@ -15,7 +15,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DEROctetString; @@ -26,19 +25,16 @@ import org.json.JSONObject; /** - * ClientIdentity represents information about the identity that submitted a - * transaction. Chaincodes can use this class to obtain information about the - * submitting identity including a unique ID, the MSP (Membership Service - * Provider) ID, and attributes. Such information is useful in enforcing access - * control by the chaincode. - * + * ClientIdentity represents information about the identity that submitted a transaction. Chaincodes can use this class + * to obtain information about the submitting identity including a unique ID, the MSP (Membership Service Provider) ID, + * and attributes. Such information is useful in enforcing access control by the chaincode. */ public final class ClientIdentity { - private static Logger logger = Logger.getLogger(ContractRouter.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ContractRouter.class.getName()); private final String mspId; private final X509Certificate cert; - private Map attrs; + private final Map attrs; private final String id; // special OID used by Fabric to save attributes in x.509 certificates private static final String FABRIC_CERT_ATTR_OID = "1.2.3.4.5.6.7.8.1"; @@ -51,7 +47,7 @@ public final class ClientIdentity { * @throws JSONException * @throws IOException */ - public ClientIdentity(final ChaincodeStub stub) throws CertificateException, JSONException, IOException { + public ClientIdentity(final ChaincodeStub stub) throws CertificateException, IOException { final byte[] signingId = stub.getCreator(); // Create a Serialized Identity protobuf @@ -60,23 +56,25 @@ public ClientIdentity(final ChaincodeStub stub) throws CertificateException, JSO final byte[] idBytes = si.getIdBytes().toByteArray(); - final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(idBytes)); + final X509Certificate cert = (X509Certificate) + CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(idBytes)); this.cert = cert; - this.attrs = new HashMap(); // Get the extension where the identity attributes are stored final byte[] extensionValue = cert.getExtensionValue(FABRIC_CERT_ATTR_OID); if (extensionValue != null) { this.attrs = parseAttributes(extensionValue); + } else { + this.attrs = new HashMap<>(); } // Populate identity - this.id = "x509::" + cert.getSubjectDN().getName() + "::" + cert.getIssuerDN().getName(); + this.id = "x509::" + cert.getSubjectDN().getName() + "::" + + cert.getIssuerDN().getName(); } /** - * getId returns the ID associated with the invoking identity. This ID is - * guaranteed to be unique within the MSP. + * getId returns the ID associated with the invoking identity. This ID is guaranteed to be unique within the MSP. * * @return {String} A string in the format: "x509::{subject DN}::{issuer DN}" */ @@ -96,18 +94,18 @@ public String getMSPID() { /** * parseAttributes returns a map of the attributes associated with an identity. * - * @param extensionValue DER-encoded Octet string stored in the attributes - * extension of the certificate, as a byte array - * @return attrMap {Map} a map of identity attributes as key - * value pair strings + * @param extensionValue DER-encoded Octet string stored in the attributes extension of the certificate, as a byte + * array + * @return attrMap {Map} a map of identity attributes as key value pair strings * @throws IOException */ private Map parseAttributes(final byte[] extensionValue) throws IOException { - final Map attrMap = new HashMap(); + final Map attrMap = new HashMap<>(); // Create ASN1InputStream from extensionValue - try (ByteArrayInputStream inStream = new ByteArrayInputStream(extensionValue); ASN1InputStream asn1InputStream = new ASN1InputStream(inStream)) { + try (ByteArrayInputStream inStream = new ByteArrayInputStream(extensionValue); + ASN1InputStream asn1InputStream = new ASN1InputStream(inStream)) { // Read the DER object final ASN1Primitive derObject = asn1InputStream.readObject(); @@ -129,56 +127,42 @@ private Map parseAttributes(final byte[] extensionValue) throws } catch (final JSONException error) { // creating a JSON object failed // decoded extensionValue is not a string containing JSON - logger.error(() -> logger.formatError(error)); + LOGGER.error(() -> LOGGER.formatError(error)); // return empty map } return attrMap; } /** - * getAttributeValue returns the value of the client's attribute named - * `attrName`. If the invoking identity possesses the attribute, returns the - * value of the attribute. If the invoking identity does not possess the + * getAttributeValue returns the value of the client's attribute named `attrName`. If the invoking identity + * possesses the attribute, returns the value of the attribute. If the invoking identity does not possess the * attribute, returns null. * - * @param attrName Name of the attribute to retrieve the value from the - * identity's credentials (such as x.509 certificate for - * PKI-based MSPs). - * @return {String | null} Value of the attribute or null if the invoking - * identity does not possess the attribute. + * @param attrName Name of the attribute to retrieve the value from the identity's credentials (such as x.509 + * certificate for PKI-based MSPs). + * @return {String | null} Value of the attribute or null if the invoking identity does not possess the attribute. */ public String getAttributeValue(final String attrName) { - if (this.attrs.containsKey(attrName)) { - return this.attrs.get(attrName); - } else { - return null; - } + return this.attrs.getOrDefault(attrName, null); } /** - * assertAttributeValue verifies that the invoking identity has the attribute - * named `attrName` with a value of `attrValue`. + * assertAttributeValue verifies that the invoking identity has the attribute named `attrName` with a value of + * `attrValue`. * - * @param attrName Name of the attribute to retrieve the value from the - * identity's credentials (such as x.509 certificate for - * PKI-based MSPs) + * @param attrName Name of the attribute to retrieve the value from the identity's credentials (such as x.509 + * certificate for PKI-based MSPs) * @param attrValue Expected value of the attribute - * @return {boolean} True if the invoking identity possesses the attribute and - * the attribute value matches the expected value. Otherwise, returns - * false. + * @return {boolean} True if the invoking identity possesses the attribute and the attribute value matches the + * expected value. Otherwise, returns false. */ public boolean assertAttributeValue(final String attrName, final String attrValue) { - if (!this.attrs.containsKey(attrName)) { - return false; - } else { - return attrValue.equals(this.attrs.get(attrName)); - } + return this.attrs.containsKey(attrName) && attrValue.equals(this.attrs.get(attrName)); } /** - * getX509Certificate returns the X509 certificate associated with the invoking - * identity, or null if it was not identified by an X509 certificate, for - * instance if the MSP is implemented with an alternative to PKI such as + * getX509Certificate returns the X509 certificate associated with the invoking identity, or null if it was not + * identified by an X509 certificate, for instance if the MSP is implemented with an alternative to PKI such as * [Identity Mixer](https://jira.hyperledger.org/browse/FAB-5673). * * @return {X509Certificate | null} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/Context.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/Context.java index c11f17f9b..ea0b4d362 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/Context.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/Context.java @@ -8,22 +8,17 @@ import java.io.IOException; import java.security.cert.CertificateException; - import org.hyperledger.fabric.shim.ChaincodeStub; import org.json.JSONException; /** + * This context is available to all 'transaction functions' and provides the transaction context. It also provides + * access to the APIs for the world state using {@link #getStub()} * - * This context is available to all 'transaction functions' and provides the - * transaction context. It also provides access to the APIs for the world state - * using {@link #getStub()} - *

- * Applications can implement their own versions if they wish to add - * functionality. All subclasses MUST implement a constructor, for example - * - *

- * {@code
+ * 

Applications can implement their own versions if they wish to add functionality. All subclasses MUST implement a + * constructor, for example * + *

{@code
  * public MyContext extends Context {
  *
  *     public MyContext(ChaincodeStub stub) {
@@ -31,19 +26,13 @@
  *     }
  * }
  *
- *}
- * 
- * + * }
*/ public class Context { - /** - * - */ + /** */ protected ChaincodeStub stub; - /** - * - */ + /** */ protected ClientIdentity clientIdentity; /** @@ -60,18 +49,12 @@ public Context(final ChaincodeStub stub) { } } - /** - * - * @return ChaincodeStub instance to use - */ + /** @return ChaincodeStub instance to use */ public ChaincodeStub getStub() { return this.stub; } - /** - * - * @return ClientIdentity object to use - */ + /** @return ClientIdentity object to use */ public ClientIdentity getClientIdentity() { return this.clientIdentity; } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContextFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContextFactory.java index b282dc2db..68514adb1 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContextFactory.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContextFactory.java @@ -8,32 +8,20 @@ import org.hyperledger.fabric.shim.ChaincodeStub; -/** - * Factory to create {@link Context} from {@link ChaincodeStub} by wrapping stub - * with dynamic proxy. - */ +/** Factory to create {@link Context} from {@link ChaincodeStub} by wrapping stub with dynamic proxy. */ public final class ContextFactory { - private static ContextFactory cf; + private static final ContextFactory INSTANCE = new ContextFactory(); - /** - * - * @return ContextFactory - */ - public static synchronized ContextFactory getInstance() { - if (cf == null) { - cf = new ContextFactory(); - } - return cf; + /** @return ContextFactory */ + public static ContextFactory getInstance() { + return INSTANCE; } /** - * * @param stub * @return Context */ public Context createContext(final ChaincodeStub stub) { - final Context newContext = new Context(stub); - return newContext; + return new Context(stub); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractInterface.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractInterface.java index 9ef0352e1..e1db9de43 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractInterface.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractInterface.java @@ -12,52 +12,44 @@ /** * All Contracts should implement this interface, in addition to the * {@linkplain org.hyperledger.fabric.contract.annotation.Contract} annotation. - *

- * All methods on this interface have default implementations; for - * many contracts it may not be needed to sub-class these. - *

- * Each method on the Contract that is marked with the {@link org.hyperledger.fabric.contract.annotation.Transaction} - * annotation is considered a Transaction Function. This is eligible for - * calling. Each transaction function is supplied with its first parameter - * being a {@link org.hyperledger.fabric.contract.Context}. The other parameters - * are supplied at the developer's discretion. - *

- * The sequence of calls is + * + *

All methods on this interface have default implementations; for many contracts it may not be needed to sub-class + * these. + * + *

Each method on the Contract that is marked with the {@link org.hyperledger.fabric.contract.annotation.Transaction} + * annotation is considered a Transaction Function. This is eligible for calling. Each transaction function is supplied + * with its first parameter being a {@link org.hyperledger.fabric.contract.Context}. The other parameters are supplied + * at the developer's discretion. + * + *

The sequence of calls is * *

  * createContext()  -> beforeTransaction() -> the transaction function -> afterTransaction()
  * 
- *

- * If any of these functions throws an exception it is considered an error case - * and the whole transaction is failed. The - * {@link org.hyperledger.fabric.contract.Context} is a very important object as - * it provides transactional context for access to current transaction id, - * ledger state, etc. - *

- * Note on Threading - *

- * All code should be 'Thread Friendly'. Each method must not rely on instance - * fields or class side variables for storage. Nor should they use any - * ThreadLocal Storage. Ledger data is stored via the ledger api available via - * the {@link Context}. - *

- * If information needs to be passed from - * {@link #beforeTransaction(Context)} to - * {@link #afterTransaction(Context, Object)} or between separate transaction - * functions when called directly then a subclass of the {@link Context} - * should be provided. + * + *

If any of these functions throws an exception it is considered an error case and the whole transaction is failed. + * The {@link org.hyperledger.fabric.contract.Context} is a very important object as it provides transactional context + * for access to current transaction id, ledger state, etc. + * + *

Note on Threading + * + *

All code should be 'Thread Friendly'. Each method must not rely on instance fields or class side variables for + * storage. Nor should they use any ThreadLocal Storage. Ledger data is stored via the ledger api available via the + * {@link Context}. + * + *

If information needs to be passed from {@link #beforeTransaction(Context)} to {@link #afterTransaction(Context, + * Object)} or between separate transaction functions when called directly then a subclass of the {@link Context} should + * be provided. */ public interface ContractInterface { /** * Create context from {@link ChaincodeStub}. * - * Default impl provided, but can be - * overwritten by contract + *

Default impl provided, but can be overwritten by contract * * @param stub Instance of the ChaincodeStub to use for this transaction - * @return instance of the context to use for the current transaction being - * executed + * @return instance of the context to use for the current transaction being executed */ default Context createContext(final ChaincodeStub stub) { return ContextFactory.getInstance().createContext(stub); @@ -66,9 +58,8 @@ default Context createContext(final ChaincodeStub stub) { /** * Invoked for any transaction that does not exist. * - * This will throw an exception. If you wish to alter the exception thrown or if - * you wish to consider requests for transactions that don't exist as not an - * error, subclass this method. + *

This will throw an exception. If you wish to alter the exception thrown or if you wish to consider requests + * for transactions that don't exist as not an error, subclass this method. * * @param ctx the context as created by {@link #createContext(ChaincodeStub)}. */ @@ -79,25 +70,25 @@ default void unknownTransaction(final Context ctx) { /** * Invoked once before each transaction. * - * Any exceptions thrown will fail the transaction, and neither the required - * transaction or the {@link #afterTransaction(Context, Object)} will be called + *

Any exceptions thrown will fail the transaction, and neither the required transaction or the + * {@link #afterTransaction(Context, Object)} will be called * * @param ctx the context as created by {@link #createContext(ChaincodeStub)}. */ default void beforeTransaction(final Context ctx) { + // Nothing by default } /** * Invoked once after each transaction. * - * Any exceptions thrown will fail the transaction. + *

Any exceptions thrown will fail the transaction. * - * @param ctx the context as created by - * {@link #createContext(ChaincodeStub)}. - * @param result The object returned from the transaction function if any. As - * this is a Java object and therefore pass-by-reference it is - * possible to modify this object. + * @param ctx the context as created by {@link #createContext(ChaincodeStub)}. + * @param result The object returned from the transaction function if any. As this is a Java object and therefore + * pass-by-reference it is possible to modify this object. */ default void afterTransaction(final Context ctx, final Object result) { + // Nothing by default } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRouter.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRouter.java index 510f14988..d7b6f9e5d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRouter.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRouter.java @@ -6,6 +6,9 @@ package org.hyperledger.fabric.contract; +import java.io.IOException; +import java.util.Properties; +import java.util.logging.Logger; import org.hyperledger.fabric.Logging; import org.hyperledger.fabric.contract.execution.ExecutionFactory; import org.hyperledger.fabric.contract.execution.ExecutionService; @@ -25,18 +28,14 @@ import org.hyperledger.fabric.shim.ResponseUtils; import org.hyperledger.fabric.traces.Traces; -import java.io.IOException; -import java.util.Properties; -import java.util.logging.Logger; - /** - * Router class routes Init/Invoke requests to contracts. Implements - * {@link org.hyperledger.fabric.shim.Chaincode} interface. + * Router class routes Init/Invoke requests to contracts. Implements {@link org.hyperledger.fabric.shim.Chaincode} + * interface. * * @see ContractInterface */ public final class ContractRouter extends ChaincodeBase { - private static Logger logger = Logger.getLogger(ContractRouter.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ContractRouter.class.getName()); private final RoutingRegistry registry; private final TypeRegistry typeRegistry; @@ -47,14 +46,14 @@ public final class ContractRouter extends ChaincodeBase { private final ExecutionService executor; /** - * Take the arguments from the cli, and initiate processing of cli options and - * environment variables. + * Take the arguments from the cli, and initiate processing of cli options and environment variables. * - * Create the Contract scanner, and the Execution service + *

Create the Contract scanner, and the Execution service * * @param args */ public ContractRouter(final String[] args) { + super(); super.initializeLogging(); super.processEnvironmentOptions(); super.processCommandLineOptions(args); @@ -64,7 +63,7 @@ public ContractRouter(final String[] args) { Metrics.initialize(props); Traces.initialize(props); - logger.fine("ContractRouter"); + LOGGER.fine("ContractRouter"); registry = new RoutingRegistryImpl(); typeRegistry = TypeRegistry.getRegistry(); @@ -74,49 +73,48 @@ public ContractRouter(final String[] args) { serializers.findAndSetContents(); } catch (InstantiationException | IllegalAccessException e) { final ContractRuntimeException cre = new ContractRuntimeException("Unable to locate Serializers", e); - logger.severe(() -> Logging.formatError(cre)); - throw new RuntimeException(cre); + LOGGER.severe(() -> Logging.formatError(cre)); + throw cre; } executor = ExecutionFactory.getInstance().createExecutionService(serializers); } - /** - * Locate all the contracts that are available on the classpath. - */ - protected void findAllContracts() { + /** Locate all the contracts that are available on the classpath. */ + void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } /** * Start the chaincode container off and running. * - * This will send the initial flow back to the peer + *

This will send the initial flow back to the peer * * @throws Exception */ + @SuppressWarnings("PMD.AvoidCatchingGenericException") void startRouting() { try { super.connectToPeer(); } catch (final Exception e) { - logger.severe(() -> Logging.formatError(e)); - final ContractRuntimeException cre = new ContractRuntimeException("Unable to start routing", e); - throw cre; + LOGGER.severe(() -> Logging.formatError(e)); + throw new ContractRuntimeException("Unable to start routing", e); } } + @SuppressWarnings("PMD.AvoidCatchingThrowable") private Response processRequest(final ChaincodeStub stub) { - logger.info(() -> "Got invoke routing request"); + LOGGER.info(() -> "Got invoke routing request"); try { - if (stub.getStringArgs().size() > 0) { - logger.info(() -> "Got the invoke request for:" + stub.getFunction() + " " + stub.getParameters()); - final InvocationRequest request = ExecutionFactory.getInstance().createRequest(stub); - final TxFunction txFn = getRouting(request); - logger.info(() -> "Got routing:" + txFn.getRouting()); - return executor.executeRequest(txFn, request, stub); - } else { + if (stub.getStringArgs().isEmpty()) { return ResponseUtils.newSuccessResponse(); } + + LOGGER.info(() -> "Got the invoke request for:" + stub.getFunction() + " " + stub.getParameters()); + final InvocationRequest request = ExecutionFactory.getInstance().createRequest(stub); + final TxFunction txFn = getRouting(request); + LOGGER.info(() -> "Got routing:" + txFn.getRouting()); + return executor.executeRequest(txFn, request, stub); } catch (final Throwable throwable) { return ResponseUtils.newErrorResponse(throwable); } @@ -143,7 +141,7 @@ TxFunction getRouting(final InvocationRequest request) { if (registry.containsRoute(request)) { return registry.getTxFn(request); } else { - logger.fine(() -> "Namespace is " + request); + LOGGER.fine(() -> "Namespace is " + request); final ContractDefinition contract = registry.getContract(request.getNamespace()); return contract.getUnknownRoute(); } @@ -154,35 +152,35 @@ TxFunction getRouting(final InvocationRequest request) { * * @param args */ + @SuppressWarnings("PMD.SignatureDeclareThrowsException") public static void main(final String[] args) throws Exception { final ContractRouter cfc = new ContractRouter(args); cfc.findAllContracts(); - logger.fine(cfc.getRoutingRegistry().toString()); + LOGGER.fine(() -> cfc.getRoutingRegistry().toString()); // Create the Metadata ahead of time rather than have to produce every // time MetadataBuilder.initialize(cfc.getRoutingRegistry(), cfc.getTypeRegistry()); - logger.info(() -> "Metadata follows:" + MetadataBuilder.debugString()); + LOGGER.info(() -> "Metadata follows:" + MetadataBuilder.debugString()); // check if this should be running in client or server mode if (cfc.isServer()) { - logger.info("Starting chaincode as server"); - ChaincodeServer chaincodeServer = new NettyChaincodeServer(cfc, - cfc.getChaincodeServerConfig()); + LOGGER.info("Starting chaincode as server"); + ChaincodeServer chaincodeServer = new NettyChaincodeServer(cfc, cfc.getChaincodeServerConfig()); chaincodeServer.start(); } else { - logger.info("Starting chaincode as client"); + LOGGER.info("Starting chaincode as client"); cfc.startRouting(); } } - protected TypeRegistry getTypeRegistry() { + TypeRegistry getTypeRegistry() { return this.typeRegistry; } - protected RoutingRegistry getRoutingRegistry() { + RoutingRegistry getRoutingRegistry() { return this.registry; } @@ -194,12 +192,11 @@ protected RoutingRegistry getRoutingRegistry() { public void startRouterWithChaincodeServer(final ChaincodeServer chaincodeServer) throws IOException, InterruptedException { findAllContracts(); - logger.fine(getRoutingRegistry().toString()); + LOGGER.fine(() -> getRoutingRegistry().toString()); MetadataBuilder.initialize(getRoutingRegistry(), getTypeRegistry()); - logger.info(() -> "Metadata follows:" + MetadataBuilder.debugString()); + LOGGER.info(() -> "Metadata follows:" + MetadataBuilder.debugString()); chaincodeServer.start(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRuntimeException.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRuntimeException.java index 0fca449fd..78d559a26 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRuntimeException.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/ContractRuntimeException.java @@ -8,25 +8,21 @@ import org.hyperledger.fabric.shim.ChaincodeException; /** - * Specific RuntimeException for events that occur in the calling and handling - * of the Contracts, NOT within the contract logic itself. - *

- * FUTURE At some future point we wish to add more diagnostic information - * into this, for example current tx id + * Specific RuntimeException for events that occur in the calling and handling of the Contracts, NOT within the contract + * logic itself. * + *

FUTURE At some future point we wish to add more diagnostic information into this, for example current tx id */ public class ContractRuntimeException extends ChaincodeException { + /** Generated serial version id. */ + private static final long serialVersionUID = -884373036398750450L; - /** - * - * @param string - */ + /** @param string */ public ContractRuntimeException(final String string) { super(string); } /** - * * @param string * @param cause */ @@ -34,17 +30,8 @@ public ContractRuntimeException(final String string, final Throwable cause) { super(string, cause); } - /** - * - * @param cause - */ + /** @param cause */ public ContractRuntimeException(final Throwable cause) { super(cause); } - - /** - * Generated serial version id. - */ - private static final long serialVersionUID = -884373036398750450L; - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contact.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contact.java index c344b37b3..fb3e2fc9a 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contact.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contact.java @@ -12,27 +12,19 @@ import java.lang.annotation.Target; /** - * Class level annotation that identifies this class as being a contact. Can be - * populated with email, name and url fields. - * + * Class level annotation that identifies this class as being a contact. Can be populated with email, name and url + * fields. */ @Retention(RUNTIME) @Target(ElementType.TYPE) public @interface Contact { - /** - * @return String - */ + /** @return String */ String email() default ""; - /** - * @return String - */ + /** @return String */ String name() default ""; - /** - * @return String - */ + /** @return String */ String url() default ""; - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contract.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contract.java index d28987b26..8114170ec 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contract.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Contract.java @@ -12,19 +12,17 @@ import java.lang.annotation.Target; /** - * Class level annotation that identifies this class as being a contract. Can - * supply information and an alternative name for the contract rather than the - * classname + * Class level annotation that identifies this class as being a contract. Can supply information and an alternative name + * for the contract rather than the classname */ @Retention(RUNTIME) @Target(ElementType.TYPE) public @interface Contract { /** - * The Info object can be supplied to provide additional information about the - * contract. + * The Info object can be supplied to provide additional information about the contract. * - * Including title, description, version and license + *

Including title, description, version and license * * @return Info object */ @@ -33,8 +31,8 @@ /** * Contract name. * - * Normally the name of the class is used to refer to the contract (name without - * package). This can be altered if wished. + *

Normally the name of the class is used to refer to the contract (name without package). This can be altered if + * wished. * * @return Name of the contract to be used instead of the Classname */ @@ -43,14 +41,12 @@ /** * Transaction Serializer Classname. * - * Fully Qualified Classname of the TRANSACTION serializer that should be used - * with this contract. + *

Fully Qualified Classname of the TRANSACTION serializer that should be used with this contract. * - * This is the serializer that is used to parse incoming transaction request - * parameters and convert the return type + *

This is the serializer that is used to parse incoming transaction request parameters and convert the return + * type * * @return Default serializer classname */ String transactionSerializer() default "org.hyperledger.fabric.contract.execution.JSONTransactionSerializer"; - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/DataType.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/DataType.java index 8799198d6..a671fcf0a 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/DataType.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/DataType.java @@ -12,18 +12,15 @@ import java.lang.annotation.Target; /** - * Class level annotation indicating this class represents one of the complex - * types that can be returned or passed to the transaction functions. - *

- * These datatypes are used (within the current implementation) for determining - * the data flow protocol from the Contracts to the SDK and for permitting a - * fully formed Interface Definition to be created for the contract. - *

- * Complex types can appear within this definition, and these are identified - * using this annotation. - *

- * FUTURE To take these annotations are also utilize them for leverage - * storage + * Class level annotation indicating this class represents one of the complex types that can be returned or passed to + * the transaction functions. + * + *

These datatypes are used (within the current implementation) for determining the data flow protocol from the + * Contracts to the SDK and for permitting a fully formed Interface Definition to be created for the contract. + * + *

Complex types can appear within this definition, and these are identified using this annotation. + * + *

FUTURE To take these annotations are also utilize them for leverage storage */ @Retention(RUNTIME) @Target(ElementType.TYPE) diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Default.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Default.java index 683ba6686..f289e56ac 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Default.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Default.java @@ -14,11 +14,9 @@ /** * Default Contract. * - * Class level annotation that defines the contract that is the default - * contract, and as such invoke of the transaction functions does not need to be - * qualified by the contract name + *

Class level annotation that defines the contract that is the default contract, and as such invoke of the + * transaction functions does not need to be qualified by the contract name */ @Retention(RUNTIME) @Target(ElementType.TYPE) -public @interface Default { -} +public @interface Default {} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Info.java index 8b1d05fdb..17d02e16c 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Info.java @@ -15,41 +15,29 @@ /** * Info Details * - * - * Class level annotation that identifies this class as being an info object. - * Can supply additional information about the contract, including title, - * description, version, license and contact information. - * + *

Class level annotation that identifies this class as being an info object. Can supply additional information about + * the contract, including title, description, version, license and contact information. */ @Retention(RUNTIME) @Target(ElementType.TYPE) public @interface Info { - /** - * @return String - */ + /** @return String */ String title() default ""; - /** - * @return String - */ + /** @return String */ String description() default ""; - /** - * @return String - */ + /** @return String */ String version() default ""; - /** - * @return String - */ + /** @return String */ String termsOfService() default ""; /** * License object that can be populated to include name and url. * * @return License object - * */ License license() default @License(); @@ -57,8 +45,6 @@ * Contact object that can be populated with email, name and url fields. * * @return Contact object - * */ Contact contact() default @Contact(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/License.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/License.java index 88989f022..a585f634e 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/License.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/License.java @@ -12,24 +12,16 @@ import java.lang.annotation.Target; /** - * Class level annotation that identifies this class as being a license object. - * Can be populated to include name and url. - * + * Class level annotation that identifies this class as being a license object. Can be populated to include name and + * url. */ @Retention(RUNTIME) @Target(ElementType.TYPE) public @interface License { - /** - * - * @return String - */ + /** @return String */ String name() default ""; - /** - * - * @return String - */ + /** @return String */ String url() default ""; - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Property.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Property.java index 1b75fffbd..5a94e8dcc 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Property.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Property.java @@ -14,10 +14,9 @@ /** * Field and parameter level annotation defining a property of the class. * - * (identified by {@link DataType}) Can also be used on the parameters of - * transaction functions - *

- * Example of using this annotation + *

(identified by {@link DataType}) Can also be used on the parameters of transaction functions + * + *

Example of using this annotation * *

  *
@@ -36,9 +35,8 @@
 public @interface Property {
 
     /**
-     * Allows each property to be defined a detail set of rules to determine the
-     * valid types of this data. The format follows the syntax of the OpenAPI Schema
-     * object.
+     * Allows each property to be defined a detail set of rules to determine the valid types of this data. The format
+     * follows the syntax of the OpenAPI Schema object.
      *
      * @return String array of the key-value pairs of the schema
      */
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Serializer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Serializer.java
index 10ff45d65..37d91fc9b 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Serializer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Serializer.java
@@ -12,32 +12,22 @@
 import java.lang.annotation.Target;
 
 /**
- * Class level annotation that defines the serializer that should be used to
- * convert objects to and from the wire format.
+ * Class level annotation that defines the serializer that should be used to convert objects to and from the wire
+ * format.
  *
- * 

This should annotate a class that implements the Serializer interface

+ *

This should annotate a class that implements the Serializer interface */ @Retention(RUNTIME) @Target({ElementType.TYPE, ElementType.TYPE_USE}) public @interface Serializer { - /** - * What is this serializer able to target? - * - */ + /** What is this serializer able to target? */ enum TARGET { - /** - * Target transaction functions. - */ + /** Target transaction functions. */ TRANSACTION, - /** - * Target all elements. - */ + /** Target all elements. */ ALL } - /** - * - * @return Target of the serializer - */ + /** @return Target of the serializer */ TARGET target() default Serializer.TARGET.ALL; } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Transaction.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Transaction.java index c9180ca46..3f41e3fbc 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Transaction.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/annotation/Transaction.java @@ -12,44 +12,35 @@ import java.lang.annotation.Target; /** - * Method level annotation indicating the method to be a callable transaction - * function. - *

- * These functions are called in client SDKs by the combination of + * Method level annotation indicating the method to be a callable transaction function. + * + *

These functions are called in client SDKs by the combination of * *

  *  [contractname]:[transactioname]
  * 
* - * Unless specified otherwise, the contract name is the class name (without - * package) and the transaction name is the method name. + * Unless specified otherwise, the contract name is the class name (without package) and the transaction name is the + * method name. */ @Retention(RUNTIME) @Target(METHOD) public @interface Transaction { - /** - * The intended invocation style for a transaction function. - */ + /** The intended invocation style for a transaction function. */ enum TYPE { - /** - * Transaction is used to submit updates to the ledger. - */ + /** Transaction is used to submit updates to the ledger. */ SUBMIT, - /** - * Transaction is evaluated to query information from the ledger. - */ + /** Transaction is evaluated to query information from the ledger. */ EVALUATE } /** * Submit semantics. * - *

TRUE indicates that this function is intended to be called with the 'submit' - * semantics

+ *

TRUE indicates that this function is intended to be called with the 'submit' semantics * - *

FALSE indicates that this is intended to be called with the evaluate - * semantics

+ *

FALSE indicates that this is intended to be called with the evaluate semantics * * @return boolean, default is true * @deprecated Please use intent @@ -59,19 +50,20 @@ enum TYPE { /** * What are submit semantics for this transaction. + * *

- *
SUBMIT
indicates that this function is intended to be called with the - * 'submit' semantics
- *
EVALUATE
indicates that this is intended to be called - * with the 'evaluate' semantics
+ *
SUBMIT + *
indicates that this function is intended to be called with the 'submit' semantics + *
EVALUATE + *
indicates that this is intended to be called with the 'evaluate' semantics *
+ * * @return submit semantics */ TYPE intent() default Transaction.TYPE.SUBMIT; /** - * The name of the callable transaction if it should be different to the method - * name. + * The name of the callable transaction if it should be different to the method name. * * @return the transaction name */ diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionFactory.java index 0d437c5ea..3cd7a5fcb 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionFactory.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionFactory.java @@ -12,16 +12,11 @@ import org.hyperledger.fabric.shim.ChaincodeStub; public class ExecutionFactory { - private static ExecutionFactory rf; + private static final ExecutionFactory INSTANCE = new ExecutionFactory(); - /** - * @return ExecutionFactory - */ + /** @return ExecutionFactory */ public static ExecutionFactory getInstance() { - if (rf == null) { - rf = new ExecutionFactory(); - } - return rf; + return INSTANCE; } /** diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionService.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionService.java index ef0b97192..8c8596808 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionService.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/ExecutionService.java @@ -13,13 +13,11 @@ /** * ExecutionService. * - * Service that executes {@link InvocationRequest} (wrapped Init/Invoke + extra - * data) using routing information + *

Service that executes {@link InvocationRequest} (wrapped Init/Invoke + extra data) using routing information */ public interface ExecutionService { /** - * * @param txFn * @param req * @param stub diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/InvocationRequest.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/InvocationRequest.java index 6978e0378..92c478c16 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/InvocationRequest.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/InvocationRequest.java @@ -11,33 +11,21 @@ /** * Invocation Request. * - * All information needed to find - * {@link org.hyperledger.fabric.contract.annotation.Contract} and invoke the - * request. + *

All information needed to find {@link org.hyperledger.fabric.contract.annotation.Contract} and invoke the request. */ public interface InvocationRequest { - /** - * - */ + /** */ String DEFAULT_NAMESPACE = "default"; - /** - * @return Namespace - */ + /** @return Namespace */ String getNamespace(); - /** - * @return Method - */ + /** @return Method */ String getMethod(); - /** - * @return Args as byte array - */ + /** @return Args as byte array */ List getArgs(); - /** - * @return Request - */ + /** @return Request */ String getRequestName(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializer.java index c7633e538..ac2e33b99 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializer.java @@ -11,11 +11,8 @@ import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.nio.charset.StandardCharsets; -import java.util.Iterator; import java.util.Map; import java.util.Set; - import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.ContractRuntimeException; import org.hyperledger.fabric.contract.annotation.Serializer; @@ -27,20 +24,13 @@ import org.json.JSONException; import org.json.JSONObject; -/** - * Used as a the default serialisation for transmission from SDK to Contract. - */ +/** Used as the default serialisation for transmission from SDK to Contract. */ @Serializer() +@SuppressWarnings({"PMD.GodClass", "PMD.AvoidLiteralsInIfCondition", "PMD.AvoidDuplicateLiterals"}) public class JSONTransactionSerializer implements SerializerInterface { - private static Logger logger = Logger.getLogger(JSONTransactionSerializer.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JSONTransactionSerializer.class.getName()); private final TypeRegistry typeRegistry = TypeRegistry.getRegistry(); - /** - * Create a new serialiser. - */ - public JSONTransactionSerializer() { - } - /** * Convert the value supplied to a byte array, according to the TypeSchema. * @@ -50,29 +40,29 @@ public JSONTransactionSerializer() { */ @Override public byte[] toBuffer(final Object value, final TypeSchema ts) { - logger.debug(() -> "Schema to convert is " + ts); + LOGGER.debug(() -> "Schema to convert is " + ts); byte[] buffer = null; if (value != null) { final String type = ts.getType(); if (type != null) { switch (type) { - case "array": - final JSONArray array = normalizeArray(new JSONArray(value), ts); - buffer = array.toString().getBytes(UTF_8); - break; - case "string": - final String format = ts.getFormat(); - if (format != null && format.contentEquals("uint16")) { - buffer = Character.valueOf((char) value).toString().getBytes(UTF_8); - } else { - buffer = ((String) value).getBytes(UTF_8); - } - break; - case "number": - case "integer": - case "boolean": - default: - buffer = (value).toString().getBytes(UTF_8); + case "array": + final JSONArray array = normalizeArray(new JSONArray(value), ts); + buffer = array.toString().getBytes(UTF_8); + break; + case "string": + final String format = ts.getFormat(); + if ("utin16".equals(format)) { + buffer = Character.valueOf((char) value).toString().getBytes(UTF_8); + } else { + buffer = ((String) value).getBytes(UTF_8); + } + break; + case "number": + case "integer": + case "boolean": + default: + buffer = value.toString().getBytes(UTF_8); } } else { // at this point we can assert that the value is @@ -82,7 +72,7 @@ public byte[] toBuffer(final Object value, final TypeSchema ts) { // it should have final DataTypeDefinition dtd = this.typeRegistry.getDataType(ts); final Set keySet = dtd.getProperties().keySet(); - final String[] propNames = keySet.toArray(new String[keySet.size()]); + final String[] propNames = keySet.toArray(new String[0]); // Note: whilst the current JSON library does pretty much // everything is required, this part is hard. @@ -102,16 +92,16 @@ public byte[] toBuffer(final Object value, final TypeSchema ts) { /** * Normalize the Array. * - * We need to take the JSON array, and if there are complex datatypes within it - * ensure that they don't get spurious JSON properties appearing + *

We need to take the JSON array, and if there are complex datatypes within it ensure that they don't get + * spurious JSON properties appearing * - * This method needs to be general so has to copy with nested arrays and with - * primitive and Object types + *

This method needs to be general so has to copy with nested arrays and with primitive and Object types * * @param jsonArray incoming array - * @param ts Schema to normalise to + * @param ts Schema to normalise to * @return JSONArray */ + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) { JSONArray normalizedArray; @@ -119,22 +109,12 @@ private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) final TypeSchema items = ts.getItems(); final String type = items.getType(); - if (type != null && type != "array") { - // primitive - can return this directly - normalizedArray = jsonArray; - } else if (type != null && type == "array") { - // nested arrays, get the type of what it makes up - // Need to loop over all elements and normalize each one - normalizedArray = new JSONArray(); - for (int i = 0; i < jsonArray.length(); i++) { - normalizedArray.put(i, normalizeArray(jsonArray.getJSONArray(i), items)); - } - } else { + if (null == type) { // get the permitted propeties in the type, // then loop over the array and ensure they are correct final DataTypeDefinition dtd = this.typeRegistry.getDataType(items); final Set keySet = dtd.getProperties().keySet(); - final String[] propNames = keySet.toArray(new String[keySet.size()]); + final String[] propNames = keySet.toArray(new String[0]); normalizedArray = new JSONArray(); // array of objects @@ -143,8 +123,18 @@ private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) final JSONObject obj = new JSONObject(jsonArray.getJSONObject(i), propNames); normalizedArray.put(i, obj); } - + } else if ("array".equals(type)) { + // nested arrays, get the type of what it makes up + // Need to loop over all elements and normalize each one + normalizedArray = new JSONArray(); + for (int i = 0; i < jsonArray.length(); i++) { + normalizedArray.put(i, normalizeArray(jsonArray.getJSONArray(i), items)); + } + } else { + // primitive - can return this directly + normalizedArray = jsonArray; } + return normalizedArray; } @@ -152,148 +142,180 @@ private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) * Take the byte buffer and return the object as required. * * @param buffer Byte buffer from the wire - * @param ts TypeSchema representing the type - * + * @param ts TypeSchema representing the type * @return Object created; relies on Java auto-boxing for primitives */ @Override public Object fromBuffer(final byte[] buffer, final TypeSchema ts) { try { - final String stringData = new String(buffer, StandardCharsets.UTF_8); - Object value = null; - - value = convert(stringData, ts); - - return value; + final String stringData = new String(buffer, UTF_8); + return convert(stringData, ts); } catch (InstantiationException | IllegalAccessException e) { - final ContractRuntimeException cre = new ContractRuntimeException(e); - throw cre; + throw new ContractRuntimeException(e); } } /** - * We need to be able to map between the primative class types and the object - * variants. In the case where this is needed Java auto-boxing doesn't actually - * help. + * We need to be able to map between the primative class types and the object variants. In the case where this is + * needed Java auto-boxing doesn't actually help. * - * For other types the parameter is passed directly back + *

For other types the parameter is passed directly back * * @param primitive class for the primitive * @return Class for the Object variant */ private Class mapPrimitive(final Class primitive) { - String primitiveType; - final boolean isArray = primitive.isArray(); - if (isArray) { - primitiveType = primitive.getComponentType().getName(); - } else { - primitiveType = primitive.getName(); + if (primitive.isArray()) { + return mapArrayPrimitive(primitive); } - switch (primitiveType) { - case "int": - return isArray ? Integer[].class : Integer.class; - case "long": - return isArray ? Long[].class : Long.class; - case "float": - return isArray ? Float[].class : Float.class; - case "double": - return isArray ? Double[].class : Double.class; - case "short": - return isArray ? Short[].class : Short.class; - case "byte": - return isArray ? Byte[].class : Byte.class; - case "char": - return isArray ? Character[].class : Character.class; - case "boolean": - return isArray ? Boolean[].class : Boolean.class; - default: - return primitive; + return mapBasicPrimitive(primitive); + } + + private Class mapArrayPrimitive(final Class primitive) { + switch (primitive.getComponentType().getName()) { + case "int": + return Integer[].class; + case "long": + return Long[].class; + case "float": + return Float[].class; + case "double": + return Double[].class; + case "short": + return Short[].class; + case "byte": + return Byte[].class; + case "char": + return Character[].class; + case "boolean": + return Boolean[].class; + default: + return primitive; } } - /* - * Internal method to do the conversion - */ - private Object convert(final String stringData, final TypeSchema ts) throws IllegalArgumentException, IllegalAccessException, InstantiationException { - logger.debug(() -> "Schema to convert is " + ts); + private Class mapBasicPrimitive(final Class primitive) { + switch (primitive.getName()) { + case "int": + return Integer.class; + case "long": + return Long.class; + case "float": + return Float.class; + case "double": + return Double.class; + case "short": + return Short.class; + case "byte": + return Byte.class; + case "char": + return Character.class; + case "boolean": + return Boolean.class; + default: + return primitive; + } + } + + /** Internal method to do the conversion */ + private Object convert(final String stringData, final TypeSchema ts) + throws IllegalAccessException, InstantiationException { + LOGGER.debug(() -> "Schema to convert is " + ts); + String type = ts.getType(); + String format = null; - Object value = null; if (type == null) { type = "object"; final String ref = ts.getRef(); - format = ref.substring(ref.lastIndexOf("/") + 1); + format = ref.substring(ref.lastIndexOf('/') + 1); } - if (type.contentEquals("string")) { - final String strformat = ts.getFormat(); - if (strformat != null && strformat.contentEquals("uint16")) { - value = stringData.charAt(0); - } else { - value = stringData; - } - } else if (type.contentEquals("integer")) { - final String intFormat = ts.getFormat(); - switch (intFormat) { + switch (type) { + case "string": + return convertString(stringData, ts); + case "integer": + return convertInteger(stringData, ts); + case "number": + return convertNumber(stringData, ts); + case "boolean": + return Boolean.parseBoolean(stringData); + case "object": + return createComponentInstance(format, stringData, ts); + case "array": + return convertArray(stringData, ts); + default: + return null; + } + } + + private Object convertArray(final String stringData, final TypeSchema ts) + throws IllegalAccessException, InstantiationException { + final JSONArray jsonArray = new JSONArray(stringData); + final TypeSchema itemSchema = ts.getItems(); + + // note here that the type has to be converted in the case of primitives + final Object[] data = (Object[]) + Array.newInstance(mapPrimitive(itemSchema.getTypeClass(this.typeRegistry)), jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + final Object convertedData = convert(jsonArray.get(i).toString(), itemSchema); + data[i] = convertedData; + } + + return data; + } + + private Object convertNumber(final String stringData, final TypeSchema ts) { + if ("float".equals(ts.getFormat())) { + return Float.parseFloat(stringData); + } + + return Double.parseDouble(stringData); + } + + private Object convertInteger(final String stringData, final TypeSchema ts) { + switch (ts.getFormat()) { case "int32": - value = Integer.parseInt(stringData); - break; + return Integer.parseInt(stringData); case "int8": - value = Byte.parseByte(stringData); - break; + return Byte.parseByte(stringData); case "int16": - value = Short.parseShort(stringData); - break; + return Short.parseShort(stringData); case "int64": - value = Long.parseLong(stringData); - break; + return Long.parseLong(stringData); default: - throw new RuntimeException("Unknown format for integer " + intFormat); - } - - } else if (type.contentEquals("number")) { - final String numFormat = ts.getFormat(); - if (numFormat.contentEquals("float")) { - value = Float.parseFloat(stringData); - } else { - value = Double.parseDouble(stringData); - } - } else if (type.contentEquals("boolean")) { - value = Boolean.parseBoolean(stringData); - } else if (type.contentEquals("object")) { - value = createComponentInstance(format, stringData, ts); - } else if (type.contentEquals("array")) { - final JSONArray jsonArray = new JSONArray(stringData); - final TypeSchema itemSchema = ts.getItems(); - - // note here that the type has to be converted in the case of primitives - final Object[] data = (Object[]) Array.newInstance(mapPrimitive(itemSchema.getTypeClass(this.typeRegistry)), jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - final Object convertedData = convert(jsonArray.get(i).toString(), itemSchema); - data[i] = convertedData; - } - value = data; + throw new IllegalArgumentException("Unknown format for integer " + ts.getFormat()); + } + } + private Object convertString(final String stringData, final TypeSchema ts) { + if ("uint16".equals(ts.getFormat())) { + return stringData.charAt(0); } - return value; + + return stringData; } /** * Create new instance of the specificied object from the supplied JSON String. * - * @param format Details of the format needed + * @param format Details of the format needed * @param jsonString JSON string - * @param ts TypeSchema + * @param ts TypeSchema * @return new object */ + @SuppressWarnings("PMD.AvoidAccessibilityAlteration") Object createComponentInstance(final String format, final String jsonString, final TypeSchema ts) { final DataTypeDefinition dtd = this.typeRegistry.getDataType(format); Object obj; try { obj = dtd.getTypeClass().getDeclaredConstructor().newInstance(); - } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e1) { + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException e1) { throw new ContractRuntimeException("Unable to to create new instance of type", e1); } @@ -302,20 +324,20 @@ Object createComponentInstance(final String format, final String jsonString, fin ts.validate(json); try { final Map fields = dtd.getProperties(); - for (final Iterator iterator = fields.values().iterator(); iterator.hasNext();) { - final PropertyDefinition prop = iterator.next(); - + for (final PropertyDefinition prop : fields.values()) { final Field f = prop.getField(); f.setAccessible(true); final Object newValue = convert(json.get(prop.getName()).toString(), prop.getSchema()); f.set(obj, newValue); - } return obj; - } catch (SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException | JSONException e) { + } catch (SecurityException + | IllegalArgumentException + | IllegalAccessException + | InstantiationException + | JSONException e) { throw new ContractRuntimeException("Unable to convert JSON to object", e); } - } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/SerializerInterface.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/SerializerInterface.java index ed5cc5840..f52d87d0c 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/SerializerInterface.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/SerializerInterface.java @@ -9,15 +9,13 @@ import org.hyperledger.fabric.contract.metadata.TypeSchema; /** - * This interface allows contract developers to change the serialization - * mechanism. There are two scenarios where instances of DataTypes are - * serialized. + * This interface allows contract developers to change the serialization mechanism. There are two scenarios where + * instances of DataTypes are serialized. * - * When the objects are (logically) transferred from the Client application to - * the Contract resulting in a transaction function being invoked. Typically this - * is JSON, hence a default JSON parser is provided. + *

When the objects are (logically) transferred from the Client application to the Contract resulting in a + * transaction function being invoked. Typically this is JSON, hence a default JSON parser is provided. * - * The JSONTransactionSerializer can be extended if needed + *

The JSONTransactionSerializer can be extended if needed */ public interface SerializerInterface { @@ -34,10 +32,8 @@ public interface SerializerInterface { * Take the byte buffer and return the object as required. * * @param buffer Byte buffer from the wire - * @param ts TypeSchema representing the type - * + * @param ts TypeSchema representing the type * @return Object created; relies on Java auto-boxing for primitives */ Object fromBuffer(byte[] buffer, TypeSchema ts); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractExecutionService.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractExecutionService.java index e96111078..509f60d90 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractExecutionService.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractExecutionService.java @@ -6,7 +6,11 @@ package org.hyperledger.fabric.contract.execution.impl; - import org.hyperledger.fabric.contract.Context; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; +import org.hyperledger.fabric.contract.Context; import org.hyperledger.fabric.contract.ContractInterface; import org.hyperledger.fabric.contract.ContractRuntimeException; import org.hyperledger.fabric.contract.annotation.Serializer; @@ -22,30 +26,22 @@ import org.hyperledger.fabric.shim.ChaincodeStub; import org.hyperledger.fabric.shim.ResponseUtils; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - public class ContractExecutionService implements ExecutionService { - private static Logger logger = Logger.getLogger(ContractExecutionService.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ContractExecutionService.class.getName()); private final SerializerRegistryImpl serializers; - /** - * @param serializers - */ + /** @param serializers */ public ContractExecutionService(final SerializerRegistryImpl serializers) { this.serializers = serializers; } - /** - * - */ + /** */ @Override - public Chaincode.Response executeRequest(final TxFunction txFn, final InvocationRequest req, final ChaincodeStub stub) { - logger.fine(() -> "Routing Request" + txFn); + public Chaincode.Response executeRequest( + final TxFunction txFn, final InvocationRequest req, final ChaincodeStub stub) { + LOGGER.fine(() -> "Routing Request" + txFn); final TxFunction.Routing rd = txFn.getRouting(); Chaincode.Response response; @@ -83,21 +79,22 @@ public Chaincode.Response executeRequest(final TxFunction txFn, final Invocation } private byte[] convertReturn(final Object obj, final TxFunction txFn) { - final SerializerInterface serializer = serializers.getSerializer( - txFn.getRouting().getSerializerName(), Serializer.TARGET.TRANSACTION); + final SerializerInterface serializer = + serializers.getSerializer(txFn.getRouting().getSerializerName(), Serializer.TARGET.TRANSACTION); final TypeSchema ts = txFn.getReturnSchema(); return serializer.toBuffer(obj, ts); } private List convertArgs(final List stubArgs, final TxFunction txFn) { - final SerializerInterface serializer = serializers.getSerializer( - txFn.getRouting().getSerializerName(), Serializer.TARGET.TRANSACTION); + final SerializerInterface serializer = + serializers.getSerializer(txFn.getRouting().getSerializerName(), Serializer.TARGET.TRANSACTION); final List schemaParams = txFn.getParamsList(); final List args = new ArrayList<>(stubArgs.size() + 1); // allow for context as the first argument for (int i = 0; i < schemaParams.size(); i++) { - args.add(i, serializer.fromBuffer(stubArgs.get(i), schemaParams.get(i).getSchema())); + args.add( + i, + serializer.fromBuffer(stubArgs.get(i), schemaParams.get(i).getSchema())); } return args; } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractInvocationRequest.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractInvocationRequest.java index a2b9d9e9b..7a3e0ff36 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractInvocationRequest.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/ContractInvocationRequest.java @@ -6,29 +6,36 @@ package org.hyperledger.fabric.contract.execution.impl; -import java.util.Collections; +import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.stream.Collectors; - +import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.contract.execution.InvocationRequest; import org.hyperledger.fabric.shim.ChaincodeStub; -public class ContractInvocationRequest implements InvocationRequest { - private String namespace; - private String method; - private List args = Collections.emptyList(); +public final class ContractInvocationRequest implements InvocationRequest { + @SuppressWarnings("PMD.ProperLogger") // PMD 7.7.0 gives a false positive here + private static final Log LOGGER = LogFactory.getLog(ContractInvocationRequest.class); + + private static final Pattern NS_REGEX = Pattern.compile(":"); - private static Log logger = LogFactory.getLog(ContractInvocationRequest.class); + private final String namespace; + private final String method; + private final List args; - /** - * @param context - */ + /** @param context */ + @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public ContractInvocationRequest(final ChaincodeStub context) { - final String func = context.getStringArgs().size() > 0 ? context.getStringArgs().get(0) : null; - final String[] funcParts = func.split(":"); - logger.debug(func); + List funcAndArgs = context.getArgs(); + if (funcAndArgs.isEmpty()) { + throw new IllegalArgumentException("Missing function name"); + } + + final String func = new String(funcAndArgs.get(0), StandardCharsets.UTF_8); + LOGGER.debug(func); + + final String[] funcParts = NS_REGEX.split(func); if (funcParts.length == 2) { namespace = funcParts[0]; method = funcParts[1]; @@ -37,48 +44,39 @@ public ContractInvocationRequest(final ChaincodeStub context) { method = funcParts[0]; } - args = context.getArgs().stream().skip(1).collect(Collectors.toList()); - logger.debug(namespace + " " + method + " " + args); + args = funcAndArgs.subList(1, funcAndArgs.size()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(namespace + " " + method + " " + args); + } } - /** - * - */ + /** */ @Override public String getNamespace() { return namespace; } - /** - * - */ + /** */ @Override public String getMethod() { return method; } - /** - * - */ + /** */ @Override public List getArgs() { return args; } - /** - * - */ + /** */ @Override public String getRequestName() { return namespace + ":" + method; } - /** - * - */ + /** */ @Override public String toString() { return namespace + ":" + method + " @" + Integer.toHexString(System.identityHashCode(this)); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/package-info.java index dd93d90a0..b708841fc 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/impl/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.execution.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/package-info.java index 2c9651ad0..4fa00279c 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/execution/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.execution; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/MetadataBuilder.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/MetadataBuilder.java index 6b1830db8..e444efa70 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/MetadataBuilder.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/MetadataBuilder.java @@ -8,6 +8,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.Serializable; +import java.io.UncheckedIOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; @@ -17,7 +18,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; - import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaClient; @@ -37,23 +37,30 @@ /** * Builder to assist in production of the metadata. - *

- * This class is used to build up the JSON structure to be returned as the - * metadata It is not a store of information, rather a set of functional data to - * process to and from metadata json to the internal data structure + * + *

This class is used to build up the JSON structure to be returned as the metadata It is not a store of information, + * rather a set of functional data to process to and from metadata json to the internal data structure */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class MetadataBuilder { - private static Logger logger = Logger.getLogger(MetadataBuilder.class); + private static final Logger LOGGER = Logger.getLogger(MetadataBuilder.class); - private MetadataBuilder() { + private static final int PADDING = 3; - } + // Metadata is composed of three primary sections + // each of which is stored in a map + private static Map> contractMap = new HashMap<>(); + private static Map overallInfoMap = new HashMap<>(); + private static Map componentMap = new HashMap<>(); - @SuppressWarnings("serial") - static class MetadataMap extends HashMap { + // The schema client used to load any other referenced schemas + private static SchemaClient schemaClient = new DefaultSchemaClient(); + + static final class MetadataMap extends HashMap { + private static final long serialVersionUID = 1L; V putIfNotNull(final K key, final V value) { - logger.info(key + " " + value); + LOGGER.info(() -> key + " " + value); if (value != null && !value.toString().isEmpty()) { return put(key, value); } else { @@ -62,14 +69,7 @@ V putIfNotNull(final K key, final V value) { } } - // Metadata is composed of three primary sections - // each of which is stored in a map - private static Map> contractMap = new HashMap<>(); - private static Map overallInfoMap = new HashMap(); - private static Map componentMap = new HashMap(); - - // The schema client used to load any other referenced schemas - private static SchemaClient schemaClient = new DefaultSchemaClient(); + private MetadataBuilder() {} /** * Validation method. @@ -77,32 +77,36 @@ V putIfNotNull(final K key, final V value) { * @throws ValidationException if the metadata is not valid */ public static void validate() { - logger.info("Running schema test validation"); + LOGGER.info("Running schema test validation"); final ClassLoader cl = MetadataBuilder.class.getClassLoader(); try (InputStream contractSchemaInputStream = cl.getResourceAsStream("contract-schema.json"); InputStream jsonSchemaInputStream = cl.getResourceAsStream("json-schema-draft-04-schema.json")) { final JSONObject rawContractSchema = new JSONObject(new JSONTokener(contractSchemaInputStream)); final JSONObject rawJsonSchema = new JSONObject(new JSONTokener(jsonSchemaInputStream)); - final SchemaLoader schemaLoader = SchemaLoader.builder().schemaClient(schemaClient).schemaJson(rawContractSchema) - .registerSchemaByURI(URI.create("http://json-schema.org/draft-04/schema"), rawJsonSchema).build(); + final SchemaLoader schemaLoader = SchemaLoader.builder() + .schemaClient(schemaClient) + .schemaJson(rawContractSchema) + .registerSchemaByURI(URI.create("http://json-schema.org/draft-04/schema"), rawJsonSchema) + .build(); final Schema schema = schemaLoader.load().build(); schema.validate(metadata()); } catch (final IOException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } catch (final ValidationException e) { - logger.error(e.getMessage()); - e.getCausingExceptions().stream().map(ValidationException::getMessage).forEach(logger::info); - logger.error(debugString()); + LOGGER.error(e::getMessage); + e.getCausingExceptions().stream() + .map(ValidationException::getMessage) + .forEach(LOGGER::info); + LOGGER.error(MetadataBuilder::debugString); throw e; } - } /** * Setup the metadata from the found contracts. * - * @param registry RoutingRegistry + * @param registry RoutingRegistry * @param typeRegistry TypeRegistry */ public static void initialize(final RoutingRegistry registry, final TypeRegistry typeRegistry) { @@ -115,9 +119,8 @@ public static void initialize(final RoutingRegistry registry, final TypeRegistry // need to validate that the metadata that has been created is really valid // it should be as it's been created by code, but this is a valuable double // check - logger.info("Validating schema created"); - MetadataBuilder.validate(); - + LOGGER.info("Validating schema created"); + validate(); } /** @@ -134,7 +137,7 @@ public static void addComponent(final DataTypeDefinition datatype) { component.put("additionalProperties", false); final Map propertiesMap = datatype.getProperties().entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, e -> (e.getValue().getSchema()))); + .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getSchema())); component.put("properties", propertiesMap); componentMap.put(datatype.getSimpleName(), component); @@ -146,7 +149,7 @@ public static void addComponent(final DataTypeDefinition datatype) { * @param contractDefinition Class of the object to use as a contract * @return the key that the contract class is referred to in the metadata */ - @SuppressWarnings("serial") + @SuppressWarnings("PMD.LooseCoupling") public static String addContract(final ContractDefinition contractDefinition) { final String key = contractDefinition.getName(); @@ -154,40 +157,34 @@ public static String addContract(final ContractDefinition contractDefinition) { final Contract annotation = contractDefinition.getAnnotation(); final Info info = annotation.info(); - final HashMap infoMap = new HashMap(); + final HashMap infoMap = new HashMap<>(); infoMap.put("title", info.title()); infoMap.put("description", info.description()); infoMap.put("termsOfService", info.termsOfService()); - infoMap.put("contact", new MetadataMap() { - { - putIfNotNull("email", info.contact().email()); - putIfNotNull("name", info.contact().name()); - putIfNotNull("url", info.contact().url()); - } - }); - infoMap.put("license", new MetadataMap() { - { - put("name", info.license().name()); - putIfNotNull("url", info.license().url()); - } - }); + + MetadataMap contact = new MetadataMap<>(); + contact.putIfNotNull("email", info.contact().email()); + contact.putIfNotNull("name", info.contact().name()); + contact.putIfNotNull("url", info.contact().url()); + infoMap.put("contact", contact); + + MetadataMap license = new MetadataMap<>(); + license.put("name", info.license().name()); + license.putIfNotNull("url", info.license().url()); + infoMap.put("license", license); + infoMap.put("version", info.version()); - final HashMap contract = new HashMap(); + final HashMap contract = new HashMap<>(); contract.put("name", key); - contract.put("transactions", new ArrayList()); + contract.put("transactions", new ArrayList<>()); contract.put("info", infoMap); contractMap.put(key, contract); - final boolean defaultContract = true; - if (defaultContract) { - overallInfoMap.putAll(infoMap); - } + overallInfoMap.putAll(infoMap); final Collection fns = contractDefinition.getTxFunctions(); - fns.forEach(txFn -> { - MetadataBuilder.addTransaction(txFn, key); - }); + fns.forEach(txFn -> addTransaction(txFn, key)); return key; } @@ -195,7 +192,7 @@ public static String addContract(final ContractDefinition contractDefinition) { /** * Adds a new transaction function to the metadata for the given contract. * - * @param txFunction Object representing the transaction function + * @param txFunction Object representing the transaction function * @param contractName Name of the contract that this function belongs to */ public static void addTransaction(final TxFunction txFunction, final String contractName) { @@ -205,7 +202,7 @@ public static void addTransaction(final TxFunction txFunction, final String cont transaction.put("returns", returnSchema); } - final ArrayList tags = new ArrayList(); + final List tags = new ArrayList<>(); tags.add(txFunction.getType()); if (txFunction.getType() == TransactionType.SUBMIT) { // add deprecated tags tags.add(TransactionType.INVOKE); @@ -217,7 +214,7 @@ public static void addTransaction(final TxFunction txFunction, final String cont @SuppressWarnings("unchecked") final List txs = (ArrayList) contract.get("transactions"); - final ArrayList paramsList = new ArrayList(); + final List paramsList = new ArrayList<>(); txFunction.getParamsList().forEach(pd -> { final TypeSchema paramMap = pd.getSchema(); paramMap.put("name", pd.getName()); @@ -226,7 +223,7 @@ public static void addTransaction(final TxFunction txFunction, final String cont transaction.put("parameters", paramsList); - if (tags.size() != 0) { + if (!tags.isEmpty()) { transaction.put("tags", tags.toArray()); transaction.put("name", txFunction.getName()); txs.add(transaction); @@ -242,8 +239,6 @@ public static String getMetadata() { return metadata().toString(); } - private static final int PADDING = 3; - /** * Returns the metadata as a JSON string (spaced out for humans). * @@ -259,21 +254,17 @@ public static String debugString() { * @return JSONObject of the metadata */ private static JSONObject metadata() { - final HashMap metadata = new HashMap(); + final Map metadata = new HashMap<>(); metadata.put("$schema", "https://fabric-shim.github.io/release-1.4/contract-schema.json"); metadata.put("info", overallInfoMap); metadata.put("contracts", contractMap); metadata.put("components", Collections.singletonMap("schemas", componentMap)); - final JSONObject joMetadata = new JSONObject(metadata); - return joMetadata; + return new JSONObject(metadata); } - /** - * - * @return All the components indexed by name - */ + /** @return All the components indexed by name */ public static Map getComponents() { return componentMap; } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/TypeSchema.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/TypeSchema.java index 213fb83d4..8b11eccd9 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/TypeSchema.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/TypeSchema.java @@ -9,7 +9,7 @@ import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; - +import java.util.Optional; import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; @@ -19,24 +19,22 @@ import org.json.JSONObject; /** - * * TypeSchema. * - * Custom sub-type of Map that helps with the case where if there's no value - * then do not insert the property at all + *

Custom sub-type of Map that helps with the case where if there's no value then do not insert the property at all * - * Does not include the "schema" top level map + *

Does not include the "schema" top level map */ -@SuppressWarnings("serial") +@SuppressWarnings({"PMD.LooseCoupling", "PMD.GodClass"}) public final class TypeSchema extends HashMap { - private static Logger logger = Logger.getLogger(TypeSchema.class.getName()); - - /** - * - */ - public TypeSchema() { + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = Logger.getLogger(TypeSchema.class.getName()); - } + private static final String SCHEMA_PROP = "schema"; + private static final String TYPE_PROP = "type"; + private static final String ITEMS_PROP = "items"; + private static final String FORMAT_PROP = "format"; + private static final String INTEGER_TYPE = "integer"; private Object putInternal(final String key, final Object value) { if (value != null && !value.toString().isEmpty()) { @@ -62,120 +60,112 @@ TypeSchema[] putIfNotNull(final String key, final TypeSchema[] value) { return (TypeSchema[]) this.putInternal(key, value); } - /** - * - * @return Return Type String - */ + /** @return Return Type String */ public String getType() { - if (this.containsKey("schema")) { - final Map intermediateMap = (Map) this.get("schema"); - return (String) intermediateMap.get("type"); + if (this.containsKey(SCHEMA_PROP)) { + final Map intermediateMap = (Map) this.get(SCHEMA_PROP); + return (String) intermediateMap.get(TYPE_PROP); } - return (String) this.get("type"); + return (String) this.get(TYPE_PROP); } - /** - * - * @return TypeSchema items - */ + /** @return TypeSchema items */ public TypeSchema getItems() { - if (this.containsKey("schema")) { - final Map intermediateMap = (Map) this.get("schema"); - return (TypeSchema) intermediateMap.get("items"); + if (this.containsKey(SCHEMA_PROP)) { + final Map intermediateMap = (Map) this.get(SCHEMA_PROP); + return (TypeSchema) intermediateMap.get(ITEMS_PROP); } - return (TypeSchema) this.get("items"); + return (TypeSchema) this.get(ITEMS_PROP); } - /** - * - * @return Reference - */ + /** @return Reference */ public String getRef() { - if (this.containsKey("schema")) { - final Map intermediateMap = (Map) this.get("schema"); + if (this.containsKey(SCHEMA_PROP)) { + final Map intermediateMap = (Map) this.get(SCHEMA_PROP); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); - } - /** - * - * @return Format - */ + /** @return Format */ public String getFormat() { - if (this.containsKey("schema")) { - final Map intermediateMap = (Map) this.get("schema"); - return (String) intermediateMap.get("format"); + if (this.containsKey(SCHEMA_PROP)) { + final Map intermediateMap = (Map) this.get(SCHEMA_PROP); + return (String) intermediateMap.get(FORMAT_PROP); } - return (String) this.get("format"); + return (String) this.get(FORMAT_PROP); } /** - * * @param typeRegistry * @return Class object */ public Class getTypeClass(final TypeRegistry typeRegistry) { - Class clz = null; - String type = getType(); - if (type == null) { - type = "object"; + String type = Optional.ofNullable(getType()).orElse("object"); + + switch (type) { + case "object": + return getObjectClass(typeRegistry); + case "string": + return getStringClass(); + case INTEGER_TYPE: + return getIntegerClass(); + case "number": + return getNumberClass(); + case "boolean": + return boolean.class; + case "array": + return getArrayClass(typeRegistry); + default: + return null; } + } - if (type.contentEquals("string")) { - final String format = getFormat(); - if (format != null && format.contentEquals("uint16")) { - clz = char.class; - } else { - clz = String.class; - } + private Class getArrayClass(final TypeRegistry typeRegistry) { + final TypeSchema typdef = this.getItems(); + final Class arrayType = typdef.getTypeClass(typeRegistry); + return Array.newInstance(arrayType, 0).getClass(); + } + + private Class getNumberClass() { + switch (getFormat()) { + case "double": + return double.class; + case "float": + return float.class; + default: + throw new IllegalArgumentException("Unknown format for number of " + getFormat()); + } + } - } else if (type.contentEquals("integer")) { - // need to check the format - final String format = getFormat(); - switch (format) { + private Class getIntegerClass() { + // need to check the format + switch (getFormat()) { case "int8": - clz = byte.class; - break; + return byte.class; case "int16": - clz = short.class; - break; + return short.class; case "int32": - clz = int.class; - break; + return int.class; case "int64": - clz = long.class; - break; + return long.class; default: - throw new RuntimeException("Unknown format for integer of " + format); - } - } else if (type.contentEquals("number")) { - // need to check the format - final String format = getFormat(); - switch (format) { - case "double": - clz = double.class; - break; - case "float": - clz = float.class; - break; - default: - throw new RuntimeException("Unknown format for number of " + format); - } - } else if (type.contentEquals("boolean")) { - clz = boolean.class; - } else if (type.contentEquals("object")) { - final String ref = this.getRef(); - final String format = ref.substring(ref.lastIndexOf("/") + 1); - clz = typeRegistry.getDataType(format).getTypeClass(); - } else if (type.contentEquals("array")) { - final TypeSchema typdef = this.getItems(); - final Class arrayType = typdef.getTypeClass(typeRegistry); - clz = Array.newInstance(arrayType, 0).getClass(); + throw new IllegalArgumentException("Unknown format for integer of " + getFormat()); + } + } + + @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") + private Class getStringClass() { + if ("uint16".equals(getFormat())) { + return char.class; } + return String.class; + } - return clz; + private Class getObjectClass(final TypeRegistry typeRegistry) { + final String ref = this.getRef(); + final String format = ref.substring(ref.lastIndexOf('/') + 1); + return typeRegistry.getDataType(format).getTypeClass(); } /** @@ -183,91 +173,94 @@ public Class getTypeClass(final TypeRegistry typeRegistry) { * * @param clz * @return TypeSchema - * */ + @SuppressWarnings({"PMD.ReturnEmptyCollectionRatherThanNull", "PMD.AvoidLiteralsInIfCondition"}) public static TypeSchema typeConvert(final Class clz) { - final TypeSchema returnschema = new TypeSchema(); String className = clz.getTypeName(); - if (className == "void") { + + if ("void".equals(className)) { return null; } - TypeSchema schema; + final TypeSchema result = new TypeSchema(); + TypeSchema schema = result; if (clz.isArray()) { - returnschema.put("type", "array"); + result.put(TYPE_PROP, "array"); + schema = new TypeSchema(); + final Class componentClass = clz.getComponentType(); + className = componentClass.getTypeName(); // double check the componentType - final Class componentClass = clz.getComponentType(); if (componentClass.isArray()) { // nested arrays - returnschema.put("items", TypeSchema.typeConvert(componentClass)); + result.put(ITEMS_PROP, typeConvert(componentClass)); } else { - returnschema.put("items", schema); + result.put(ITEMS_PROP, schema); } - - className = componentClass.getTypeName(); - } else { - schema = returnschema; } - switch (className) { - case "java.lang.String": - schema.put("type", "string"); - break; - case "char": - case "java.lang.Character": - schema.put("type", "string"); - schema.put("format", "uint16"); - break; - case "byte": - case "java.lang.Byte": - schema.put("type", "integer"); - schema.put("format", "int8"); - break; - case "short": - case "java.lang.Short": - schema.put("type", "integer"); - schema.put("format", "int16"); - break; - case "int": - case "java.lang.Integer": - schema.put("type", "integer"); - schema.put("format", "int32"); - break; - case "long": - case "java.lang.Long": - schema.put("type", "integer"); - schema.put("format", "int64"); - break; - case "double": - case "java.lang.Double": - schema.put("type", "number"); - schema.put("format", "double"); - break; - case "float": - case "java.lang.Float": - schema.put("type", "number"); - schema.put("format", "float"); - break; - case "boolean": - case "java.lang.Boolean": - schema.put("type", "boolean"); - break; - default: - schema.put("$ref", "#/components/schemas/" + className.substring(className.lastIndexOf('.') + 1)); - } + updateSchemaForClass(schema, className); - return returnschema; + return result; } + @SuppressWarnings("PMD.CyclomaticComplexity") + private static void updateSchemaForClass(final TypeSchema schema, final String className) { + switch (className) { + case "java.lang.String": + schema.put(TYPE_PROP, "string"); + return; + case "char": + case "java.lang.Character": + schema.put(TYPE_PROP, "string"); + schema.put(FORMAT_PROP, "uint16"); + return; + case "byte": + case "java.lang.Byte": + schema.put(TYPE_PROP, INTEGER_TYPE); + schema.put(FORMAT_PROP, "int8"); + return; + case "short": + case "java.lang.Short": + schema.put(TYPE_PROP, INTEGER_TYPE); + schema.put(FORMAT_PROP, "int16"); + return; + case "int": + case "java.lang.Integer": + schema.put(TYPE_PROP, INTEGER_TYPE); + schema.put(FORMAT_PROP, "int32"); + return; + case "long": + case "java.lang.Long": + schema.put(TYPE_PROP, INTEGER_TYPE); + schema.put(FORMAT_PROP, "int64"); + return; + case "double": + case "java.lang.Double": + schema.put(TYPE_PROP, "number"); + schema.put(FORMAT_PROP, "double"); + return; + case "float": + case "java.lang.Float": + schema.put(TYPE_PROP, "number"); + schema.put(FORMAT_PROP, "float"); + return; + case "boolean": + case "java.lang.Boolean": + schema.put(TYPE_PROP, "boolean"); + return; + default: + schema.put("$ref", "#/components/schemas/" + className.substring(className.lastIndexOf('.') + 1)); + } + } - /** - * Validates the object against this schema. - * - * @param obj - */ + /** + * Validates the object against this schema. + * + * @param obj + */ public void validate(final JSONObject obj) { // get the components bit of the main metadata @@ -275,8 +268,8 @@ public void validate(final JSONObject obj) { toValidate.put("prop", obj); JSONObject schemaJSON; - if (this.containsKey("schema")) { - schemaJSON = new JSONObject((Map) this.get("schema")); + if (this.containsKey(SCHEMA_PROP)) { + schemaJSON = new JSONObject((Map) this.get(SCHEMA_PROP)); } else { schemaJSON = new JSONObject(this); } @@ -289,11 +282,12 @@ public void validate(final JSONObject obj) { schema.validate(toValidate); } catch (final ValidationException e) { final StringBuilder sb = new StringBuilder("Validation Errors::"); - e.getCausingExceptions().stream().map(ValidationException::getMessage).forEach(sb::append); - logger.info(sb.toString()); - throw new ContractRuntimeException(sb.toString(), e); + e.getCausingExceptions().stream() + .map(ValidationException::getMessage) + .forEach(sb::append); + String message = sb.toString(); + LOGGER.info(message); + throw new ContractRuntimeException(message, e); } - } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/package-info.java index 743c7b047..d02326ece 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/metadata/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.metadata; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/package-info.java index 5185aedb3..24dbf8be1 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/package-info.java @@ -7,15 +7,10 @@ /** * Provides interfaces and classes to support the contract programming model. * - *

- * The {@link org.hyperledger.fabric.contract} package implements the Fabric - * programming model as described in the Developing + *

The {@link org.hyperledger.fabric.contract} package implements the Fabric programming model as described in the Developing * Applications chapter of the Fabric documentation. * - *

- * The main interface to implement is - * {@link org.hyperledger.fabric.contract.ContractInterface} - * + *

The main interface to implement is {@link org.hyperledger.fabric.contract.ContractInterface} */ package org.hyperledger.fabric.contract; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ContractDefinition.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ContractDefinition.java index ba8072cb1..4bca0f44d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ContractDefinition.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ContractDefinition.java @@ -8,77 +8,56 @@ import java.lang.reflect.Method; import java.util.Collection; - import org.hyperledger.fabric.contract.ContractInterface; import org.hyperledger.fabric.contract.annotation.Contract; /** * Definition of the Contract * - * A data structure that represents the contract that will be executed in the - * chaincode. Primarily has + *

A data structure that represents the contract that will be executed in the chaincode. Primarily has * - * Name - either defined by the Contract annotation or the Class name (can be - * referred to as Namespace) Default - is the default contract (defined by the - * Default annotation) TxFunctions in this contract do not need the name prefix + *

Name - either defined by the Contract annotation or the Class name (can be referred to as Namespace) Default - is + * the default contract (defined by the Default annotation) TxFunctions in this contract do not need the name prefix * when invoked TxFunctions - the transaction functions defined in this contract * - * Will embedded the ContractInterface instance, as well as the annotation - * itself, and the routing for any tx function that is unknown - * + *

Will embedded the ContractInterface instance, as well as the annotation itself, and the routing for any tx + * function that is unknown */ public interface ContractDefinition { - /** - * @return the fully qualified name of the Contract - */ + /** @return the fully qualified name of the Contract */ String getName(); - /** - * @return Complete collection of all the transaction functions in this contract - */ + /** @return Complete collection of all the transaction functions in this contract */ Collection getTxFunctions(); - /** - * @return Object reference to the instantiated object that is 'the contract' - */ + /** @return Object reference to the instantiated object that is 'the contract' */ Class getContractImpl(); /** - * @param m The java.lang.reflect object that is the method that is a tx - * function + * @param m The java.lang.reflect object that is the method that is a tx function * @return TxFunction object representing this method */ TxFunction addTxFunction(Method m); - /** - * - * @return if this is contract is the default one or not - */ + /** @return if this is contract is the default one or not */ boolean isDefault(); /** - * * @param method name to be returned * @return TxFunction that represents this requested method */ TxFunction getTxFunction(String method); /** - * * @param method name to be checked * @return true if this txFunction exists or not */ boolean hasTxFunction(String method); - /** - * @return The TxFunction to be used for this contract in case of unknown - * request - */ + /** @return The TxFunction to be used for this contract in case of unknown request */ TxFunction getUnknownRoute(); - /** - * @return Underlying raw annotation - */ + /** @return Underlying raw annotation */ Contract getAnnotation(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/DataTypeDefinition.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/DataTypeDefinition.java index 3267a718c..84d2e3fbf 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/DataTypeDefinition.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/DataTypeDefinition.java @@ -6,33 +6,22 @@ package org.hyperledger.fabric.contract.routing; import java.util.Map; - import org.hyperledger.fabric.contract.metadata.TypeSchema; public interface DataTypeDefinition { - /** - * @return String - */ + /** @return String */ String getName(); - /** - * @return Map of String to PropertyDefinitions - */ + /** @return Map of String to PropertyDefinitions */ Map getProperties(); - /** - * @return String - */ + /** @return String */ String getSimpleName(); - /** - * @return Class object of the type - */ + /** @return Class object of the type */ Class getTypeClass(); - /** - * @return TypeSchema - */ + /** @return TypeSchema */ TypeSchema getSchema(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ParameterDefinition.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ParameterDefinition.java index bc81c234c..2411e6aad 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ParameterDefinition.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/ParameterDefinition.java @@ -6,29 +6,19 @@ package org.hyperledger.fabric.contract.routing; import java.lang.reflect.Parameter; - import org.hyperledger.fabric.contract.metadata.TypeSchema; public interface ParameterDefinition { - /** - * @return Class type of the parameter - */ + /** @return Class type of the parameter */ Class getTypeClass(); - /** - * @return TypeSchema of the parameter - */ + /** @return TypeSchema of the parameter */ TypeSchema getSchema(); - /** - * @return Parameter - */ + /** @return Parameter */ Parameter getParameter(); - /** - * @return name of the parameter - */ + /** @return name of the parameter */ String getName(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/PropertyDefinition.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/PropertyDefinition.java index dd4e7e372..4c53cdc79 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/PropertyDefinition.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/PropertyDefinition.java @@ -6,29 +6,19 @@ package org.hyperledger.fabric.contract.routing; import java.lang.reflect.Field; - import org.hyperledger.fabric.contract.metadata.TypeSchema; public interface PropertyDefinition { - /** - * @return Class of the Property - */ + /** @return Class of the Property */ Class getTypeClass(); - /** - * @return TypeSchema - */ + /** @return TypeSchema */ TypeSchema getSchema(); - /** - * @return Field - */ + /** @return Field */ Field getField(); - /** - * @return Name of the property - */ + /** @return Name of the property */ String getName(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/RoutingRegistry.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/RoutingRegistry.java index 3c4e9825e..264ff9b21 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/RoutingRegistry.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/RoutingRegistry.java @@ -6,7 +6,6 @@ package org.hyperledger.fabric.contract.routing; import java.util.Collection; - import org.hyperledger.fabric.contract.ContractInterface; import org.hyperledger.fabric.contract.execution.InvocationRequest; @@ -65,5 +64,4 @@ public interface RoutingRegistry { * @param typeRegistry */ void findAndSetContracts(TypeRegistry typeRegistry); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TransactionType.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TransactionType.java index 80472df52..37e307b7d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TransactionType.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TransactionType.java @@ -6,24 +6,14 @@ package org.hyperledger.fabric.contract.routing; public enum TransactionType { - /** - * - */ - INVOKE, //deprecated - /** - * - */ - QUERY, //deprecated - /** - * - */ - DEFAULT, //deprecated - /** - * - */ + /** */ + INVOKE, // deprecated + /** */ + QUERY, // deprecated + /** */ + DEFAULT, // deprecated + /** */ SUBMIT, - /** - * - */ + /** */ EVALUATE } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TxFunction.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TxFunction.java index 860e22783..392419fae 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TxFunction.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TxFunction.java @@ -8,7 +8,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; - import org.hyperledger.fabric.contract.ContractInterface; import org.hyperledger.fabric.contract.metadata.TypeSchema; @@ -17,86 +16,68 @@ public interface TxFunction { interface Routing { /** * Method to route calls to the transaction function. + * * @return a method. */ Method getMethod(); /** * The associated contract class. + * * @return a contract class. */ Class getContractClass(); /** * The associated contract instance. + * * @return a contract. * @throws IllegalAccessException * @throws InstantiationException * @throws InvocationTargetException * @throws NoSuchMethodException */ - ContractInterface getContractInstance() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException; + ContractInterface getContractInstance() + throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException; /** * Name of the serializer used for the transaction function. + * * @return a serializer name. */ String getSerializerName(); } - /** - * @return is this tx to be called when request fn is unknown - */ + /** @return is this tx to be called when request fn is unknown */ boolean isUnknownTx(); - /** - * @param unknown true if the transaction is to be called when the request fn is unknown; otherwise false. - */ + /** @param unknown true if the transaction is to be called when the request fn is unknown; otherwise false. */ void setUnknownTx(boolean unknown); - /** - * @return Name - */ + /** @return Name */ String getName(); - /** - * @return Routing object - */ + /** @return Routing object */ Routing getRouting(); - /** - * @return Class of the return type - */ + /** @return Class of the return type */ Class getReturnType(); - /** - * @return Parameter array - */ + /** @return Parameter array */ java.lang.reflect.Parameter[] getParameters(); - /** - * @return Submit or Evaluate - */ + /** @return Submit or Evaluate */ TransactionType getType(); - /** - * @param returnSchema - */ + /** @param returnSchema */ void setReturnSchema(TypeSchema returnSchema); - /** - * @return TypeSchema of the return type - */ + /** @return TypeSchema of the return type */ TypeSchema getReturnSchema(); - /** - * @param list - */ + /** @param list */ void setParameterDefinitions(List list); - /** - * @return List of parameters - */ + /** @return List of parameters */ List getParamsList(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TypeRegistry.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TypeRegistry.java index 732719561..4b61e2d41 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TypeRegistry.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/TypeRegistry.java @@ -6,27 +6,20 @@ package org.hyperledger.fabric.contract.routing; import java.util.Collection; - import org.hyperledger.fabric.contract.metadata.TypeSchema; import org.hyperledger.fabric.contract.routing.impl.TypeRegistryImpl; public interface TypeRegistry { - /** - * @return TypeRegistry - */ + /** @return TypeRegistry */ static TypeRegistry getRegistry() { return TypeRegistryImpl.getInstance(); } - /** - * @param dtd - */ + /** @param dtd */ void addDataType(DataTypeDefinition dtd); - /** - * @param cl - */ + /** @param cl */ void addDataType(Class cl); /** @@ -41,9 +34,6 @@ static TypeRegistry getRegistry() { */ DataTypeDefinition getDataType(TypeSchema schema); - /** - * @return All datatypes - */ + /** @return All datatypes */ Collection getAllDataTypes(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ContractDefinitionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ContractDefinitionImpl.java index 09a293fcb..8df5f3ab9 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ContractDefinitionImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ContractDefinitionImpl.java @@ -9,7 +9,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; - import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.Context; import org.hyperledger.fabric.contract.ContractInterface; @@ -22,28 +21,23 @@ /** * Implementation of the ContractDefinition. * - * Contains information about the contract, including transaction functions and - * unknown transaction routing - * + *

Contains information about the contract, including transaction functions and unknown transaction routing */ public final class ContractDefinitionImpl implements ContractDefinition { - private static Logger logger = Logger.getLogger(ContractDefinitionImpl.class); + private static final Logger LOGGER = Logger.getLogger(ContractDefinitionImpl.class); private final Map txFunctions = new HashMap<>(); - private String name; + private final String name; private final boolean isDefault; private final Class contractClz; private final Contract contractAnnotation; - private TxFunction unknownTx; + private final TxFunction unknownTx; - /** - * - * @param cl - */ + /** @param cl */ public ContractDefinitionImpl(final Class cl) { final Contract annotation = cl.getAnnotation(Contract.class); - logger.debug(() -> "Class Contract Annotation: " + annotation); + LOGGER.debug(() -> "Class Contract Annotation: " + annotation); final String annotationName = annotation.name(); @@ -58,17 +52,18 @@ public ContractDefinitionImpl(final Class cl) { contractClz = cl; try { - final Method m = cl.getMethod("unknownTransaction", new Class[] {Context.class}); + final Method m = cl.getMethod("unknownTransaction", Context.class); unknownTx = new TxFunctionImpl(m, this); unknownTx.setUnknownTx(true); } catch (NoSuchMethodException | SecurityException e) { - final ContractRuntimeException cre = new ContractRuntimeException("Failure to find unknownTransaction method", e); - logger.severe(() -> logger.formatError(cre)); + final ContractRuntimeException cre = + new ContractRuntimeException("Failure to find unknownTransaction method", e); + LOGGER.severe(() -> LOGGER.formatError(cre)); throw cre; } - logger.info(() -> "Found class: " + cl.getCanonicalName()); - logger.debug(() -> "Namespace: " + this.name); + LOGGER.info(() -> "Found class: " + cl.getCanonicalName()); + LOGGER.debug(() -> "Namespace: " + this.name); } @Override @@ -88,13 +83,13 @@ public Class getContractImpl() { @Override public TxFunction addTxFunction(final Method m) { - logger.debug(() -> "Adding method " + m.getName()); + LOGGER.debug(() -> "Adding method " + m.getName()); final TxFunction txFn = new TxFunctionImpl(m, this); final TxFunction previousTxnFn = txFunctions.put(txFn.getName(), txFn); if (previousTxnFn != null) { final String message = String.format("Duplicate transaction method %s", previousTxnFn.getName()); final ContractRuntimeException cre = new ContractRuntimeException(message); - logger.severe(() -> logger.formatError(cre)); + LOGGER.severe(() -> LOGGER.formatError(cre)); throw cre; } return txFn; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/DataTypeDefinitionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/DataTypeDefinitionImpl.java index 78c2b9a12..8d1ed8679 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/DataTypeDefinitionImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/DataTypeDefinitionImpl.java @@ -7,9 +7,9 @@ import java.lang.reflect.Field; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.stream.Stream; - import org.hyperledger.fabric.contract.annotation.Property; import org.hyperledger.fabric.contract.metadata.TypeSchema; import org.hyperledger.fabric.contract.routing.DataTypeDefinition; @@ -22,10 +22,8 @@ public final class DataTypeDefinitionImpl implements DataTypeDefinition { private final String simpleName; private final Class clazz; - /** - * - * @param componentClass - */ + /** @param componentClass */ + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public DataTypeDefinitionImpl(final Class componentClass) { this.clazz = componentClass; this.name = componentClass.getName(); @@ -43,21 +41,23 @@ public DataTypeDefinitionImpl(final Class componentClass) { for (int i = 0; i < userSupplied.length; i += 2) { final String userKey = userSupplied[i]; Object userValue; - switch (userKey.toLowerCase()) { - case "title": - case "pattern": - userValue = userSupplied[i + 1]; - break; - case "uniqueitems": - userValue = Boolean.parseBoolean(userSupplied[i + 1]); - break; - case "required": - case "enum": - userValue = Stream.of(userSupplied[i + 1].split(",")).map(String::trim).toArray(String[]::new); - break; - default: - userValue = Integer.parseInt(userSupplied[i + 1]); - break; + switch (userKey.toLowerCase(Locale.getDefault())) { + case "title": + case "pattern": + userValue = userSupplied[i + 1]; + break; + case "uniqueitems": + userValue = Boolean.parseBoolean(userSupplied[i + 1]); + break; + case "required": + case "enum": + userValue = Stream.of(userSupplied[i + 1].split(",")) + .map(String::trim) + .toArray(String[]::new); + break; + default: + userValue = Integer.parseInt(userSupplied[i + 1]); + break; } ts.put(userKey, userValue); } @@ -66,7 +66,6 @@ public DataTypeDefinitionImpl(final Class componentClass) { this.properties.put(f.getName(), propDef); } } - } @Override @@ -115,5 +114,4 @@ public String getSimpleName() { public String toString() { return this.simpleName + " " + properties; } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ParameterDefinitionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ParameterDefinitionImpl.java index a99765cab..7fa8f6e6a 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ParameterDefinitionImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/ParameterDefinitionImpl.java @@ -7,7 +7,6 @@ package org.hyperledger.fabric.contract.routing.impl; import java.lang.reflect.Parameter; - import org.hyperledger.fabric.contract.metadata.TypeSchema; import org.hyperledger.fabric.contract.routing.ParameterDefinition; @@ -19,13 +18,13 @@ public final class ParameterDefinitionImpl implements ParameterDefinition { private final String name; /** - * * @param name * @param typeClass * @param schema * @param p */ - public ParameterDefinitionImpl(final String name, final Class typeClass, final TypeSchema schema, final Parameter p) { + public ParameterDefinitionImpl( + final String name, final Class typeClass, final TypeSchema schema, final Parameter p) { this.typeClass = typeClass; this.schema = schema; this.parameter = p; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/PropertyDefinitionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/PropertyDefinitionImpl.java index 5ea837054..f7772d046 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/PropertyDefinitionImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/PropertyDefinitionImpl.java @@ -7,7 +7,6 @@ package org.hyperledger.fabric.contract.routing.impl; import java.lang.reflect.Field; - import org.hyperledger.fabric.contract.metadata.TypeSchema; import org.hyperledger.fabric.contract.routing.PropertyDefinition; @@ -19,7 +18,6 @@ public final class PropertyDefinitionImpl implements PropertyDefinition { private final String name; /** - * * @param name * @param typeClass * @param schema @@ -51,5 +49,4 @@ public Field getField() { public String getName() { return this.name; } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/RoutingRegistryImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/RoutingRegistryImpl.java index 084b32802..49180d385 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/RoutingRegistryImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/RoutingRegistryImpl.java @@ -5,6 +5,9 @@ */ package org.hyperledger.fabric.contract.routing.impl; +import io.github.classgraph.ClassGraph; +import io.github.classgraph.ClassInfo; +import io.github.classgraph.ScanResult; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; @@ -13,7 +16,6 @@ import java.util.List; import java.util.Map; import java.util.Set; - import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.ContractInterface; import org.hyperledger.fabric.contract.ContractRuntimeException; @@ -26,18 +28,12 @@ import org.hyperledger.fabric.contract.routing.TxFunction; import org.hyperledger.fabric.contract.routing.TypeRegistry; -import io.github.classgraph.ClassGraph; -import io.github.classgraph.ClassInfo; -import io.github.classgraph.ScanResult; - /** - * Registry to hold permit access to the routing definitions. This is the - * primary internal data structure to permit access to information about the - * contracts, and their transaction functions. - * - * Contracts are added, and processed. At runtime, this can then be accessed to - * locate a specific 'Route' that can be handed off to the ExecutionService + * Registry to hold permit access to the routing definitions. This is the primary internal data structure to permit + * access to information about the contracts, and their transaction functions. * + *

Contracts are added, and processed. At runtime, this can then be accessed to locate a specific 'Route' that can be + * handed off to the ExecutionService */ public final class RoutingRegistryImpl implements RoutingRegistry { private static Logger logger = Logger.getLogger(RoutingRegistryImpl.class); @@ -100,8 +96,7 @@ public TxFunction.Routing getRoute(final InvocationRequest request) { @Override public TxFunction getTxFn(final InvocationRequest request) { - final TxFunction txFunction = contracts.get(request.getNamespace()).getTxFunction(request.getMethod()); - return txFunction; + return contracts.get(request.getNamespace()).getTxFunction(request.getMethod()); } /* @@ -131,7 +126,6 @@ public ContractDefinition getContract(final String namespace) { @Override public Collection getAllDefinitions() { return contracts.values(); - } /* @@ -145,14 +139,12 @@ public Collection getAllDefinitions() { public void findAndSetContracts(final TypeRegistry typeRegistry) { // Find all classes that are valid contract or data type instances. - final ClassGraph classGraph = new ClassGraph() - .enableClassInfo() - .enableAnnotationInfo(); + final ClassGraph classGraph = new ClassGraph().enableClassInfo().enableAnnotationInfo(); final List> contractClasses = new ArrayList<>(); final List> dataTypeClasses = new ArrayList<>(); try (ScanResult scanResult = classGraph.scan()) { for (final ClassInfo classInfo : scanResult.getClassesWithAnnotation(Contract.class.getCanonicalName())) { - logger.debug("Found class with contract annotation: " + classInfo.getName()); + logger.debug(() -> "Found class with contract annotation: " + classInfo.getName()); try { final Class contractClass = classInfo.loadClass(); logger.debug("Loaded class"); @@ -162,18 +154,18 @@ public void findAndSetContracts(final TypeRegistry typeRegistry) { // compatible, // and not some random class with the same name. logger.debug("Class does not have compatible contract annotation"); - } else if (!ContractInterface.class.isAssignableFrom(contractClass)) { - logger.debug("Class is not assignable from ContractInterface"); - } else { + } else if (ContractInterface.class.isAssignableFrom(contractClass)) { logger.debug("Class is assignable from ContractInterface"); contractClasses.add((Class) contractClass); + } else { + logger.debug("Class is not assignable from ContractInterface"); } } catch (final IllegalArgumentException e) { - logger.debug("Failed to load class: " + e); + logger.debug(() -> "Failed to load class: " + e); } } for (final ClassInfo classInfo : scanResult.getClassesWithAnnotation(DataType.class.getCanonicalName())) { - logger.debug("Found class with data type annotation: " + classInfo.getName()); + logger.debug(() -> "Found class with data type annotation: " + classInfo.getName()); try { final Class dataTypeClass = classInfo.loadClass(); logger.debug("Loaded class"); @@ -188,7 +180,7 @@ public void findAndSetContracts(final TypeRegistry typeRegistry) { dataTypeClasses.add(dataTypeClass); } } catch (final IllegalArgumentException e) { - logger.debug("Failed to load class: " + e); + logger.debug(() -> "Failed to load class: " + e); } } } @@ -198,7 +190,6 @@ public void findAndSetContracts(final TypeRegistry typeRegistry) { // now need to look for the data types have been set with the dataTypeClasses.forEach(typeRegistry::addDataType); - } private void addContracts(final List> contractClasses) { @@ -214,10 +205,9 @@ private void addContracts(final List> contractClasses) logger.debug("Searching annotated methods"); for (final Method m : contractClass.getMethods()) { if (m.getAnnotation(Transaction.class) != null) { - logger.debug("Found annotated method " + m.getName()); + logger.debug(() -> "Found annotated method " + m.getName()); contract.addTxFunction(m); - } } @@ -225,5 +215,4 @@ private void addContracts(final List> contractClasses) } } } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/SerializerRegistryImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/SerializerRegistryImpl.java index 74b9a0b84..728966f09 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/SerializerRegistryImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/SerializerRegistryImpl.java @@ -5,43 +5,34 @@ */ package org.hyperledger.fabric.contract.routing.impl; +import io.github.classgraph.ClassGraph; +import io.github.classgraph.ClassInfo; +import io.github.classgraph.ScanResult; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.annotation.Serializer; import org.hyperledger.fabric.contract.execution.SerializerInterface; -import io.github.classgraph.ClassGraph; -import io.github.classgraph.ClassInfo; -import io.github.classgraph.ScanResult; - /** * Registry to hold permit access to the serializer implementations. * - * It holds the serializers that have been defined. JSONTransactionSerializer - * is the default. + *

It holds the serializers that have been defined. JSONTransactionSerializer is the default. */ public class SerializerRegistryImpl { - private static Logger logger = Logger.getLogger(SerializerRegistryImpl.class); + private static final Logger LOGGER = Logger.getLogger(SerializerRegistryImpl.class); private final Class annotationClass = Serializer.class; - /** - * - */ - public SerializerRegistryImpl() { - } - // Could index these by name and or type. private final Map contents = new HashMap<>(); /** * Get a Serializer for the matching fully qualified classname, and the Target. * - * @param name fully qualified classname + * @param name fully qualified classname * @param target the intended target of the serializer * @return Serializer instance */ @@ -50,17 +41,15 @@ public SerializerInterface getSerializer(final String name, final Serializer.TAR return contents.get(key); } - private SerializerInterface add(final String name, final Serializer.TARGET target, final Class clazz) { - logger.debug(() -> "Adding new Class " + clazz.getCanonicalName() + " for " + target); - try { - final String key = name + ":" + target; - final SerializerInterface newObj = clazz.newInstance(); - this.contents.put(key, newObj); + private SerializerInterface add( + final String name, final Serializer.TARGET target, final Class clazz) + throws InstantiationException, IllegalAccessException { + LOGGER.debug(() -> "Adding new Class " + clazz.getCanonicalName() + " for " + target); + final String key = name + ":" + target; + final SerializerInterface newObj = clazz.newInstance(); + this.contents.put(key, newObj); - return newObj; - } catch (InstantiationException | IllegalAccessException e) { - throw new RuntimeException(e); - } + return newObj; } /** @@ -78,25 +67,18 @@ public void findAndSetContents() throws InstantiationException, IllegalAccessExc final Set seenClass = new HashSet<>(); try (ScanResult scanResult = classGraph.scan()) { - for (final ClassInfo classInfo : scanResult.getClassesWithAnnotation(this.annotationClass.getCanonicalName())) { - logger.debug("Found class with contract annotation: " + classInfo.getName()); - try { - final Class cls = (Class) classInfo.loadClass(); - logger.debug("Loaded class"); - - final String className = cls.getCanonicalName(); - if (!seenClass.contains(className)) { - seenClass.add(className); - this.add(className, Serializer.TARGET.TRANSACTION, cls); - } - - } catch (final IllegalArgumentException e) { - logger.debug("Failed to load class: " + e); + for (final ClassInfo classInfo : + scanResult.getClassesWithAnnotation(this.annotationClass.getCanonicalName())) { + LOGGER.debug(() -> "Found class with contract annotation: " + classInfo.getName()); + final Class cls = (Class) classInfo.loadClass(); + LOGGER.debug("Loaded class"); + + final String className = cls.getCanonicalName(); + if (!seenClass.contains(className)) { + seenClass.add(className); + this.add(className, Serializer.TARGET.TRANSACTION, cls); } } - } - } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TxFunctionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TxFunctionImpl.java index b12726d23..26f336f53 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TxFunctionImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TxFunctionImpl.java @@ -7,10 +7,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; +import java.lang.reflect.Parameter; import java.util.Arrays; import java.util.List; - +import java.util.stream.Collectors; import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.Context; import org.hyperledger.fabric.contract.ContractInterface; @@ -24,25 +24,23 @@ import org.hyperledger.fabric.contract.routing.TxFunction; public final class TxFunctionImpl implements TxFunction { - private static Logger logger = Logger.getLogger(TxFunctionImpl.class); + private static final Logger LOGGER = Logger.getLogger(TxFunctionImpl.class); private final Method method; private String name; private TransactionType type; - private TransactionType typeDeprecated; private final Routing routing; private TypeSchema returnSchema; - private List paramsList = new ArrayList<>(); + private List paramsList; private boolean isUnknownTx; - public final class RoutingImpl implements Routing { + public static final class RoutingImpl implements Routing { private final Method method; private final Class clazz; private final String serializerName; /** - * * @param method * @param contract */ @@ -63,7 +61,9 @@ public Class getContractClass() { } @Override - public ContractInterface getContractInstance() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { + public ContractInterface getContractInstance() + throws IllegalAccessException, InstantiationException, InvocationTargetException, + NoSuchMethodException { return clazz.getDeclaredConstructor().newInstance(); } @@ -76,20 +76,19 @@ public String toString() { public String getSerializerName() { return serializerName; } - } /** * New TxFunction Definition Impl. * - * @param m Reflect method object + * @param m Reflect method object * @param contract ContractDefinition this is part of */ public TxFunctionImpl(final Method m, final ContractDefinition contract) { this.method = m; if (m.getAnnotation(Transaction.class) != null) { - logger.debug("Found Transaction method: " + m.getName()); + LOGGER.debug(() -> "Found Transaction method: " + m.getName()); if (m.getAnnotation(Transaction.class).intent() == Transaction.TYPE.SUBMIT) { this.type = TransactionType.SUBMIT; } else { @@ -114,18 +113,18 @@ public TxFunctionImpl(final Method m, final ContractDefinition contract) { this.returnSchema = TypeSchema.typeConvert(m.getReturnType()); // parameter processing - final List params = new ArrayList( - Arrays.asList(method.getParameters())); + this.paramsList = buildParameters(m); + } + private List buildParameters(final Method m) { + Parameter[] params = m.getParameters(); // validate the first one is a context object - if (params.size() == 0) { + if (params.length == 0) { throw new ContractRuntimeException("First argument should be of type Context"); - } else if (!Context.class.isAssignableFrom(params.get(0).getType())) { + } + if (!Context.class.isAssignableFrom(params[0].getType())) { throw new ContractRuntimeException( - "First argument should be of type Context " + method.getName() + " " + params.get(0).getType()); - } else { - - params.remove(0); + "First argument should be of type Context " + m.getName() + " " + params[0].getType()); } // FUTURE: if ever the method of creating the instance where to change, @@ -133,24 +132,27 @@ public TxFunctionImpl(final Method m, final ContractDefinition contract) { // here encapsulating the change. eg use an annotation to define where the // context goes - for (final java.lang.reflect.Parameter parameter : params) { - final TypeSchema paramMap = new TypeSchema(); - final TypeSchema schema = TypeSchema.typeConvert(parameter.getType()); + return Arrays.stream(params) + .skip(1) + .map(TxFunctionImpl::newParameterDefinition) + .collect(Collectors.toList()); + } - final Property annotation = parameter.getAnnotation(org.hyperledger.fabric.contract.annotation.Property.class); - if (annotation != null) { - final String[] userSupplied = annotation.schema(); - for (int i = 0; i < userSupplied.length; i += 2) { - schema.put(userSupplied[i], userSupplied[i + 1]); - } - } + private static ParameterDefinitionImpl newParameterDefinition(final Parameter parameter) { + final TypeSchema paramMap = new TypeSchema(); + final TypeSchema schema = TypeSchema.typeConvert(parameter.getType()); - paramMap.put("name", parameter.getName()); - paramMap.put("schema", schema); - final ParameterDefinition pd = new ParameterDefinitionImpl(parameter.getName(), parameter.getClass(), paramMap, - parameter); - paramsList.add(pd); + final Property annotation = parameter.getAnnotation(Property.class); + if (annotation != null) { + final String[] userSupplied = annotation.schema(); + for (int i = 0; i < userSupplied.length; i += 2) { + schema.put(userSupplied[i], userSupplied[i + 1]); + } } + + paramMap.put("name", parameter.getName()); + paramMap.put("schema", schema); + return new ParameterDefinitionImpl(parameter.getName(), parameter.getClass(), paramMap, parameter); } @Override @@ -169,7 +171,7 @@ public Class getReturnType() { } @Override - public java.lang.reflect.Parameter[] getParameters() { + public Parameter[] getParameters() { return method.getParameters(); } @@ -193,11 +195,8 @@ public List getParamsList() { return paramsList; } - /** - * - * @param paramsList - */ - public void setParamsList(final ArrayList paramsList) { + /** @param paramsList */ + public void setParamsList(final List paramsList) { this.paramsList = paramsList; } @@ -209,7 +208,6 @@ public TypeSchema getReturnSchema() { @Override public void setParameterDefinitions(final List list) { this.paramsList = list; - } @Override @@ -221,5 +219,4 @@ public boolean isUnknownTx() { public void setUnknownTx(final boolean unknown) { this.isUnknownTx = unknown; } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TypeRegistryImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TypeRegistryImpl.java index dc50d3dc9..54d2e9958 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TypeRegistryImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/TypeRegistryImpl.java @@ -8,18 +8,15 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; - import org.hyperledger.fabric.contract.metadata.TypeSchema; import org.hyperledger.fabric.contract.routing.DataTypeDefinition; import org.hyperledger.fabric.contract.routing.TypeRegistry; -/** - * Registry to hold the complex data types as defined in the contract. - * - */ +/** Registry to hold the complex data types as defined in the contract. */ public final class TypeRegistryImpl implements TypeRegistry { + private static final TypeRegistryImpl INSTANCE = new TypeRegistryImpl(); - private static TypeRegistryImpl singletonInstance; + private final Map components = new HashMap<>(); /** * Get the TypeRegistry singleton instance. @@ -27,15 +24,9 @@ public final class TypeRegistryImpl implements TypeRegistry { * @return TypeRegistry */ public static TypeRegistry getInstance() { - if (singletonInstance == null) { - singletonInstance = new TypeRegistryImpl(); - } - - return singletonInstance; + return INSTANCE; } - private final Map components = new HashMap<>(); - /* * (non-Javadoc) * @@ -72,8 +63,7 @@ public DataTypeDefinition getDataType(final String name) { @Override public DataTypeDefinition getDataType(final TypeSchema schema) { final String ref = schema.getRef(); - final String format = ref.substring(ref.lastIndexOf("/") + 1); + final String format = ref.substring(ref.lastIndexOf('/') + 1); return getDataType(format); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/package-info.java index 108f8132d..e3d4b1ea8 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/impl/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.routing.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/package-info.java index 32533b45b..4ab5847bb 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/routing/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.routing; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/SystemContract.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/SystemContract.java index f2427e226..762efe664 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/SystemContract.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/SystemContract.java @@ -12,29 +12,21 @@ import org.hyperledger.fabric.contract.annotation.Transaction; import org.hyperledger.fabric.contract.metadata.MetadataBuilder; -/** - * - */ -@Contract(name = "org.hyperledger.fabric", - info = @Info(title = "Fabric System Contract", description = "Provides information about the contracts within this container")) +/** */ +@Contract( + name = "org.hyperledger.fabric", + info = + @Info( + title = "Fabric System Contract", + description = "Provides information about the contracts within this container")) public final class SystemContract implements ContractInterface { /** - * - */ - public SystemContract() { - - } - - /** - * * @param ctx * @return Metadata */ - @Transaction(submit = false, name = "GetMetadata") + @Transaction(intent = Transaction.TYPE.EVALUATE, name = "GetMetadata") public String getMetadata(final Context ctx) { - final String jsonmetadata = MetadataBuilder.getMetadata(); - return jsonmetadata; + return MetadataBuilder.getMetadata(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/package-info.java index 5dcfe058a..cde12bb03 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/contract/systemcontract/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.contract.systemcontract; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Collection.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Collection.java index 195eb5f80..1f109da8d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Collection.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Collection.java @@ -8,14 +8,12 @@ /** Place holder. */ public interface Collection { - /** - * Constant that can be used to refer to the 'Worldstate' collection explicitly. - */ + /** Constant that can be used to refer to the 'Worldstate' collection explicitly. */ String WORLD = "worldstate"; /** - * Placeholder. Purely in place to prevent Checkstyle inferring this class is pointless. - * will be removed in the next story + * Placeholder. Purely in place to prevent Checkstyle inferring this class is pointless. will be removed in the next + * story */ void placeholder(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Ledger.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Ledger.java index ce3479711..1d97ec717 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Ledger.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/Ledger.java @@ -11,40 +11,35 @@ /** * Ledger representing the overall shared Transaction Data of the Network. * - * It is composed of a number of collections, one being the public or world - * state, and other private data collections, including the implicit - * organizational collections. - * - * Ledger objects can be passed between methods if required. All operations on - * the Ledger directly or via any child object such as a Collection will be - * controlled by the supplied transactional context. + *

It is composed of a number of collections, one being the public or world state, and other private data + * collections, including the implicit organizational collections. * + *

Ledger objects can be passed between methods if required. All operations on the Ledger directly or via any child + * object such as a Collection will be controlled by the supplied transactional context. */ public interface Ledger { /** * Get the Ledger instance that represents the current ledger state. * - * Any interactions with the ledger will be done under the control of the - * transactional context supplied. The ledger object may be passed to other - * methods if required. + *

Any interactions with the ledger will be done under the control of the transactional context supplied. The + * ledger object may be passed to other methods if required. * - * A new instance is returned on each call. + *

A new instance is returned on each call. * - * @param ctx Context The Transactional context to use for interactions with - * this ledger + * @param ctx Context The Transactional context to use for interactions with this ledger * @return Ledger instance */ static Ledger getLedger(final Context ctx) { return new LedgerImpl(ctx); - }; + } /** * Return the a collection based on the supplied name. * - * Private Data collections can be accessed by name. + *

Private Data collections can be accessed by name. * - * A new instance of a Collection object is returned on each call. + *

A new instance of a Collection object is returned on each call. * * @param name * @return Collection instance @@ -54,7 +49,7 @@ static Ledger getLedger(final Context ctx) { /** * Return the World State collection. * - * A new instance of a Collection object is returned on each call. + *

A new instance of a Collection object is returned on each call. * * @return Collection instance */ @@ -63,14 +58,12 @@ static Ledger getLedger(final Context ctx) { /** * Return a implicit organization collection. * - * Given the mspid of the ogranization return the private data collection that - * is implicitly created + *

Given the mspid of the ogranization return the private data collection that is implicitly created * - * A new instance of a Collection object is returned on each call. + *

A new instance of a Collection object is returned on each call. * * @param mspid String Organization's mspid * @return Collection instance */ Collection getOrganizationCollection(String mspid); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/CollectionImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/CollectionImpl.java deleted file mode 100644 index faea7f491..000000000 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/CollectionImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2020 IBM All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.hyperledger.fabric.ledger.impl; - -import org.hyperledger.fabric.ledger.Collection; - -/** - * Placeholder. - */ -public class CollectionImpl implements Collection { - - private final String name; - - /** - * - * - * @param name - * @param ledgerImpl - */ - public CollectionImpl(final String name, final LedgerImpl ledgerImpl) { - this.name = name; - } - - @Override - public void placeholder() { - // TODO Auto-generated method stub - - } - -} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/LedgerImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/LedgerImpl.java index 1087cd24f..5d204ba20 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/LedgerImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/LedgerImpl.java @@ -8,26 +8,27 @@ import org.hyperledger.fabric.contract.Context; import org.hyperledger.fabric.ledger.Collection; import org.hyperledger.fabric.ledger.Ledger; -import org.hyperledger.fabric.shim.ChaincodeStub; public final class LedgerImpl implements Ledger { - // The Chaincode Stub or SPI to provide access to the underlying Fabric - // APIs - private final ChaincodeStub stub; - /** * New Ledger Implementation. * * @param ctx Context transactional context to use */ + @SuppressWarnings("PMD.UnusedFormalParameter") public LedgerImpl(final Context ctx) { - this.stub = ctx.getStub(); + // Empty stub } @Override public Collection getCollection(final String name) { - return new CollectionImpl(name, this); + return new Collection() { + @Override + public void placeholder() { + // Empty stub + } + }; } @Override @@ -39,5 +40,4 @@ public Collection getDefaultCollection() { public Collection getOrganizationCollection(final String mspid) { return this.getCollection("_implicit_org_" + mspid); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/package-info.java index 96b288ea9..025bb854b 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/impl/package-info.java @@ -1,6 +1,6 @@ -/* - * Copyright 2023 IBM All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.hyperledger.fabric.ledger.impl; +/* + * Copyright 2023 IBM All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.fabric.ledger.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/package-info.java index ca6cfec78..129a4271c 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/ledger/package-info.java @@ -4,9 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - *

- * Provides the API for contracts to access the shared ledger. - * - */ +/** Provides the API for contracts to access the shared ledger. */ package org.hyperledger.fabric.ledger; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/Metrics.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/Metrics.java index 56bcdab67..b13e3708b 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/Metrics.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/Metrics.java @@ -5,19 +5,16 @@ */ package org.hyperledger.fabric.metrics; -import java.lang.reflect.InvocationTargetException; import java.util.Properties; import java.util.logging.Logger; - import org.hyperledger.fabric.metrics.impl.DefaultProvider; import org.hyperledger.fabric.metrics.impl.NullProvider; /** * Metrics Interface. * - * Metrics setups up the provider in use from the configuration supplied If not - * enabled, nothing happens, but if enabled but no specific logger default is - * used that uses the org.hyperledger.Performance logger + *

Metrics setups up the provider in use from the configuration supplied If not enabled, nothing happens, but if + * enabled but no specific logger default is used that uses the org.hyperledger.Performance logger */ public final class Metrics { @@ -28,16 +25,13 @@ public final class Metrics { private static MetricsProvider provider; - - private Metrics() { - - } + private Metrics() {} /** - * * @param props * @return The metrics provide */ + @SuppressWarnings("PMD.AvoidCatchingGenericException") public static MetricsProvider initialize(final Properties props) { if (Boolean.parseBoolean((String) props.get(CHAINCODE_METRICS_ENABLED))) { try { @@ -46,37 +40,30 @@ public static MetricsProvider initialize(final Properties props) { final String providerClass = (String) props.get(CHAINCODE_METRICS_PROVIDER); @SuppressWarnings("unchecked") // it must be this type otherwise an error - final - Class clazz = (Class) Class.forName(providerClass); + final Class clazz = (Class) Class.forName(providerClass); provider = clazz.getConstructor().newInstance(); } else { logger.info("Using default metrics provider (logs to org.hyperledger.Performance)"); provider = new DefaultProvider(); } - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e) { - throw new RuntimeException("Unable to start metrics", e); + } catch (Exception e) { + throw new IllegalStateException("Unable to start metrics", e); } } else { // return a 'null' provider logger.info("Metrics disabled"); provider = new NullProvider(); - } provider.initialize(props); return provider; } - /** - * - * @return MetricsProvider - */ + /** @return MetricsProvider */ public static MetricsProvider getProvider() { if (provider == null) { throw new IllegalStateException("No provider set, this should have been set"); } return provider; } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java index 482fbbdf4..aa726b964 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java @@ -9,20 +9,16 @@ import java.util.Properties; /** - * Interface to be implemented to send metrics on the chaincode to the - * 'backend-of-choice'. + * Interface to be implemented to send metrics on the chaincode to the 'backend-of-choice'. * - * An instance of this will be created, and provided with the resources from - * which chaincode specific metrics can be collected. (via the no-argument - * constructor). + *

An instance of this will be created, and provided with the resources from which chaincode specific metrics can be + * collected. (via the no-argument constructor). * - * The choice of when, where and what to collect etc are within the remit of the - * provider. + *

The choice of when, where and what to collect etc are within the remit of the provider. * - * This is the effective call sequence. + *

This is the effective call sequence. * - * MyMetricsProvider mmp = new MyMetricsProvider() - * mmp.initialize(props_from_environment); // short while later.... + *

MyMetricsProvider mmp = new MyMetricsProvider() mmp.initialize(props_from_environment); // short while later.... * mmp.setTaskMetricsCollector(taskService); */ public interface MetricsProvider { @@ -33,16 +29,16 @@ public interface MetricsProvider { * @param props */ default void initialize(final Properties props) { - }; + // Do nothing by default + } /** - * Pass a reference to this task service for information gathering. This is - * related specifically to the handling of tasks within the chaincode. i.e. how - * individual transactions are dispatched for execution. + * Pass a reference to this task service for information gathering. This is related specifically to the handling of + * tasks within the chaincode. i.e. how individual transactions are dispatched for execution. * * @param taskService */ default void setTaskMetricsCollector(final TaskMetricsCollector taskService) { - }; - + // Do nothing by default + } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java index bb2c6065b..ef59d6a44 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java @@ -8,11 +8,9 @@ /** * Collect metrics relating to the task execution. * - * The task execution (of which each fabric transaction is one) is backed by a - * thread pool that implements this interface. As that is an implementation - * class this interface abstracts the information available from it (as far as + *

The task execution (of which each fabric transaction is one) is backed by a thread pool that implements this + * interface. As that is an implementation class this interface abstracts the information available from it (as far as * metrics go). - * */ public interface TaskMetricsCollector { diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java index a2dc8a785..3f34028d3 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java @@ -9,26 +9,20 @@ import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; - import org.hyperledger.fabric.Logging; import org.hyperledger.fabric.metrics.MetricsProvider; import org.hyperledger.fabric.metrics.TaskMetricsCollector; -/** - * Simple default provider that logs to the org.hyperledger.Performance logger - * the basic metrics. - * - */ +/** Simple default provider that logs to the org.hyperledger.Performance logger the basic metrics. */ public final class DefaultProvider implements MetricsProvider { - private static Logger perflogger = Logger.getLogger(Logging.PERFLOGGER); + private static final Logger PERFLOGGER = Logger.getLogger(Logging.PERFLOGGER); + private static final int TIME_INTERVAL = 5000; private TaskMetricsCollector taskService; - /** - * - */ + /** */ public DefaultProvider() { - perflogger.info("Default Metrics Provider started"); + PERFLOGGER.info("Default Metrics Provider started"); } @Override @@ -36,36 +30,36 @@ public void setTaskMetricsCollector(final TaskMetricsCollector taskService) { this.taskService = taskService; } - private static final int TIME_INTERVAL = 5000; - @Override public void initialize(final Properties props) { final Timer metricTimer = new Timer(true); - metricTimer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - DefaultProvider.this.logMetrics(); - } - }, 0, TIME_INTERVAL); - + metricTimer.scheduleAtFixedRate( + new TimerTask() { + @Override + public void run() { + DefaultProvider.this.logMetrics(); + } + }, + 0, + TIME_INTERVAL); } - protected void logMetrics() { - - perflogger.info(() -> { - if (DefaultProvider.this.taskService == null) { + void logMetrics() { + PERFLOGGER.info(() -> { + if (taskService == null) { return "No Metrics Provider service yet"; } - final StringBuilder sb = new StringBuilder(); - sb.append('{'); - sb.append(String.format(" \"active_count\":%d ", DefaultProvider.this.taskService.getActiveCount())).append(','); - sb.append(String.format(" \"pool_size\":%d ", DefaultProvider.this.taskService.getPoolSize())).append(','); - sb.append(String.format(" \"core_pool_size\":%d ", DefaultProvider.this.taskService.getCorePoolSize())).append(','); - sb.append(String.format(" \"current_task_count\":%d ", DefaultProvider.this.taskService.getCurrentTaskCount())).append(','); - sb.append(String.format(" \"current_queue_depth\":%d ", DefaultProvider.this.taskService.getCurrentQueueCount())); - return sb.append('}').toString(); + return '{' + + String.format(" \"active_count\":%d ", taskService.getActiveCount()) + + ',' + + String.format(" \"pool_size\":%d ", taskService.getPoolSize()) + + ',' + + String.format(" \"core_pool_size\":%d ", taskService.getCorePoolSize()) + + ',' + + String.format(" \"current_task_count\":%d ", taskService.getCurrentTaskCount()) + + ',' + + String.format(" \"current_queue_depth\":%d ", taskService.getCurrentQueueCount()) + + '}'; }); - } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java index f977ac67f..35be1fa61 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java @@ -7,17 +7,5 @@ import org.hyperledger.fabric.metrics.MetricsProvider; -/** - * Very simple provider that does absolutely nothing. Used when metrics are - * disabled. - * - */ -public class NullProvider implements MetricsProvider { - - /** - * - */ - public NullProvider() { - } - -} +/** Very simple provider that does absolutely nothing. Used when metrics are disabled. */ +public class NullProvider implements MetricsProvider {} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java index 301529657..59afe468e 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.metrics.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java index ec9d196aa..f9cf1f7b3 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java @@ -7,24 +7,17 @@ /** * Provides interfaces and classes to support collection of metrics. * - *

- * The main metrics that are available are the statistics around the number of - * tasks that are running, and how the thread pool is handling these. + *

The main metrics that are available are the statistics around the number of tasks that are running, and how the + * thread pool is handling these. * - *

- * Note a 'task' is a message from the Peer to the Chaincode - this message is - * either a new transaction, or a response from a stub API, eg getState(). Query - * apis may return more than one response. + *

Note a 'task' is a message from the Peer to the Chaincode - this message is either a new transaction, or a + * response from a stub API, eg getState(). Query apis may return more than one response. * - *

- * To enable metrics, add a CHAINCODE_METRICS_ENABLED=true setting - * to the config.props chaincode configuration file. - * See the Overview for details of how to - * configure chaincode. + *

To enable metrics, add a CHAINCODE_METRICS_ENABLED=true setting to the config.props + * chaincode configuration file. See the Overview for details of how to configure + * chaincode. * - *

Open Telemetry

- * - * To use Open Telemetry, set the following properties: + *

Open Telemetry To use Open Telemetry, set the following properties: * *

  * CHAINCODE_METRICS_ENABLED=true
@@ -34,7 +27,8 @@
  * Additionally, you can set properties after the specification:
  * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md
  *
- * Example:
+ * 

Example: + * *

  * OTEL_EXPORTER_OTLP_ENDPOINT=otelcollector:4317
  * OTEL_EXPORTER_OTLP_INSECURE=true
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
index cb5d58f60..dfeb5e026 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
@@ -4,7 +4,5 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-/**
- * Provides logging classes.
- */
+/** Provides logging classes. */
 package org.hyperledger.fabric;
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
index 046595df3..ca576534d 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
@@ -11,13 +11,11 @@
 import java.util.HashMap;
 import java.util.Map;
 
-/**
- * Defines methods that all chaincodes must implement.
- */
+/** Defines methods that all chaincodes must implement. */
 public interface Chaincode {
     /**
-     * Called during an instantiate transaction after the container has been
-     * established, allowing the chaincode to initialize its internal data.
+     * Called during an instantiate transaction after the container has been established, allowing the chaincode to
+     * initialize its internal data.
      *
      * @param stub the chaincode stub
      * @return the chaincode response
@@ -25,8 +23,7 @@ public interface Chaincode {
     Response init(ChaincodeStub stub);
 
     /**
-     * Called for every Invoke transaction. The chaincode may change its state
-     * variables.
+     * Called for every Invoke transaction. The chaincode may change its state variables.
      *
      * @param stub the chaincode stub
      * @return the chaincode response
@@ -34,9 +31,8 @@ public interface Chaincode {
     Response invoke(ChaincodeStub stub);
 
     /**
-     * Wrapper around protobuf Response, contains status, message and payload.
-     * Object returned by call to {@link #init(ChaincodeStub)}
-     * and{@link #invoke(ChaincodeStub)}
+     * Wrapper around protobuf Response, contains status, message and payload. Object returned by call to
+     * {@link #init(ChaincodeStub)} and{@link #invoke(ChaincodeStub)}
      */
     class Response {
         private final int statusCode;
@@ -45,10 +41,12 @@ class Response {
 
         /**
          * Constructor.
+         *
          * @param status a status object.
          * @param message a response message.
          * @param payload a response payload.
          */
+        @SuppressWarnings("PMD.ArrayIsStoredDirectly")
         public Response(final Status status, final String message, final byte[] payload) {
             this.statusCode = status.getCode();
             this.message = message;
@@ -57,10 +55,12 @@ public Response(final Status status, final String message, final byte[] payload)
 
         /**
          * Constructor.
+         *
          * @param statusCode a status code.
          * @param message a response message.
          * @param payload a response payload.
          */
+        @SuppressWarnings("PMD.ArrayIsStoredDirectly")
         public Response(final int statusCode, final String message, final byte[] payload) {
             this.statusCode = statusCode;
             this.message = message;
@@ -69,6 +69,7 @@ public Response(final int statusCode, final String message, final byte[] payload
 
         /**
          * Get the response status.
+         *
          * @return status.
          */
         public Status getStatus() {
@@ -81,6 +82,7 @@ public Status getStatus() {
 
         /**
          * Get the response status code.
+         *
          * @return status code.
          */
         public int getStatusCode() {
@@ -89,6 +91,7 @@ public int getStatusCode() {
 
         /**
          * Get the response message.
+         *
          * @return a message.
          */
         public String getMessage() {
@@ -97,35 +100,30 @@ public String getMessage() {
 
         /**
          * Get the response payload.
+         *
          * @return payload bytes.
          */
+        @SuppressWarnings("PMD.MethodReturnsInternalArray")
         public byte[] getPayload() {
             return payload;
         }
 
         /**
          * Get the response payload as a UTF-8 string.
+         *
          * @return a string.
          */
         public String getStringPayload() {
             return (payload == null) ? null : new String(payload, UTF_8);
         }
 
-        /**
-         * {@link Response} status enum.
-         */
+        /** {@link Response} status enum. */
         public enum Status {
-            /**
-             * Successful response status.
-             */
+            /** Successful response status. */
             SUCCESS(200),
-            /**
-             * Minimum threshold for as error status code.
-             */
+            /** Minimum threshold for as error status code. */
             ERROR_THRESHOLD(400),
-            /**
-             * Server-side error status.
-             */
+            /** Server-side error status. */
             INTERNAL_SERVER_ERROR(500);
 
             private static final Map CODETOSTATUS = new HashMap<>();
@@ -137,6 +135,7 @@ public enum Status {
 
             /**
              * Get the status code associated with this status object.
+             *
              * @return a status code.
              */
             public int getCode() {
@@ -145,6 +144,7 @@ public int getCode() {
 
             /**
              * Get a status object for a given status code.
+             *
              * @param code a status code.
              * @return a status object.
              */
@@ -158,6 +158,7 @@ public static Status forCode(final int code) {
 
             /**
              * Whether a status exists for a given status code.
+             *
              * @param code a status code.
              * @return True if a status for the code exists; otherwise false.
              */
@@ -166,12 +167,10 @@ public static boolean hasStatusForCode(final int code) {
             }
 
             static {
-                for (final Status status : Status.values()) {
+                for (final Status status : values()) {
                     CODETOSTATUS.put(status.code, status);
                 }
             }
-
         }
-
     }
 }
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
index da8da55e6..a90e6bdac 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
@@ -6,9 +6,16 @@
 
 package org.hyperledger.fabric.shim;
 
-import static java.lang.String.format;
 import static java.util.logging.Level.ALL;
 
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.util.JsonFormat;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
+import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
+import io.grpc.stub.StreamObserver;
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
@@ -21,15 +28,12 @@
 import java.nio.file.Paths;
 import java.security.Security;
 import java.util.Base64;
+import java.util.Locale;
 import java.util.Properties;
 import java.util.logging.Level;
 import java.util.logging.LogRecord;
 import java.util.logging.Logger;
 import java.util.logging.SimpleFormatter;
-
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protobuf.util.JsonFormat;
-
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -43,63 +47,39 @@
 import org.hyperledger.fabric.shim.impl.InvocationTaskManager;
 import org.hyperledger.fabric.traces.Traces;
 
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
-import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
-import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
-import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
-import io.grpc.stub.StreamObserver;
-
 /**
  * Abstract implementation of {@link Chaincode}.
  *
- * 

- * All chaincode implementations must extend the abstract class - * ChaincodeBase. It is possible to implement chaincode by - * extending ChaincodeBase directly however new projects should - * implement {@link org.hyperledger.fabric.contract.ContractInterface} and use - * the contract programming model instead. + *

All chaincode implementations must extend the abstract class ChaincodeBase. It is possible to + * implement chaincode by extending ChaincodeBase directly however new projects should implement + * {@link org.hyperledger.fabric.contract.ContractInterface} and use the contract programming model instead. * * @see org.hyperledger.fabric.contract */ +@SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.GodClass"}) public abstract class ChaincodeBase implements Chaincode { - /** - * - */ + /** */ public static final String CORE_CHAINCODE_LOGGING_SHIM = "CORE_CHAINCODE_LOGGING_SHIM"; - /** - * - */ + /** */ public static final String CORE_CHAINCODE_LOGGING_LEVEL = "CORE_CHAINCODE_LOGGING_LEVEL"; - @Override - public abstract Response init(ChaincodeStub stub); - - @Override - public abstract Response invoke(ChaincodeStub stub); - private static final Logger LOGGER = Logger.getLogger(ChaincodeBase.class.getName()); - /** - * - */ + /** */ + @SuppressWarnings("PMD.AvoidUsingHardCodedIP") public static final String DEFAULT_HOST = "127.0.0.1"; - /** - * - */ + /** */ public static final int DEFAULT_PORT = 7051; - /** - * Default to 100MB for maximum inbound grpc message size. - */ + /** Default to 100MB for maximum inbound grpc message size. */ public static final String DEFAULT_MAX_INBOUND_MESSAGE_SIZE = "104857600"; private String host = DEFAULT_HOST; private int port = DEFAULT_PORT; - private boolean tlsEnabled = false; + private boolean tlsEnabled; private String tlsClientKeyPath; private String tlsClientCertPath; private String tlsClientKeyFile; @@ -123,19 +103,26 @@ public abstract class ChaincodeBase implements Chaincode { private static final String MAX_INBOUND_MESSAGE_SIZE = "MAX_INBOUND_MESSAGE_SIZE"; private Properties props; private Level logLevel; + private CCState state = CCState.CREATED; static { Security.addProvider(new BouncyCastleProvider()); } + @Override + public abstract Response init(ChaincodeStub stub); + + @Override + public abstract Response invoke(ChaincodeStub stub); + private int getMaxInboundMessageSize() { if (this.props == null) { throw new IllegalStateException("Chaincode config not available"); } - final int maxMsgSize = Integer - .parseInt(this.props.getProperty(MAX_INBOUND_MESSAGE_SIZE, DEFAULT_MAX_INBOUND_MESSAGE_SIZE)); - final String msgSizeInfo = String.format("Maximum Inbound Message Size [%s] = %d", MAX_INBOUND_MESSAGE_SIZE, - maxMsgSize); + final int maxMsgSize = + Integer.parseInt(this.props.getProperty(MAX_INBOUND_MESSAGE_SIZE, DEFAULT_MAX_INBOUND_MESSAGE_SIZE)); + final String msgSizeInfo = + String.format("Maximum Inbound Message Size [%s] = %d", MAX_INBOUND_MESSAGE_SIZE, maxMsgSize); LOGGER.info(msgSizeInfo); return maxMsgSize; } @@ -145,7 +132,7 @@ private int getMaxInboundMessageSize() { * * @param args command line arguments */ - + @SuppressWarnings("PMD.AvoidCatchingGenericException") public void start(final String[] args) { try { initializeLogging(); @@ -173,7 +160,8 @@ protected final void connectToPeer() throws IOException { // This is then passed to the ChaincodeSupportClient to be connected to the // gRPC streams - final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(this.id).build(); + final ChaincodeID chaincodeId = + ChaincodeID.newBuilder().setName(this.id).build(); final ManagedChannelBuilder channelBuilder = newChannelBuilder(); final ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder); @@ -202,9 +190,9 @@ protected final void connectToPeer() throws IOException { // for any error - shut everything down // as this is long lived (well forever) then any completion means something // has stopped in the peer or the network comms, so also shutdown - final StreamObserver requestObserver = chaincodeSupportClient.getStub().register( - - new StreamObserver() { + final StreamObserver requestObserver = chaincodeSupportClient + .getStub() + .register(new StreamObserver<>() { @Override public void onNext(final ChaincodeMessage chaincodeMessage) { // message off to the ITM... @@ -225,24 +213,20 @@ public void onCompleted() { LOGGER.severe("Chaincode stream is complete. Shutting down the chaincode stream."); chaincodeSupportClient.shutdown(itm); } - } - - ); + }); chaincodeSupportClient.start(itm, requestObserver); - } /** * connect external chaincode to peer for chat. * * @param requestObserver reqeust from peer - * @return itm - The InnvocationTask Manager handles the message level - * communication with the peer. + * @return itm - The InnvocationTask Manager handles the message level communication with the peer. * @throws IOException validation fields exception */ - protected StreamObserver connectToPeer( - final StreamObserver requestObserver) throws IOException { + protected StreamObserver connectToPeer(final StreamObserver requestObserver) + throws IOException { validateOptions(); if (requestObserver == null) { throw new IOException("StreamObserver 'requestObserver' for chat with peer can't be null"); @@ -256,7 +240,8 @@ protected StreamObserver connectToPeer( // This is then passed to the ChaincodeSupportClient to be connected to the // gRPC streams - final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(this.id).build(); + final ChaincodeID chaincodeId = + ChaincodeID.newBuilder().setName(this.id).build(); final ManagedChannelBuilder channelBuilder = newChannelBuilder(); final ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder); @@ -264,7 +249,7 @@ protected StreamObserver connectToPeer( chaincodeSupportClient.start(itm, requestObserver); - return new StreamObserver() { + return new StreamObserver<>() { @Override public void onNext(final ChaincodeMessage chaincodeMessage) { itm.onChaincodeMessage(chaincodeMessage); @@ -288,20 +273,20 @@ public void onCompleted() { protected final void initializeLogging() { // the VM wide formatting string. - System.setProperty("java.util.logging.SimpleFormatter.format", - "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); + System.setProperty( + "java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n"); final Logger rootLogger = Logger.getLogger(""); + var formatter = new SimpleFormatter() { + @Override + public String format(final LogRecord record) { + return Thread.currentThread() + " " + super.format(record); + } + }; + for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { handler.setLevel(ALL); - handler.setFormatter(new SimpleFormatter() { - - @Override - public synchronized String format(final LogRecord record) { - return Thread.currentThread() + " " + super.format(record); - } - - }); + handler.setFormatter(formatter); } rootLogger.info("Updated all handlers the format"); @@ -322,33 +307,31 @@ public synchronized String format(final LogRecord record) { final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM)); Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel); Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel); - } private Level mapLevel(final String level) { if (level != null) { - switch (level.toUpperCase().trim()) { - case "CRITICAL": - case "ERROR": - return Level.SEVERE; - case "WARNING": - case "WARN": - return Level.WARNING; - case "INFO": - return Level.INFO; - case "NOTICE": - return Level.CONFIG; - case "DEBUG": - return Level.FINEST; - default: - break; + switch (level.toUpperCase(Locale.getDefault()).trim()) { + case "CRITICAL": + case "ERROR": + return Level.SEVERE; + case "WARNING": + case "WARN": + return Level.WARNING; + case "INFO": + return Level.INFO; + case "NOTICE": + return Level.CONFIG; + case "DEBUG": + return Level.FINEST; + default: + break; } } return Level.INFO; } - private SocketAddress parseHostPort(final String hostAddrStr) throws URISyntaxException { // WORKAROUND: add any scheme to make the resulting URI valid. @@ -356,9 +339,8 @@ private SocketAddress parseHostPort(final String hostAddrStr) throws URISyntaxEx String host = uri.getHost(); int port = uri.getPort(); - if (uri.getHost() == null || uri.getPort() == -1) { - throw new URISyntaxException(uri.toString(), - "URI must have host and port parts"); + if (host == null || port == -1) { + throw new URISyntaxException(uri.toString(), "URI must have host and port parts"); } // validation succeeded @@ -374,31 +356,35 @@ public boolean isServer() { return !chaincodeServerAddress.isEmpty(); } - /** - * Validate init parameters from env chaincode base. - */ + /** Validate init parameters from env chaincode base. */ + @SuppressWarnings("PMD.CyclomaticComplexity") public void validateOptions() { if (this.id == null || this.id.isEmpty()) { - throw new IllegalArgumentException(format( + throw new IllegalArgumentException(String.format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { - throw new IllegalArgumentException( - format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); + throw new IllegalArgumentException(String.format( + "Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( - format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); + String.format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { - throw new IllegalArgumentException( - format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); + throw new IllegalArgumentException(String.format( + "Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } + @SuppressWarnings({ + "PMD.AvoidLiteralsInIfCondition", + "PMD.AvoidCatchingGenericException", + "PMD.ExceptionAsFlowControl" + }) protected final void processCommandLineOptions(final String[] args) { final Options options = new Options(); options.addOption("a", "peer.address", true, "Address of peer to connect to"); @@ -416,7 +402,7 @@ protected final void processCommandLineOptions(final String[] args) { } final String[] hostArr = hostAddrStr.split(":"); if (hostArr.length == 2) { - port = Integer.valueOf(hostArr[1].trim()); + port = Integer.parseInt(hostArr[1].trim()); host = hostArr[0].trim(); } else { final String msg = String.format( @@ -432,15 +418,13 @@ protected final void processCommandLineOptions(final String[] args) { LOGGER.warning(() -> "cli parsing failed with exception" + Logging.formatError(e)); } - LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>"); - LOGGER.info("CORE_CHAINCODE_ID_NAME: " + this.id); - LOGGER.info("CORE_PEER_ADDRESS: " + this.host + ":" + this.port); - + LOGGER.info(() -> "<<<<<<<<<<<<>>>>>>>>>>>" + "\nCORE_CHAINCODE_ID_NAME: " + + this.id + "\nCORE_PEER_ADDRESS: " + + this.host + ":" + this.port); } - /** - * set fields from env. - */ + /** set fields from env. */ + @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public final void processEnvironmentOptions() { if (System.getenv().containsKey(CORE_CHAINCODE_ID_NAME)) { @@ -449,7 +433,7 @@ public final void processEnvironmentOptions() { if (System.getenv().containsKey(CORE_PEER_ADDRESS)) { final String[] hostArr = System.getenv(CORE_PEER_ADDRESS).split(":"); if (hostArr.length == 2) { - this.port = Integer.valueOf(hostArr[1].trim()); + this.port = Integer.parseInt(hostArr[1].trim()); this.host = hostArr[0].trim(); } else { final String msg = String.format( @@ -477,24 +461,25 @@ public final void processEnvironmentOptions() { this.tlsClientCertFile = System.getenv(ENV_TLS_CLIENT_CERT_FILE); } - LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>"); - LOGGER.info("CORE_CHAINCODE_ID_NAME: " + this.id); - LOGGER.info("CORE_PEER_ADDRESS: " + this.host); - LOGGER.info("CORE_PEER_TLS_ENABLED: " + this.tlsEnabled); - LOGGER.info("CORE_PEER_TLS_ROOTCERT_FILE: " + this.tlsClientRootCertPath); - LOGGER.info("CORE_TLS_CLIENT_KEY_PATH: " + this.tlsClientKeyPath); - LOGGER.info("CORE_TLS_CLIENT_CERT_PATH: " + this.tlsClientCertPath); - LOGGER.info("CORE_TLS_CLIENT_KEY_FILE: " + this.tlsClientKeyFile); - LOGGER.info("CORE_TLS_CLIENT_CERT_FILE: " + this.tlsClientCertFile); - LOGGER.info("CORE_PEER_LOCALMSPID: " + this.localMspId); - LOGGER.info("CHAINCODE_SERVER_ADDRESS: " + this.chaincodeServerAddress); - LOGGER.info("LOGLEVEL: " + this.logLevel); + if (LOGGER.isLoggable(Level.INFO)) { + LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>"); + LOGGER.info("CORE_CHAINCODE_ID_NAME: " + this.id); + LOGGER.info("CORE_PEER_ADDRESS: " + this.host); + LOGGER.info("CORE_PEER_TLS_ENABLED: " + this.tlsEnabled); + LOGGER.info("CORE_PEER_TLS_ROOTCERT_FILE: " + this.tlsClientRootCertPath); + LOGGER.info("CORE_TLS_CLIENT_KEY_PATH: " + this.tlsClientKeyPath); + LOGGER.info("CORE_TLS_CLIENT_CERT_PATH: " + this.tlsClientCertPath); + LOGGER.info("CORE_TLS_CLIENT_KEY_FILE: " + this.tlsClientKeyFile); + LOGGER.info("CORE_TLS_CLIENT_CERT_FILE: " + this.tlsClientCertFile); + LOGGER.info("CORE_PEER_LOCALMSPID: " + this.localMspId); + LOGGER.info("CHAINCODE_SERVER_ADDRESS: " + this.chaincodeServerAddress); + LOGGER.info("LOGLEVEL: " + this.logLevel); + } } /** - * Obtains configuration specifically for running the chaincode and settable on - * a per chaincode basis rather than taking properties from the Peers' - * configuration. + * Obtains configuration specifically for running the chaincode and settable on a per chaincode basis rather than + * taking properties from the Peers' configuration. * * @return Configuration */ @@ -519,7 +504,7 @@ public Properties getChaincodeConfig() { props.setProperty(CORE_PEER_ADDRESS, this.host); LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>"); - LOGGER.info(() -> this.props.toString()); + LOGGER.info(this.props::toString); } return this.props; @@ -579,8 +564,10 @@ final SslContext createSSLContext() throws IOException { final byte[] ckb = Files.readAllBytes(Paths.get(this.tlsClientKeyPath)); final byte[] ccb = Files.readAllBytes(Paths.get(this.tlsClientCertPath)); - return GrpcSslContexts.forClient().trustManager(new File(this.tlsClientRootCertPath)) - .keyManager(new ByteArrayInputStream(Base64.getDecoder().decode(ccb)), + return GrpcSslContexts.forClient() + .trustManager(new File(this.tlsClientRootCertPath)) + .keyManager( + new ByteArrayInputStream(Base64.getDecoder().decode(ccb)), new ByteArrayInputStream(Base64.getDecoder().decode(ckb))) .build(); } @@ -663,12 +650,9 @@ String getId() { return id; } - /** - * Chaincode State. - */ + /** Chaincode State. */ public enum CCState { - /** - * */ + /** */ CREATED, /** */ ESTABLISHED, @@ -676,20 +660,12 @@ public enum CCState { READY } - private CCState state = CCState.CREATED; - - /** - * - * @return State - */ + /** @return State */ public final CCState getState() { return this.state; } - /** - * - * @param newState - */ + /** @param newState */ public final void setState(final CCState newState) { this.state = newState; } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java index fe73b5703..36ec21cf2 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java @@ -8,18 +8,13 @@ import static java.nio.charset.StandardCharsets.UTF_8; /** - * Contracts should use {@code ChaincodeException} to indicate when an error - * occurs in Smart Contract logic. + * Contracts should use {@code ChaincodeException} to indicate when an error occurs in Smart Contract logic. * - *

- * When a {@code ChaincodeException} is thrown an error response will be - * returned from the chaincode container containing the exception message and - * payload, if specified. + *

When a {@code ChaincodeException} is thrown an error response will be returned from the chaincode container + * containing the exception message and payload, if specified. * - *

- * {@code ChaincodeException} may be extended to provide application specific - * error information. Subclasses should ensure that {@link #getPayload} returns - * a serialized representation of the error in a suitable format for client + *

{@code ChaincodeException} may be extended to provide application specific error information. Subclasses should + * ensure that {@link #getPayload} returns a serialized representation of the error in a suitable format for client * applications to process. */ public class ChaincodeException extends RuntimeException { @@ -28,16 +23,13 @@ public class ChaincodeException extends RuntimeException { private byte[] payload; - /** - * Constructs a new {@code ChaincodeException} with no detail message. - */ + /** Constructs a new {@code ChaincodeException} with no detail message. */ public ChaincodeException() { super(); } /** - * Constructs a new {@code ChaincodeException} with the specified detail - * message. + * Constructs a new {@code ChaincodeException} with the specified detail message. * * @param message the detail message. */ @@ -55,23 +47,22 @@ public ChaincodeException(final Throwable cause) { } /** - * Constructs a new {@code ChaincodeException} with the specified detail message - * and cause. + * Constructs a new {@code ChaincodeException} with the specified detail message and cause. * * @param message the detail message. - * @param cause the cause. + * @param cause the cause. */ public ChaincodeException(final String message, final Throwable cause) { super(message, cause); } /** - * Constructs a new {@code ChaincodeException} with the specified detail message - * and response payload. + * Constructs a new {@code ChaincodeException} with the specified detail message and response payload. * * @param message the detail message. * @param payload the response payload. */ + @SuppressWarnings("PMD.ArrayIsStoredDirectly") public ChaincodeException(final String message, final byte[] payload) { super(message); @@ -79,13 +70,13 @@ public ChaincodeException(final String message, final byte[] payload) { } /** - * Constructs a new {@code ChaincodeException} with the specified detail - * message, response payload and cause. + * Constructs a new {@code ChaincodeException} with the specified detail message, response payload and cause. * * @param message the detail message. * @param payload the response payload. - * @param cause the cause. + * @param cause the cause. */ + @SuppressWarnings("PMD.ArrayIsStoredDirectly") public ChaincodeException(final String message, final byte[] payload, final Throwable cause) { super(message, cause); @@ -93,8 +84,7 @@ public ChaincodeException(final String message, final byte[] payload, final Thro } /** - * Constructs a new {@code ChaincodeException} with the specified detail message - * and response payload. + * Constructs a new {@code ChaincodeException} with the specified detail message and response payload. * * @param message the detail message. * @param payload the response payload. @@ -106,12 +96,11 @@ public ChaincodeException(final String message, final String payload) { } /** - * Constructs a new {@code ChaincodeException} with the specified detail - * message, response payload and cause. + * Constructs a new {@code ChaincodeException} with the specified detail message, response payload and cause. * * @param message the detail message. * @param payload the response payload. - * @param cause the cause. + * @param cause the cause. */ public ChaincodeException(final String message, final String payload, final Throwable cause) { super(message, cause); @@ -122,15 +111,13 @@ public ChaincodeException(final String message, final String payload, final Thro /** * Returns the response payload or {@code null} if there is no response. * - *

- * The payload should represent the chaincode error in a way that client - * applications written in different programming languages can interpret. For - * example it could include a domain specific error code, in addition to any - * state information which would allow client applications to respond - * appropriately. + *

The payload should represent the chaincode error in a way that client applications written in different + * programming languages can interpret. For example it could include a domain specific error code, in addition to + * any state information which would allow client applications to respond appropriately. * * @return the response payload or {@code null} if there is no response. */ + @SuppressWarnings("PMD.MethodReturnsInternalArray") public byte[] getPayload() { return payload; } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java index 8c8ff2b35..81c7ce292 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java @@ -8,9 +8,7 @@ import java.io.IOException; -/** - * External chaincode server. - */ +/** External chaincode server. */ public interface ChaincodeServer { /** @@ -21,9 +19,6 @@ public interface ChaincodeServer { */ void start() throws IOException, InterruptedException; - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ void stop(); - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java index 27c842572..4352fe14a 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java @@ -9,41 +9,48 @@ public final class ChaincodeServerProperties { private SocketAddress serverAddress; - private int maxInboundMetadataSize = 100 * 1024 * 1024; // checkstyle:ignore-line:MagicNumber - private int maxInboundMessageSize = 100 * 1024 * 1024; // checkstyle:ignore-line:MagicNumber - private int maxConnectionAgeSeconds = 5; // checkstyle:ignore-line:MagicNumber - private int keepAliveTimeoutSeconds = 20; // checkstyle:ignore-line:MagicNumber - private int permitKeepAliveTimeMinutes = 1; // checkstyle:ignore-line:MagicNumber - private int keepAliveTimeMinutes = 1; // checkstyle:ignore-line:MagicNumber + private int maxInboundMetadataSize = 100 * 1024 * 1024; + private int maxInboundMessageSize = 100 * 1024 * 1024; + private int maxConnectionAgeSeconds = 5; + private int keepAliveTimeoutSeconds = 20; + private int permitKeepAliveTimeMinutes = 1; + private int keepAliveTimeMinutes = 1; private boolean permitKeepAliveWithoutCalls = true; private String keyPassword; private String keyCertChainFile; private String keyFile; private String trustCertCollectionFile; - private boolean tlsEnabled = false; + private boolean tlsEnabled; - /** - * Constructor using default configuration. - */ + /** Constructor using default configuration. */ public ChaincodeServerProperties() { + // Nothing to do } /** * Constructor. + * * @param portChaincodeServer ignored. * @param maxInboundMetadataSize the maximum metadata size allowed to be received by the server. * @param maxInboundMessageSize the maximum message size allowed to be received by the server. * @param maxConnectionAgeSeconds the maximum connection age in seconds. * @param keepAliveTimeoutSeconds timeout for a keep-alive ping request in seconds. - * @param permitKeepAliveTimeMinutes the most aggressive keep-alive time clients are permitted to configure in minutes. + * @param permitKeepAliveTimeMinutes the most aggressive keep-alive time clients are permitted to configure in + * minutes. * @param keepAliveTimeMinutes delay before server sends a keep-alive in minutes. - * @param permitKeepAliveWithoutCalls whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection. + * @param permitKeepAliveWithoutCalls whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are + * no outstanding RPCs on the connection. */ - // checkstyle:ignore-next-line:ParameterNumber + @SuppressWarnings({"PMD.UnusedFormalParameter", "PMD.NullAssignment"}) public ChaincodeServerProperties( - final int portChaincodeServer, final int maxInboundMetadataSize, final int maxInboundMessageSize, - final int maxConnectionAgeSeconds, final int keepAliveTimeoutSeconds, final int permitKeepAliveTimeMinutes, - final int keepAliveTimeMinutes, final boolean permitKeepAliveWithoutCalls) { + final int portChaincodeServer, + final int maxInboundMetadataSize, + final int maxInboundMessageSize, + final int maxConnectionAgeSeconds, + final int keepAliveTimeoutSeconds, + final int permitKeepAliveTimeMinutes, + final int keepAliveTimeMinutes, + final boolean permitKeepAliveWithoutCalls) { this.serverAddress = null; this.maxInboundMetadataSize = maxInboundMetadataSize; @@ -57,6 +64,7 @@ public ChaincodeServerProperties( /** * The maximum size of metadata allowed to be received. + * * @return The maximum metadata size allowed. */ public int getMaxInboundMetadataSize() { @@ -65,6 +73,7 @@ public int getMaxInboundMetadataSize() { /** * Sets the maximum metadata size allowed to be received by the server. + * * @param maxInboundMetadataSize The new maximum size allowed for incoming metadata. */ public void setMaxInboundMetadataSize(final int maxInboundMetadataSize) { @@ -73,6 +82,7 @@ public void setMaxInboundMetadataSize(final int maxInboundMetadataSize) { /** * The maximum message size allowed to be received by the server. + * * @return the maximum message size allowed. */ public int getMaxInboundMessageSize() { @@ -81,6 +91,7 @@ public int getMaxInboundMessageSize() { /** * Sets the maximum message size allowed to be received by the server. + * * @param maxInboundMessageSize The new maximum size allowed for incoming messages. */ public void setMaxInboundMessageSize(final int maxInboundMessageSize) { @@ -89,6 +100,7 @@ public void setMaxInboundMessageSize(final int maxInboundMessageSize) { /** * The maximum connection age. + * * @return The maximum connection age in seconds. */ public int getMaxConnectionAgeSeconds() { @@ -97,6 +109,7 @@ public int getMaxConnectionAgeSeconds() { /** * Specify a maximum connection age. + * * @param maxConnectionAgeSeconds The maximum connection age in seconds. */ public void setMaxConnectionAgeSeconds(final int maxConnectionAgeSeconds) { @@ -105,6 +118,7 @@ public void setMaxConnectionAgeSeconds(final int maxConnectionAgeSeconds) { /** * The timeout for a keep-alive ping requests. + * * @return timeout in seconds. */ public int getKeepAliveTimeoutSeconds() { @@ -113,6 +127,7 @@ public int getKeepAliveTimeoutSeconds() { /** * Set the timeout for keep-alive ping requests. + * * @param keepAliveTimeoutSeconds timeout in seconds. */ public void setKeepAliveTimeoutSeconds(final int keepAliveTimeoutSeconds) { @@ -121,6 +136,7 @@ public void setKeepAliveTimeoutSeconds(final int keepAliveTimeoutSeconds) { /** * The most aggressive keep-alive time clients are permitted to configure. + * * @return time in minutes. */ public int getPermitKeepAliveTimeMinutes() { @@ -129,6 +145,7 @@ public int getPermitKeepAliveTimeMinutes() { /** * Specify the most aggressive keep-alive time clients are permitted to configure. + * * @param permitKeepAliveTimeMinutes time in minutes. */ public void setPermitKeepAliveTimeMinutes(final int permitKeepAliveTimeMinutes) { @@ -137,6 +154,7 @@ public void setPermitKeepAliveTimeMinutes(final int permitKeepAliveTimeMinutes) /** * The delay before the server sends a keep-alive. + * * @return delay in minutes. */ public int getKeepAliveTimeMinutes() { @@ -145,6 +163,7 @@ public int getKeepAliveTimeMinutes() { /** * Set the delay before the server sends a keep-alive. + * * @param keepAliveTimeMinutes delay in minutes. */ public void setKeepAliveTimeMinutes(final int keepAliveTimeMinutes) { @@ -152,15 +171,19 @@ public void setKeepAliveTimeMinutes(final int keepAliveTimeMinutes) { } /** - * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection. + * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the + * connection. + * * @return true if clients are allowed to send keep-alive requests without calls; otherwise false. */ + @SuppressWarnings("PMD.BooleanGetMethodName") public boolean getPermitKeepAliveWithoutCalls() { return permitKeepAliveWithoutCalls; } /** * Get the server socket address. + * * @return a socket address. */ public SocketAddress getServerAddress() { @@ -169,6 +192,7 @@ public SocketAddress getServerAddress() { /** * Set the server socket address. + * * @param address a socket address. */ public void setServerAddress(final SocketAddress address) { @@ -176,7 +200,9 @@ public void setServerAddress(final SocketAddress address) { } /** - * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection. + * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the + * connection. + * * @return true if clients are allowed to send keep-alive requests without calls; otherwise false. */ public boolean isPermitKeepAliveWithoutCalls() { @@ -184,7 +210,9 @@ public boolean isPermitKeepAliveWithoutCalls() { } /** - * Specify whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection. + * Specify whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the + * connection. + * * @param permitKeepAliveWithoutCalls Whether to allow clients to send keep-alive requests without calls. */ public void setPermitKeepAliveWithoutCalls(final boolean permitKeepAliveWithoutCalls) { @@ -193,6 +221,7 @@ public void setPermitKeepAliveWithoutCalls(final boolean permitKeepAliveWithoutC /** * Password used to access the server key. + * * @return a password. */ public String getKeyPassword() { @@ -201,6 +230,7 @@ public String getKeyPassword() { /** * Set the password used to access the server key. + * * @param keyPassword a password. */ public void setKeyPassword(final String keyPassword) { @@ -209,6 +239,7 @@ public void setKeyPassword(final String keyPassword) { /** * Server keychain file name. + * * @return a file name. */ public String getKeyCertChainFile() { @@ -217,6 +248,7 @@ public String getKeyCertChainFile() { /** * Set the server keychain file name. + * * @param keyCertChainFile a file name. */ public void setKeyCertChainFile(final String keyCertChainFile) { @@ -225,6 +257,7 @@ public void setKeyCertChainFile(final String keyCertChainFile) { /** * Server key file name. + * * @return a file name. */ public String getKeyFile() { @@ -233,6 +266,7 @@ public String getKeyFile() { /** * Set the server key file name. + * * @param keyFile a file name. */ public void setKeyFile(final String keyFile) { @@ -241,6 +275,7 @@ public void setKeyFile(final String keyFile) { /** * Server trust certificate collection file name. + * * @return a file name. */ public String getTrustCertCollectionFile() { @@ -249,6 +284,7 @@ public String getTrustCertCollectionFile() { /** * Set the server trust certificate collection file name. + * * @param trustCertCollectionFile a file name. */ public void setTrustCertCollectionFile(final String trustCertCollectionFile) { @@ -257,6 +293,7 @@ public void setTrustCertCollectionFile(final String trustCertCollectionFile) { /** * Whether TLS is enabled for the server. + * * @return true if TLS is enabled; otherwise false. */ public boolean isTlsEnabled() { @@ -265,6 +302,7 @@ public boolean isTlsEnabled() { /** * Set whether TLS is enabled for the server. + * * @param tlsEnabled true to enable TLS; otherwise false. */ public void setTlsEnabled(final boolean tlsEnabled) { @@ -273,37 +311,46 @@ public void setTlsEnabled(final boolean tlsEnabled) { /** * Check that all the server property values are valid. + * * @throws IllegalArgumentException if any properties are not valid. */ + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.NPathComplexity"}) public void validate() { if (this.getServerAddress() == null) { throw new IllegalArgumentException("chaincodeServerProperties.getServerAddress() must be set"); } if (this.getKeepAliveTimeMinutes() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0"); } if (this.getKeepAliveTimeoutSeconds() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0"); } if (this.getPermitKeepAliveTimeMinutes() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0"); } if (this.getMaxConnectionAgeSeconds() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0"); } if (this.getMaxInboundMetadataSize() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0"); } if (this.getMaxInboundMessageSize() <= 0) { - throw new IllegalArgumentException("chaincodeServerProperties.getMaxInboundMessageSize() must be more then 0"); + throw new IllegalArgumentException( + "chaincodeServerProperties.getMaxInboundMessageSize() must be more then 0"); } - if (this.isTlsEnabled() && (this.getKeyCertChainFile() == null || this.getKeyCertChainFile().isEmpty() - || this.getKeyFile() == null || this.getKeyFile().isEmpty())) { + if (this.isTlsEnabled() + && (this.getKeyCertChainFile() == null + || this.getKeyCertChainFile().isEmpty() + || this.getKeyFile() == null + || this.getKeyFile().isEmpty())) { throw new IllegalArgumentException("if chaincodeServerProperties.isTlsEnabled() must be more specified" - + " chaincodeServerProperties.getKeyCertChainFile() and chaincodeServerProperties.getKeyFile()" - + " with optional chaincodeServerProperties.getKeyPassword()"); + + " chaincodeServerProperties.getKeyCertChainFile() and chaincodeServerProperties.getKeyFile()" + + " with optional chaincodeServerProperties.getKeyPassword()"); } } - - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java index 7c77f5daa..63a5fab40 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java @@ -13,7 +13,6 @@ import java.util.Arrays; import java.util.List; import java.util.Map; - import org.hyperledger.fabric.protos.peer.ChaincodeEvent; import org.hyperledger.fabric.protos.peer.SignedProposal; import org.hyperledger.fabric.shim.Chaincode.Response; @@ -24,23 +23,22 @@ import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata; /** - * An object which manages the transaction context, provides access to state variables, and supports calls to other chaincode implementations. + * An object which manages the transaction context, provides access to state variables, and supports calls to other + * chaincode implementations. */ +@SuppressWarnings("PMD.ExcessivePublicCount") public interface ChaincodeStub { /** - * Returns the arguments corresponding to the call to - * {@link Chaincode#init(ChaincodeStub)} or - * {@link Chaincode#invoke(ChaincodeStub)}, each argument represented as byte - * array. + * Returns the arguments corresponding to the call to {@link Chaincode#init(ChaincodeStub)} or + * {@link Chaincode#invoke(ChaincodeStub)}, each argument represented as byte array. * * @return a list of arguments (bytes arrays) */ List getArgs(); /** - * Returns the arguments corresponding to the call to - * {@link Chaincode#init(ChaincodeStub)} or + * Returns the arguments corresponding to the call to {@link Chaincode#init(ChaincodeStub)} or * {@link Chaincode#invoke(ChaincodeStub)}, cast to UTF-8 string. * * @return a list of arguments cast to UTF-8 strings @@ -48,22 +46,19 @@ public interface ChaincodeStub { List getStringArgs(); /** - * A convenience method that returns the first argument of the chaincode - * invocation for use as a function name. - *

- * The bytes of the first argument are decoded as a UTF-8 string. + * A convenience method that returns the first argument of the chaincode invocation for use as a function name. + * + *

The bytes of the first argument are decoded as a UTF-8 string. * * @return the function name */ String getFunction(); /** - * A convenience method that returns all except the first argument of the - * chaincode invocation for use as the parameters to the function returned by - * #{@link ChaincodeStub#getFunction()}. - *

- * The bytes of the arguments are decoded as a UTF-8 strings and returned as a - * list of string parameters. + * A convenience method that returns all except the first argument of the chaincode invocation for use as the + * parameters to the function returned by #{@link ChaincodeStub#getFunction()}. + * + *

The bytes of the arguments are decoded as a UTF-8 strings and returned as a list of string parameters. * * @return a list of parameters */ @@ -71,9 +66,8 @@ public interface ChaincodeStub { /** * Returns the transaction id for the current chaincode invocation request. - *

- * The transaction id uniquely identifies the transaction within the scope of - * the channel. + * + *

The transaction id uniquely identifies the transaction within the scope of the channel. * * @return the transaction id */ @@ -81,49 +75,45 @@ public interface ChaincodeStub { /** * Returns the channel id for the current proposal. - *

- * This would be the 'channel_id' of the transaction proposal except where the - * chaincode is calling another on a different channel. + * + *

This would be the 'channel_id' of the transaction proposal except where the chaincode is calling another on a + * different channel. * * @return the channel id */ String getChannelId(); /** - * Locally calls the specified chaincode invoke() using the same - * transaction context. - *

- * chaincode calling chaincode doesn't create a new transaction message. - *

- * If the called chaincode is on the same channel, it simply adds the called - * chaincode read set and write set to the calling transaction. - *

- * If the called chaincode is on a different channel, only the Response is - * returned to the calling chaincode; any putState calls from the - * called chaincode will not have any effect on the ledger; that is, the called - * chaincode on a different channel will not have its read set and write set - * applied to the transaction. Only the calling chaincode's read set and write - * set will be applied to the transaction. Effectively the called chaincode on a - * different channel is a `Query`, which does not participate in state - * validation checks in subsequent commit phase. - *

- * If `channel` is empty, the caller's channel is assumed. - *

- * Invoke another chaincode using the same transaction context. + * Locally calls the specified chaincode invoke() using the same transaction context. + * + *

chaincode calling chaincode doesn't create a new transaction message. + * + *

If the called chaincode is on the same channel, it simply adds the called chaincode read set and write set to + * the calling transaction. + * + *

If the called chaincode is on a different channel, only the Response is returned to the calling chaincode; any + * putState calls from the called chaincode will not have any effect on the ledger; that is, the called + * chaincode on a different channel will not have its read set and write set applied to the transaction. Only the + * calling chaincode's read set and write set will be applied to the transaction. Effectively the called chaincode + * on a different channel is a `Query`, which does not participate in state validation checks in subsequent commit + * phase. + * + *

If `channel` is empty, the caller's channel is assumed. + * + *

Invoke another chaincode using the same transaction context. * * @param chaincodeName Name of chaincode to be invoked. - * @param args Arguments to pass on to the called chaincode. - * @param channel If not specified, the caller's channel is assumed. + * @param args Arguments to pass on to the called chaincode. + * @param channel If not specified, the caller's channel is assumed. * @return {@link Response} object returned by called chaincode */ Response invokeChaincode(String chaincodeName, List args, String channel); /** * Returns the value of the specified key from the ledger. - *

- * Note that getState doesn't read data from the writeset, which has not been - * committed to the ledger. In other words, GetState doesn't consider data - * modified by PutState that has not been committed. + * + *

Note that getState doesn't read data from the writeset, which has not been committed to the ledger. In other + * words, GetState doesn't consider data modified by PutState that has not been committed. * * @param key name of the value * @return value the value read from the ledger @@ -131,9 +121,8 @@ public interface ChaincodeStub { byte[] getState(String key); /** - * retrieves the key-level endorsement policy for key. Note that - * this will introduce a read dependency on key in the - * transaction's readset. + * retrieves the key-level endorsement policy for key. Note that this will introduce a read dependency + * on key in the transaction's readset. * * @param key key to get key level endorsement * @return endorsement policy @@ -141,15 +130,14 @@ public interface ChaincodeStub { byte[] getStateValidationParameter(String key); /** - * Puts the specified key and value into the - * transaction's writeset as a data-write proposal. - *

- * putState doesn't effect the ledger until the transaction is validated and - * successfully committed. Simple keys must not be an empty string and must not - * start with 0x00 character, in order to avoid range query collisions with + * Puts the specified key and value into the transaction's writeset as a data-write + * proposal. + * + *

putState doesn't effect the ledger until the transaction is validated and successfully committed. Simple keys + * must not be an empty string and must not start with 0x00 character, in order to avoid range query collisions with * composite keys * - * @param key name of the value + * @param key name of the value * @param value the value to write to the ledger */ void putState(String key, byte[] value); @@ -157,79 +145,66 @@ public interface ChaincodeStub { /** * Sets the key-level endorsement policy for key. * - * @param key key to set key level endorsement + * @param key key to set key level endorsement * @param value endorsement policy */ void setStateValidationParameter(String key, byte[] value); /** - * Records the specified key to be deleted in the writeset of the - * transaction proposal. - *

- * The key and its value will be deleted from the ledger when the - * transaction is validated and successfully committed. + * Records the specified key to be deleted in the writeset of the transaction proposal. + * + *

The key and its value will be deleted from the ledger when the transaction is validated and + * successfully committed. * * @param key name of the value to be deleted */ void delState(String key); /** - * Returns all existing keys, and their values, that are lexicographically - * between startkey (inclusive) and the endKey - * (exclusive). - *

- * The keys are returned by the iterator in lexical order. Note that startKey - * and endKey can be empty string, which implies unbounded range query on start - * or end. - *

- * Call close() on the returned {@link QueryResultsIterator#close()} object when - * done. + * Returns all existing keys, and their values, that are lexicographically between startkey (inclusive) + * and the endKey (exclusive). + * + *

The keys are returned by the iterator in lexical order. Note that startKey and endKey can be empty string, + * which implies unbounded range query on start or end. + * + *

Call close() on the returned {@link QueryResultsIterator#close()} object when done. * * @param startKey key as the start of the key range (inclusive) - * @param endKey key as the end of the key range (exclusive) + * @param endKey key as the end of the key range (exclusive) * @return an {@link Iterable} of {@link KeyValue} */ QueryResultsIterator getStateByRange(String startKey, String endKey); /** - * Returns a range iterator over a set of keys in the ledger. The iterator can - * be used to fetch keys between the startKey (inclusive) and - * endKey (exclusive). When an empty string is passed as a value to - * the bookmark argument, the returned iterator can be used to - * fetch the first pageSize keys between the startKey - * and endKey. When the bookmark is a non-empty - * string, the iterator can be used to fetch first pageSize keys - * between the bookmark and endKey. Note that only the - * bookmark present in a prior page of query results - * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) - * can be used as a value to the bookmark argument. Otherwise, an empty string - * must be passed as bookmark. The keys are returned by the iterator in lexical - * order. Note that startKey and endKey can be empty - * string, which implies unbounded range query on start or end. This call is - * only supported in a read only transaction. + * Returns a range iterator over a set of keys in the ledger. The iterator can be used to fetch keys between the + * startKey (inclusive) and endKey (exclusive). When an empty string is passed as a value + * to the bookmark argument, the returned iterator can be used to fetch the first pageSize + * keys between the startKey and endKey. When the bookmark is a non-empty + * string, the iterator can be used to fetch first pageSize keys between the bookmark and + * endKey. Note that only the bookmark present in a prior page of query results + * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark + * argument. Otherwise, an empty string must be passed as bookmark. The keys are returned by the iterator in lexical + * order. Note that startKey and endKey can be empty string, which implies unbounded range + * query on start or end. This call is only supported in a read only transaction. * * @param startKey the start key - * @param endKey the end key + * @param endKey the end key * @param pageSize the page size * @param bookmark the bookmark * @return QueryIterator */ - QueryResultsIteratorWithMetadata getStateByRangeWithPagination(String startKey, String endKey, int pageSize, String bookmark); + QueryResultsIteratorWithMetadata getStateByRangeWithPagination( + String startKey, String endKey, int pageSize, String bookmark); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey}. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. - *

- * This method takes responsibility to correctly parse the {@link CompositeKey} - * from a String and behaves exactly as - * {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}. - *

- *

- * Call close() on the returned {@link QueryResultsIterator#close()} object when - * done. + * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. + * + *

This method takes responsibility to correctly parse the {@link CompositeKey} from a String and behaves exactly + * as {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}. + * + *

Call close() on the returned {@link QueryResultsIterator#close()} object when done. * * @param compositeKey partial composite key * @return an {@link Iterable} of {@link KeyValue} @@ -237,21 +212,15 @@ public interface ChaincodeStub { QueryResultsIterator getStateByPartialCompositeKey(String compositeKey); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey}. - *

- * It combines the attributes and the objectType to form a partial composite - * key. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. - *

- * This method takes responsibility to correctly combine Object type and - * attributes creating a {@link CompositeKey} and behaves exactly as - * {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}. - *

- * Call close() on the returned {@link QueryResultsIterator#close()} object when - * done. + * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}. + * + *

It combines the attributes and the objectType to form a partial composite key. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. + * + *

This method takes responsibility to correctly combine Object type and attributes creating a + * {@link CompositeKey} and behaves exactly as {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}. + * Call close() on the returned {@link QueryResultsIterator#close()} object when done. * * @param objectType ObjectType of the compositeKey * @param attributes Attributes of the composite key @@ -260,11 +229,9 @@ public interface ChaincodeStub { QueryResultsIterator getStateByPartialCompositeKey(String objectType, String... attributes); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey}. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. + * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. * * @param compositeKey partial composite key * @return an {@link Iterable} of {@link KeyValue} @@ -272,36 +239,32 @@ public interface ChaincodeStub { QueryResultsIterator getStateByPartialCompositeKey(CompositeKey compositeKey); /** - * Queries the state in the ledger based on a given partial composite key. This - * function returns an iterator which can be used to iterate over the composite - * keys whose prefix matches the given partial composite key. - *

- * When an empty string is passed as a value to the bookmark - * argument, the returned iterator can be used to fetch the first - * pageSize composite keys whose prefix matches the given partial - * composite key. - *

- * When the bookmark is a non-empty string, the iterator can be - * used to fetch first pageSize keys between the - * bookmark (inclusive) and and the last matching composite key. - *

- * Note that only the bookmark present in a prior page of query results - * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) - * can be used as a value to the bookmark argument. Otherwise, an empty string - * must be passed as bookmark. - *

- * This call is only supported in a read only transaction. + * Queries the state in the ledger based on a given partial composite key. This function returns an iterator which + * can be used to iterate over the composite keys whose prefix matches the given partial composite key. + * + *

When an empty string is passed as a value to the bookmark argument, the returned iterator can be + * used to fetch the first pageSize composite keys whose prefix matches the given partial composite + * key. + * + *

When the bookmark is a non-empty string, the iterator can be used to fetch first pageSize + * keys between the bookmark (inclusive) and and the last matching composite key. + * + *

Note that only the bookmark present in a prior page of query results + * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark + * argument. Otherwise, an empty string must be passed as bookmark. + * + *

This call is only supported in a read only transaction. * * @param compositeKey the composite key - * @param pageSize the page size - * @param bookmark the bookmark + * @param pageSize the page size + * @param bookmark the bookmark * @return QueryIterator */ - QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(CompositeKey compositeKey, int pageSize, String bookmark); + QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination( + CompositeKey compositeKey, int pageSize, String bookmark); /** - * Given a set of attributes, this method combines these attributes to return a - * composite key. + * Given a set of attributes, this method combines these attributes to return a composite key. * * @param objectType A string used as the prefix of the resulting key * @param attributes List of attribute values to concatenate into the key @@ -319,53 +282,46 @@ public interface ChaincodeStub { /** * Performs a "rich" query against a state database. - *

- * It is only supported for state databases that support rich query, e.g. - * CouchDB. The query string is in the native syntax of the underlying state - * database. An {@link QueryResultsIterator} is returned which can be used to + * + *

It is only supported for state databases that support rich query, e.g. CouchDB. The query string is in the + * native syntax of the underlying state database. An {@link QueryResultsIterator} is returned which can be used to * iterate (next) over the query result set. * - * @param query query string in a syntax supported by the underlying state - * database + * @param query query string in a syntax supported by the underlying state database * @return {@link QueryResultsIterator} object contains query results - * @throws UnsupportedOperationException if the underlying state database does - * not support rich queries. + * @throws UnsupportedOperationException if the underlying state database does not support rich queries. */ QueryResultsIterator getQueryResult(String query); /** - * Performs a "rich" query against a state database. It is only supported for - * state databases that support rich query, e.g., CouchDB. The query string is - * in the native syntax of the underlying state database. An iterator is - * returned which can be used to iterate over keys in the query result set. When - * an empty string is passed as a value to the bookmark argument, - * the returned iterator can be used to fetch the first pageSize of - * query results.. - *

- * When the bookmark is a non-empty string, the iterator can be - * used to fetch first pageSize keys between the - * bookmark (inclusive) and the last key in the query result. - *

- * Note that only the bookmark present in a prior page of query results - * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) - * can be used as a value to the bookmark argument. Otherwise, an empty string - * must be passed as bookmark. - *

- * This call is only supported in a read only transaction. - * - * @param query the query + * Performs a "rich" query against a state database. It is only supported for state databases that support rich + * query, e.g., CouchDB. The query string is in the native syntax of the underlying state database. An iterator is + * returned which can be used to iterate over keys in the query result set. When an empty string is passed as a + * value to the bookmark argument, the returned iterator can be used to fetch the first pageSize + * of query results.. + * + *

When the bookmark is a non-empty string, the iterator can be used to fetch first pageSize + * keys between the bookmark (inclusive) and the last key in the query result. + * + *

Note that only the bookmark present in a prior page of query results + * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark + * argument. Otherwise, an empty string must be passed as bookmark. + * + *

This call is only supported in a read only transaction. + * + * @param query the query * @param pageSize the page size * @param bookmark the bookmark * @return QueryIterator */ - QueryResultsIteratorWithMetadata getQueryResultWithPagination(String query, int pageSize, String bookmark); + QueryResultsIteratorWithMetadata getQueryResultWithPagination( + String query, int pageSize, String bookmark); /** * Returns a history of key values across time. - *

- * For each historic key update, the historic value and associated transaction - * id and timestamp are returned. The timestamp is the timestamp provided by the - * client in the proposal header. This method requires peer configuration + * + *

For each historic key update, the historic value and associated transaction id and timestamp are returned. The + * timestamp is the timestamp provided by the client in the proposal header. This method requires peer configuration * core.ledger.history.enableHistoryDatabase to be true. * * @param key The state variable key @@ -374,227 +330,197 @@ public interface ChaincodeStub { QueryResultsIterator getHistoryForKey(String key); /** - * Returns the value of the specified key from the specified - * collection. - *

- * Note that {@link #getPrivateData(String, String)} doesn't read data from the - * private writeset, which has not been committed to the - * collection. In other words, - * {@link #getPrivateData(String, String)} doesn't consider data modified by - * {@link #putPrivateData(String, String, byte[])} * that has not been - * committed. + * Returns the value of the specified key from the specified collection. + * + *

Note that {@link #getPrivateData(String, String)} doesn't read data from the private writeset, which has not + * been committed to the collection. In other words, {@link #getPrivateData(String, String)} doesn't + * consider data modified by {@link #putPrivateData(String, String, byte[])} * that has not been committed. * * @param collection name of the collection - * @param key name of the value + * @param key name of the value * @return value the value read from the collection */ byte[] getPrivateData(String collection, String key); /** * @param collection name of the collection - * @param key name of the value + * @param key name of the value * @return the private data hash */ byte[] getPrivateDataHash(String collection, String key); /** - * Retrieves the key-level endorsement policy for the private data specified by - * key. Note that this introduces a read dependency on - * key in the transaction's readset. + * Retrieves the key-level endorsement policy for the private data specified by key. Note that this + * introduces a read dependency on key in the transaction's readset. * * @param collection name of the collection - * @param key key to get endorsement policy + * @param key key to get endorsement policy * @return Key Level endorsement as byte array */ byte[] getPrivateDataValidationParameter(String collection, String key); /** - * Puts the specified key and value into the - * transaction's private writeset. - *

- * Note that only hash of the private writeset goes into the transaction - * proposal response (which is sent to the client who issued the transaction) - * and the actual private writeset gets temporarily stored in a transient store. - * putPrivateData doesn't effect the collection until the - * transaction is validated and successfully committed. Simple keys must not be - * an empty string and must not start with null character (0x00), in order to - * avoid range query collisions with composite keys, which internally get - * prefixed with 0x00 as composite key namespace. + * Puts the specified key and value into the transaction's private writeset. + * + *

Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the + * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store. + * putPrivateData doesn't effect the collection until the transaction is validated and successfully + * committed. Simple keys must not be an empty string and must not start with null character (0x00), in order to + * avoid range query collisions with composite keys, which internally get prefixed with 0x00 as composite key + * namespace. * * @param collection name of the collection - * @param key name of the value - * @param value the value to write to the ledger + * @param key name of the value + * @param value the value to write to the ledger */ void putPrivateData(String collection, String key, byte[] value); /** - * Sets the key-level endorsement policy for the private data specified by - * key. + * Sets the key-level endorsement policy for the private data specified by key. * * @param collection name of the collection - * @param key key to set endorsement policy - * @param value endorsement policy + * @param key key to set endorsement policy + * @param value endorsement policy */ void setPrivateDataValidationParameter(String collection, String key, byte[] value); /** - * Records the specified key to be deleted in the private writeset - * of the transaction. - *

- * Note that only hash of the private writeset goes into the transaction - * proposal response (which is sent to the client who issued the transaction) - * and the actual private writeset gets temporarily stored in a transient store. - * The key and its value will be deleted from the collection when - * the transaction is validated and successfully committed. + * Records the specified key to be deleted in the private writeset of the transaction. + * + *

Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the + * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store. + * The key and its value will be deleted from the collection when the transaction is validated and + * successfully committed. * * @param collection name of the collection - * @param key name of the value to be deleted + * @param key name of the value to be deleted */ void delPrivateData(String collection, String key); /** - * Reqauests purging of the specified key to be from - * the private data stores. - *

- * Note that only hash of the private writeset goes into the transaction - * proposal response (which is sent to the client who issued the transaction) - * and the actual private writeset gets temporarily stored in a transient store. - * The key and its value will be purged from the collection. This is an - * asynchronous activity. - *

- * Purge is a complete removal of the history of the key. There is existing purge - * possible mased on block height. This API allows the contract to be pro-active in - * requesting data be purged. This can contribute towards meeting privacy requirements. + * Reqauests purging of the specified key to be from the private data stores. + * + *

Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the + * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store. + * The key and its value will be purged from the collection. This is an asynchronous activity. + * + *

Purge is a complete removal of the history of the key. There is existing purge possible mased on block height. + * This API allows the contract to be pro-active in requesting data be purged. This can contribute towards meeting + * privacy requirements. * * @param collection name of the collection - * @param key name of the value to be deleted + * @param key name of the value to be deleted */ void purgePrivateData(String collection, String key); /** - * Returns all existing keys, and their values, that are lexicographically - * between startkey (inclusive) and the endKey - * (exclusive) in a given private collection. - *

- * Note that startKey and endKey can be empty string, which implies unbounded - * range query on start or end. The query is re-executed during validation phase - * to ensure result set has not changed since transaction endorsement (phantom - * reads detected). + * Returns all existing keys, and their values, that are lexicographically between startkey (inclusive) + * and the endKey (exclusive) in a given private collection. + * + *

Note that startKey and endKey can be empty string, which implies unbounded range query on start or end. The + * query is re-executed during validation phase to ensure result set has not changed since transaction endorsement + * (phantom reads detected). * * @param collection name of the collection - * @param startKey private data variable key as the start of the key range - * (inclusive) - * @param endKey private data variable key as the end of the key range - * (exclusive) + * @param startKey private data variable key as the start of the key range (inclusive) + * @param endKey private data variable key as the end of the key range (exclusive) * @return an {@link Iterable} of {@link KeyValue} */ QueryResultsIterator getPrivateDataByRange(String collection, String startKey, String endKey); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey} in a given private collection. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. - *

- * The query is re-executed during validation phase to ensure result set has not - * changed since transaction endorsement (phantom reads detected). - *

- * This method takes responsibility to correctly parse the {@link CompositeKey} - * from a String and behaves exactly as - * {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}. - *

- * - * @param collection name of the collection + * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a + * given private collection. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. + * + *

The query is re-executed during validation phase to ensure result set has not changed since transaction + * endorsement (phantom reads detected). + * + *

This method takes responsibility to correctly parse the {@link CompositeKey} from a String and behaves exactly + * as {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}. + * + * @param collection name of the collection * @param compositeKey partial composite key * @return an {@link Iterable} of {@link KeyValue} */ QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, String compositeKey); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey} in a given private collection. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. - *

- * The query is re-executed during validation phase to ensure result set has not - * changed since transaction endorsement (phantom reads detected). + * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a + * given private collection. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. + * + *

The query is re-executed during validation phase to ensure result set has not changed since transaction + * endorsement (phantom reads detected). * - * @param collection name of the collection + * @param collection name of the collection * @param compositeKey partial composite key * @return an {@link Iterable} of {@link KeyValue} */ QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, CompositeKey compositeKey); /** - * Returns all existing keys, and their values, that are prefixed by the - * specified partial {@link CompositeKey} in a given private collection. - *

- * If a full composite key is specified, it will not match itself, resulting in - * no keys being returned. - *

- * The query is re-executed during validation phase to ensure result set has not - * changed since transaction endorsement (phantom reads detected). - *

- * This method takes responsibility to correctly combine Object type and - * attributes creating a {@link CompositeKey} and behaves exactly as - * {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}. - *

+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a + * given private collection. + * + *

If a full composite key is specified, it will not match itself, resulting in no keys being returned. + * + *

The query is re-executed during validation phase to ensure result set has not changed since transaction + * endorsement (phantom reads detected). + * + *

This method takes responsibility to correctly combine Object type and attributes creating a + * {@link CompositeKey} and behaves exactly as {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, + * CompositeKey)}. * * @param collection name of the collection * @param objectType ObjectType of the compositeKey * @param attributes Attributes of the composite key * @return an {@link Iterable} of {@link KeyValue} */ - QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, String objectType, String... attributes); + QueryResultsIterator getPrivateDataByPartialCompositeKey( + String collection, String objectType, String... attributes); /** * Perform a rich query against a given private collection. - *

- * It is only supported for state databases that support rich query, - * e.g.CouchDB. The query string is in the native syntax of the underlying state - * database. An iterator is returned which can be used to iterate (next) over - * the query result set. The query is NOT re-executed during validation phase, - * phantom reads are not detected. That is, other committed transactions may - * have added, updated, or removed keys that impact the result set, and this - * would not be detected at validation/commit time. Applications susceptible to - * this should therefore not use GetQueryResult as part of transactions that - * update ledger, and should limit use to read-only chaincode operations. + * + *

It is only supported for state databases that support rich query, e.g.CouchDB. The query string is in the + * native syntax of the underlying state database. An iterator is returned which can be used to iterate (next) over + * the query result set. The query is NOT re-executed during validation phase, phantom reads are not detected. That + * is, other committed transactions may have added, updated, or removed keys that impact the result set, and this + * would not be detected at validation/commit time. Applications susceptible to this should therefore not use + * GetQueryResult as part of transactions that update ledger, and should limit use to read-only chaincode + * operations. * * @param collection name of the collection - * @param query query string in a syntax supported by the underlying state - * database + * @param query query string in a syntax supported by the underlying state database * @return {@link QueryResultsIterator} object contains query results - * @throws UnsupportedOperationException if the underlying state database does - * not support rich queries. + * @throws UnsupportedOperationException if the underlying state database does not support rich queries. */ QueryResultsIterator getPrivateDataQueryResult(String collection, String query); /** - * Allows the chaincode to propose an event on the transaction proposal response. - * When the transaction is included in a block and the block is successfully committed to the ledger, - * the block event (including transaction level chaincode events) - * will be delivered to the current client application event listeners that have been registered with the peer's event producer. - * Consult each SDK's documentation for details. - * Only a single chaincode event can be included in a transaction. - * If setEvent() is called multiple times only the last event will be included in the transaction. - * The event must originate from the outer-most invoked chaincode in chaincode-to-chaincode scenarios. + * Allows the chaincode to propose an event on the transaction proposal response. When the transaction is included + * in a block and the block is successfully committed to the ledger, the block event (including transaction level + * chaincode events) will be delivered to the current client application event listeners that have been registered + * with the peer's event producer. Consult each SDK's documentation for details. Only a single chaincode event can + * be included in a transaction. If setEvent() is called multiple times only the last event will be included in the + * transaction. The event must originate from the outer-most invoked chaincode in chaincode-to-chaincode scenarios. * The marshaled ChaincodeEvent will be available in the transaction's ChaincodeAction.events field. * - * @param name Name of event. Cannot be null or empty string. + * @param name Name of event. Cannot be null or empty string. * @param payload Optional event payload. */ void setEvent(String name, byte[] payload); /** * Invoke another chaincode using the same transaction context. - *

- * Same as {@link #invokeChaincode(String, List, String)} using channelId to - * null + * + *

Same as {@link #invokeChaincode(String, List, String)} using channelId to null * * @param chaincodeName Name of chaincode to be invoked. - * @param args Arguments to pass on to the called chaincode. + * @param args Arguments to pass on to the called chaincode. * @return {@link Response} object returned by called chaincode */ default Response invokeChaincode(final String chaincodeName, final List args) { @@ -603,28 +529,29 @@ default Response invokeChaincode(final String chaincodeName, final List /** * Invoke another chaincode using the same transaction context. - *

- * This is a convenience version of - * {@link #invokeChaincode(String, List, String)}. The string args will be + * + *

This is a convenience version of {@link #invokeChaincode(String, List, String)}. The string args will be * encoded into as UTF-8 bytes. * * @param chaincodeName Name of chaincode to be invoked. - * @param args Arguments to pass on to the called chaincode. - * @param channel If not specified, the caller's channel is assumed. + * @param args Arguments to pass on to the called chaincode. + * @param channel If not specified, the caller's channel is assumed. * @return {@link Response} object returned by called chaincode */ - default Response invokeChaincodeWithStringArgs(final String chaincodeName, final List args, final String channel) { - return invokeChaincode(chaincodeName, args.stream().map(x -> x.getBytes(UTF_8)).collect(toList()), channel); + default Response invokeChaincodeWithStringArgs( + final String chaincodeName, final List args, final String channel) { + return invokeChaincode( + chaincodeName, args.stream().map(x -> x.getBytes(UTF_8)).collect(toList()), channel); } /** * Invoke another chaincode using the same transaction context. - *

- * This is a convenience version of {@link #invokeChaincode(String, List)}. The - * string args will be encoded into as UTF-8 bytes. + * + *

This is a convenience version of {@link #invokeChaincode(String, List)}. The string args will be encoded into + * as UTF-8 bytes. * * @param chaincodeName Name of chaincode to be invoked. - * @param args Arguments to pass on to the called chaincode. + * @param args Arguments to pass on to the called chaincode. * @return {@link Response} object returned by called chaincode */ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final List args) { @@ -633,12 +560,12 @@ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final /** * Invoke another chaincode using the same transaction context. - *

- * This is a convenience version of {@link #invokeChaincode(String, List)}. The - * string args will be encoded into as UTF-8 bytes. + * + *

This is a convenience version of {@link #invokeChaincode(String, List)}. The string args will be encoded into + * as UTF-8 bytes. * * @param chaincodeName Name of chaincode to be invoked. - * @param args Arguments to pass on to the called chaincode. + * @param args Arguments to pass on to the called chaincode. * @return {@link Response} object returned by called chaincode */ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final String... args) { @@ -646,10 +573,9 @@ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final } /** - * Returns the byte array value specified by the key and decoded as a UTF-8 - * encoded string, from the ledger. - *

- * This is a convenience version of {@link #getState(String)} + * Returns the byte array value specified by the key and decoded as a UTF-8 encoded string, from the ledger. + * + *

This is a convenience version of {@link #getState(String)} * * @param key name of the value * @return value the value read from the ledger @@ -659,24 +585,22 @@ default String getStringState(final String key) { } /** - * Writes the specified value and key into the sidedb collection value converted - * to byte array. + * Writes the specified value and key into the sidedb collection value converted to byte array. * * @param collection collection name - * @param key name of the value - * @param value the value to write to the ledger + * @param key name of the value + * @param value the value to write to the ledger */ - default void putPrivateData(final String collection, final String key, final String value) { putPrivateData(collection, key, value.getBytes(UTF_8)); } /** - * Returns the byte array value specified by the key and decoded as a UTF-8 - * encoded string, from the sidedb collection. + * Returns the byte array value specified by the key and decoded as a UTF-8 encoded string, from the sidedb + * collection. * * @param collection collection name - * @param key name of the value + * @param key name of the value * @return value the value read from the ledger */ default String getPrivateDataUTF8(final String collection, final String key) { @@ -686,7 +610,7 @@ default String getPrivateDataUTF8(final String collection, final String key) { /** * Writes the specified value and key into the ledger. * - * @param key name of the value + * @param key name of the value * @param value the value to write to the ledger */ default void putStringState(final String key, final String value) { @@ -694,8 +618,8 @@ default void putStringState(final String key, final String value) { } /** - * Returns the CHAINCODE type event that will be posted to interested clients - * when the chaincode's result is committed to the ledger. + * Returns the CHAINCODE type event that will be posted to interested clients when the chaincode's result is + * committed to the ledger. * * @return the chaincode event or null */ @@ -704,8 +628,7 @@ default void putStringState(final String key, final String value) { /** * Returns the signed transaction proposal currently being executed. * - * @return null if the current transaction is an internal call to a system - * chaincode. + * @return null if the current transaction is an internal call to a system chaincode. */ SignedProposal getSignedProposal(); diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java index 88bf03614..c6df3d0f7 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java @@ -6,19 +6,19 @@ package org.hyperledger.fabric.shim; import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.logging.Logger; import org.hyperledger.fabric.Logging; import org.hyperledger.fabric.protos.peer.ChaincodeGrpc; import org.hyperledger.fabric.protos.peer.ChaincodeMessage; -import java.io.IOException; -import java.util.logging.Logger; - public class ChatChaincodeWithPeer extends ChaincodeGrpc.ChaincodeImplBase { private static Logger logger = Logger.getLogger(ChatChaincodeWithPeer.class.getName()); - private ChaincodeBase chaincodeBase; + private final ChaincodeBase chaincodeBase; ChatChaincodeWithPeer(final ChaincodeBase chaincodeBase) throws IOException { + super(); if (chaincodeBase == null) { throw new IOException("chaincodeBase can't be null"); } @@ -28,13 +28,14 @@ public class ChatChaincodeWithPeer extends ChaincodeGrpc.ChaincodeImplBase { } /** - * Chaincode as a server - peer establishes a connection to the chaincode as a client - * Currently only supports a stream connection. + * Chaincode as a server - peer establishes a connection to the chaincode as a client Currently only supports a + * stream connection. * * @param responseObserver * @return */ @Override + @SuppressWarnings("PMD.AvoidCatchingGenericException") public StreamObserver connect(final StreamObserver responseObserver) { if (responseObserver == null) { return null; @@ -43,7 +44,8 @@ public StreamObserver connect(final StreamObserver "catch exception while chaincodeBase.connectToPeer(responseObserver)." + Logging.formatError(e)); + logger.severe(() -> + "catch exception while chaincodeBase.connectToPeer(responseObserver)." + Logging.formatError(e)); return null; } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java index aa10efc31..9460dd22a 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java @@ -8,9 +8,7 @@ import java.io.IOException; -/** - * Common interface for grpc server. - */ +/** Common interface for grpc server. */ public interface GrpcServer { /** @@ -20,9 +18,7 @@ public interface GrpcServer { */ void start() throws IOException; - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ void stop(); /** diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java index a7073d78f..146793848 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java @@ -10,9 +10,7 @@ public class NettyChaincodeServer implements ChaincodeServer { - /** - * Server. - */ + /** Server. */ private final GrpcServer grpcServer; /** @@ -22,7 +20,9 @@ public class NettyChaincodeServer implements ChaincodeServer { * @param chaincodeServerProperties - setting for grpc server * @throws IOException */ - public NettyChaincodeServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) throws IOException { + public NettyChaincodeServer( + final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) + throws IOException { // create listener and grpc server grpcServer = new NettyGrpcServer(chaincodeBase, chaincodeServerProperties); } @@ -30,17 +30,17 @@ public NettyChaincodeServer(final ChaincodeBase chaincodeBase, final ChaincodeSe /** * run external chaincode server. * - * @throws IOException problem while start grpc server + * @throws IOException problem while start grpc server * @throws InterruptedException thrown when block and awaiting shutdown gprc server */ + @Override public void start() throws IOException, InterruptedException { grpcServer.start(); grpcServer.blockUntilShutdown(); } - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ + @Override public void stop() { grpcServer.stop(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java index 4d6e9c33e..00e7c2acf 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java @@ -6,23 +6,21 @@ package org.hyperledger.fabric.shim; - import io.grpc.Server; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ApplicationProtocolConfig; import io.grpc.netty.shaded.io.netty.handler.ssl.ApplicationProtocolNames; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -import java.util.logging.Logger; - import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.net.ssl.SSLException; -/** - * implementation grpc server with NettyGrpcServer. - */ +/** implementation grpc server with NettyGrpcServer. */ public final class NettyGrpcServer implements GrpcServer { private static final Logger LOGGER = Logger.getLogger(NettyGrpcServer.class.getName()); @@ -32,11 +30,12 @@ public final class NettyGrpcServer implements GrpcServer { /** * init netty grpc server. * - * @param chaincodeBase - chaincode implementation (invoke, init) + * @param chaincodeBase - chaincode implementation (invoke, init) * @param chaincodeServerProperties - setting for grpc server * @throws IOException */ - public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) throws IOException { + public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) + throws IOException { if (chaincodeBase == null) { throw new IllegalArgumentException("chaincode must be specified"); } @@ -45,7 +44,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP } chaincodeServerProperties.validate(); - final NettyServerBuilder serverBuilder = NettyServerBuilder.forAddress(chaincodeServerProperties.getServerAddress()) + final NettyServerBuilder serverBuilder = NettyServerBuilder.forAddress( + chaincodeServerProperties.getServerAddress()) .addService(new ChatChaincodeWithPeer(chaincodeBase)) .keepAliveTime(chaincodeServerProperties.getKeepAliveTimeMinutes(), TimeUnit.MINUTES) .keepAliveTimeout(chaincodeServerProperties.getKeepAliveTimeoutSeconds(), TimeUnit.SECONDS) @@ -56,65 +56,78 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP .maxInboundMessageSize(chaincodeServerProperties.getMaxInboundMessageSize()); if (chaincodeServerProperties.isTlsEnabled()) { - final File keyCertChainFile = Paths.get(chaincodeServerProperties.getKeyCertChainFile()).toFile(); - final File keyFile = Paths.get(chaincodeServerProperties.getKeyFile()).toFile(); - - SslContextBuilder sslContextBuilder; - if (chaincodeServerProperties.getKeyPassword() == null || chaincodeServerProperties.getKeyPassword().isEmpty()) { - sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile); - } else { - sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword()); - } - - ApplicationProtocolConfig apn = new ApplicationProtocolConfig( - ApplicationProtocolConfig.Protocol.ALPN, - ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, - ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, - ApplicationProtocolNames.HTTP_2); - sslContextBuilder.applicationProtocolConfig(apn); - - if (chaincodeServerProperties.getTrustCertCollectionFile() != null) { - final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile()).toFile(); - sslContextBuilder.clientAuth(ClientAuth.REQUIRE); - sslContextBuilder.trustManager(trustCertCollectionFile); - } - - serverBuilder.sslContext(sslContextBuilder.build()); + configureTls(serverBuilder, chaincodeServerProperties); } - LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>:\n"); - LOGGER.info("ServerAddress:" + chaincodeServerProperties.getServerAddress().toString()); - LOGGER.info("MaxInboundMetadataSize:" + chaincodeServerProperties.getMaxInboundMetadataSize()); - LOGGER.info("MaxInboundMessageSize:" + chaincodeServerProperties.getMaxInboundMessageSize()); - LOGGER.info("MaxConnectionAgeSeconds:" + chaincodeServerProperties.getMaxConnectionAgeSeconds()); - LOGGER.info("KeepAliveTimeoutSeconds:" + chaincodeServerProperties.getKeepAliveTimeoutSeconds()); - LOGGER.info("PermitKeepAliveTimeMinutes:" + chaincodeServerProperties.getPermitKeepAliveTimeMinutes()); - LOGGER.info("KeepAliveTimeMinutes:" + chaincodeServerProperties.getKeepAliveTimeMinutes()); - LOGGER.info("PermitKeepAliveWithoutCalls:" + chaincodeServerProperties.getPermitKeepAliveWithoutCalls()); - LOGGER.info("KeyPassword:" + chaincodeServerProperties.getKeyPassword()); - LOGGER.info("KeyCertChainFile:" + chaincodeServerProperties.getKeyCertChainFile()); - LOGGER.info("KeyFile:" + chaincodeServerProperties.getKeyFile()); - LOGGER.info("isTlsEnabled:" + chaincodeServerProperties.isTlsEnabled()); - LOGGER.info("\n"); + if (LOGGER.isLoggable(Level.INFO)) { + LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>:\n"); + LOGGER.info("ServerAddress:" + + chaincodeServerProperties.getServerAddress().toString()); + LOGGER.info("MaxInboundMetadataSize:" + chaincodeServerProperties.getMaxInboundMetadataSize()); + LOGGER.info("MaxInboundMessageSize:" + chaincodeServerProperties.getMaxInboundMessageSize()); + LOGGER.info("MaxConnectionAgeSeconds:" + chaincodeServerProperties.getMaxConnectionAgeSeconds()); + LOGGER.info("KeepAliveTimeoutSeconds:" + chaincodeServerProperties.getKeepAliveTimeoutSeconds()); + LOGGER.info("PermitKeepAliveTimeMinutes:" + chaincodeServerProperties.getPermitKeepAliveTimeMinutes()); + LOGGER.info("KeepAliveTimeMinutes:" + chaincodeServerProperties.getKeepAliveTimeMinutes()); + LOGGER.info("PermitKeepAliveWithoutCalls:" + chaincodeServerProperties.getPermitKeepAliveWithoutCalls()); + LOGGER.info("KeyPassword:" + chaincodeServerProperties.getKeyPassword()); + LOGGER.info("KeyCertChainFile:" + chaincodeServerProperties.getKeyCertChainFile()); + LOGGER.info("KeyFile:" + chaincodeServerProperties.getKeyFile()); + LOGGER.info("isTlsEnabled:" + chaincodeServerProperties.isTlsEnabled()); + LOGGER.info("\n"); + } this.server = serverBuilder.build(); } + private static void configureTls( + final NettyServerBuilder serverBuilder, final ChaincodeServerProperties chaincodeServerProperties) + throws SSLException { + final File keyCertChainFile = + Paths.get(chaincodeServerProperties.getKeyCertChainFile()).toFile(); + final File keyFile = Paths.get(chaincodeServerProperties.getKeyFile()).toFile(); + + final SslContextBuilder sslContextBuilder; + if (chaincodeServerProperties.getKeyPassword() == null + || chaincodeServerProperties.getKeyPassword().isEmpty()) { + sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile); + } else { + sslContextBuilder = + SslContextBuilder.forServer(keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword()); + } + + ApplicationProtocolConfig apn = new ApplicationProtocolConfig( + ApplicationProtocolConfig.Protocol.ALPN, + ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, + ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, + ApplicationProtocolNames.HTTP_2); + sslContextBuilder.applicationProtocolConfig(apn); + + if (chaincodeServerProperties.getTrustCertCollectionFile() != null) { + final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile()) + .toFile(); + sslContextBuilder.clientAuth(ClientAuth.REQUIRE); + sslContextBuilder.trustManager(trustCertCollectionFile); + } + + serverBuilder.sslContext(sslContextBuilder.build()); + } + /** * start grpc server. * * @throws IOException */ + @SuppressWarnings("PMD.SystemPrintln") + @Override public void start() throws IOException { LOGGER.info("start grpc server"); - Runtime.getRuntime() - .addShutdownHook( - new Thread(() -> { - // Use stderr here since the logger may have been reset by its JVM shutdown hook. - System.err.println("*** shutting down gRPC server since JVM is shutting down"); - NettyGrpcServer.this.stop(); - System.err.println("*** server shut down"); - })); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + // Use stderr here since the logger may have been reset by its JVM shutdown hook. + System.err.println("*** shutting down gRPC server since JVM is shutting down"); + stop(); + System.err.println("*** server shut down"); + })); server.start(); } @@ -123,14 +136,14 @@ public void start() throws IOException { * * @throws InterruptedException */ + @Override public void blockUntilShutdown() throws InterruptedException { LOGGER.info("Waits for the server to become terminated."); server.awaitTermination(); } - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ + @Override public void stop() { LOGGER.info("shutdown now grpc server."); server.shutdownNow(); diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java index c46e1a788..ab7419fa3 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java @@ -14,8 +14,7 @@ public final class ResponseUtils { private static Logger logger = Logger.getLogger(ResponseUtils.class.getName()); - private ResponseUtils() { - } + private ResponseUtils() {} /** * @param message @@ -26,9 +25,7 @@ public static Chaincode.Response newSuccessResponse(final String message, final return new Chaincode.Response(SUCCESS, message, payload); } - /** - * @return Chaincode.Response - */ + /** @return Chaincode.Response */ public static Chaincode.Response newSuccessResponse() { return newSuccessResponse(null, null); } @@ -58,9 +55,7 @@ public static Chaincode.Response newErrorResponse(final String message, final by return new Chaincode.Response(INTERNAL_SERVER_ERROR, message, payload); } - /** - * @return Chaincode.Response - */ + /** @return Chaincode.Response */ public static Chaincode.Response newErrorResponse() { return newErrorResponse(null, null); } @@ -90,17 +85,12 @@ public static Chaincode.Response newErrorResponse(final Throwable throwable) { // logged logger.error(() -> logger.formatError(throwable)); - String message = null; - byte[] payload = null; if (throwable instanceof ChaincodeException) { - message = throwable.getMessage(); - payload = ((ChaincodeException) throwable).getPayload(); + String message = throwable.getMessage(); + byte[] payload = ((ChaincodeException) throwable).getPayload(); return new Chaincode.Response(INTERNAL_SERVER_ERROR, message, payload); - } else { - message = "Unexpected error"; - return ResponseUtils.newErrorResponse(message, payload); } - + return newErrorResponse("Unexpected error", null); } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java index a7b250205..df22a7b95 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java @@ -10,10 +10,9 @@ import java.util.Map; /** - * StateBasedEndorsement provides a set of convenience methods to create and - * modify a state-based endorsement policy. Endorsement policies created by this - * convenience layer will always be a logical AND of "ORG.peer" principals for - * one or more ORGs specified by the caller. + * StateBasedEndorsement provides a set of convenience methods to create and modify a state-based endorsement policy. + * Endorsement policies created by this convenience layer will always be a logical AND of "ORG.peer" principals for one + * or more ORGs specified by the caller. */ public interface StateBasedEndorsement { /** @@ -24,20 +23,18 @@ public interface StateBasedEndorsement { byte[] policy(); /** - * Adds the specified orgs to the list of orgs that are required to endorse. All - * orgs MSP role types will be set to the role that is specified in the first - * parameter. Among other aspects the desired role depends on the channel's - * configuration: if it supports node OUs, it is likely going to be the PEER - * role, while the MEMBER role is the suited one if it does not. + * Adds the specified orgs to the list of orgs that are required to endorse. All orgs MSP role types will be set to + * the role that is specified in the first parameter. Among other aspects the desired role depends on the channel's + * configuration: if it supports node OUs, it is likely going to be the PEER role, while the MEMBER role is the + * suited one if it does not. * - * @param roleType the MSP role type + * @param roleType the MSP role type * @param organizations the list of organizations */ void addOrgs(RoleType roleType, String... organizations); /** - * deletes the specified channel orgs from the existing key-level endorsement - * policy for this KVS key. + * deletes the specified channel orgs from the existing key-level endorsement policy for this KVS key. * * @param organizations the list of organizations */ @@ -50,43 +47,34 @@ public interface StateBasedEndorsement { */ List listOrgs(); - /** - * RoleType of an endorsement policy's identity. - */ + /** RoleType of an endorsement policy's identity. */ + @SuppressWarnings("PMD.FieldNamingConventions") enum RoleType { - /** - * RoleTypeMember identifies an org's member identity. - */ + /** RoleTypeMember identifies an org's member identity. */ RoleTypeMember("MEMBER"), - /** - * RoleTypePeer identifies an org's peer identity. - */ + /** RoleTypePeer identifies an org's peer identity. */ RoleTypePeer("PEER"); + private static final Map reverseLookup = new HashMap<>(); + + static { + for (final RoleType item : values()) { + reverseLookup.put(item.getVal(), item); + } + } + private final String val; RoleType(final String val) { this.val = val; } - /** - * - * @return String value - */ + /** @return String value */ public String getVal() { return val; } - private static Map reverseLookup = new HashMap<>(); - - static { - for (final RoleType item : RoleType.values()) { - reverseLookup.put(item.getVal(), item); - } - } - /** - * * @param val * @return RoleType */ diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java index da1db8ca5..9a040a59d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java @@ -7,26 +7,18 @@ import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement; -/** - * Factory for {@link StateBasedEndorsement} objects. - */ +/** Factory for {@link StateBasedEndorsement} objects. */ public class StateBasedEndorsementFactory { - private static StateBasedEndorsementFactory instance; + private static final StateBasedEndorsementFactory INSTANCE = new StateBasedEndorsementFactory(); - /** - * - * @return Endorsement Factory - */ - public static synchronized StateBasedEndorsementFactory getInstance() { - if (instance == null) { - instance = new StateBasedEndorsementFactory(); - } - return instance; + /** @return Endorsement Factory */ + public static StateBasedEndorsementFactory getInstance() { + return INSTANCE; } /** - * Constructs a state-based endorsement policy from a given serialized EP byte - * array. If the byte array is empty, a new EP is created. + * Constructs a state-based endorsement policy from a given serialized EP byte array. If the byte array is empty, a + * new EP is created. * * @param ep serialized endorsement policy * @return New StateBasedEndorsement instance diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java index 6dbdbd263..1226a3cb7 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java @@ -5,12 +5,12 @@ */ package org.hyperledger.fabric.shim.ext.sbe.impl; +import com.google.protobuf.InvalidProtocolBufferException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.common.MSPPrincipal; @@ -21,13 +21,10 @@ import org.hyperledger.fabric.protos.common.SignaturePolicyEnvelope; import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement; -import com.google.protobuf.InvalidProtocolBufferException; - -/** - * Implements {@link StateBasedEndorsement}. - */ +/** Implements {@link StateBasedEndorsement}. */ public final class StateBasedEndorsementImpl implements StateBasedEndorsement { - private static Log logger = LogFactory.getLog(StateBasedEndorsementImpl.class); + @SuppressWarnings("PMD.ProperLogger") // PMD 7.7.0 reports a false positive + private static final Log LOGGER = LogFactory.getLog(StateBasedEndorsementImpl.class); private final Map orgs = new HashMap<>(); @@ -44,7 +41,6 @@ public final class StateBasedEndorsementImpl implements StateBasedEndorsement { } catch (final InvalidProtocolBufferException e) { throw new IllegalArgumentException("error unmarshalling endorsement policy bytes", e); } - } @Override @@ -81,7 +77,9 @@ public List listOrgs() { } private void setMSPIDsFromSP(final SignaturePolicyEnvelope spe) { - spe.getIdentitiesList().stream().filter(identity -> Classification.ROLE.equals(identity.getPrincipalClassification())).forEach(this::addOrg); + spe.getIdentitiesList().stream() + .filter(identity -> Classification.ROLE.equals(identity.getPrincipalClassification())) + .forEach(this::addOrg); } private void addOrg(final MSPPrincipal identity) { @@ -89,7 +87,7 @@ private void addOrg(final MSPPrincipal identity) { final MSPRole mspRole = MSPRole.parseFrom(identity.getPrincipal()); orgs.put(mspRole.getMspIdentifier(), mspRole.getRole()); } catch (final InvalidProtocolBufferException e) { - logger.warn("error unmarshalling msp principal"); + LOGGER.warn("error unmarshalling msp principal"); throw new IllegalArgumentException("error unmarshalling msp principal", e); } } @@ -102,15 +100,23 @@ private SignaturePolicyEnvelope policyFromMSPIDs() { final List sigpolicy = new ArrayList<>(); for (int i = 0; i < mspids.size(); i++) { final String mspid = mspids.get(i); - principals.add(MSPPrincipal.newBuilder().setPrincipalClassification(Classification.ROLE) - .setPrincipal(MSPRole.newBuilder().setMspIdentifier(mspid).setRole(orgs.get(mspid)).build().toByteString()).build()); + principals.add(MSPPrincipal.newBuilder() + .setPrincipalClassification(Classification.ROLE) + .setPrincipal(MSPRole.newBuilder() + .setMspIdentifier(mspid) + .setRole(orgs.get(mspid)) + .build() + .toByteString()) + .build()); sigpolicy.add(StateBasedEndorsementUtils.signedBy(i)); } // create the policy: it requires exactly 1 signature from all of the principals - return SignaturePolicyEnvelope.newBuilder().setVersion(0).setRule(StateBasedEndorsementUtils.nOutOf(mspids.size(), sigpolicy)) - .addAllIdentities(principals).build(); + return SignaturePolicyEnvelope.newBuilder() + .setVersion(0) + .setRule(StateBasedEndorsementUtils.nOutOf(mspids.size(), sigpolicy)) + .addAllIdentities(principals) + .build(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java index 4234a70c1..845056bcd 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java @@ -7,7 +7,6 @@ import java.util.Arrays; import java.util.List; - import org.hyperledger.fabric.protos.common.MSPPrincipal; import org.hyperledger.fabric.protos.common.MSPPrincipal.Classification; import org.hyperledger.fabric.protos.common.MSPRole; @@ -16,15 +15,10 @@ import org.hyperledger.fabric.protos.common.SignaturePolicy.NOutOf; import org.hyperledger.fabric.protos.common.SignaturePolicyEnvelope; -/** - * Utility to create {@link SignaturePolicy} and - * {@link SignaturePolicyEnvelope}. - */ +/** Utility to create {@link SignaturePolicy} and {@link SignaturePolicyEnvelope}. */ public final class StateBasedEndorsementUtils { - private StateBasedEndorsementUtils() { - - } + private StateBasedEndorsementUtils() {} /** * Creates a SignaturePolicy requiring a given signer's signature. @@ -39,20 +33,21 @@ static SignaturePolicy signedBy(final int index) { /** * Create a policy. * - * Creates a policy which requires N out of the slice of policies to evaluate to - * true + *

Creates a policy which requires N out of the slice of policies to evaluate to true * * @param n * @param policies * @return SignaturePolicy */ static SignaturePolicy nOutOf(final int n, final List policies) { - return SignaturePolicy.newBuilder().setNOutOf(NOutOf.newBuilder().setN(n).addAllRules(policies).build()).build(); + return SignaturePolicy.newBuilder() + .setNOutOf(NOutOf.newBuilder().setN(n).addAllRules(policies).build()) + .build(); } /** - * Creates a {@link SignaturePolicyEnvelope} requiring 1 signature from any - * fabric entity, having the passed role, of the specified MSP. + * Creates a {@link SignaturePolicyEnvelope} requiring 1 signature from any fabric entity, having the passed role, + * of the specified MSP. * * @param mspId * @param role @@ -60,13 +55,21 @@ static SignaturePolicy nOutOf(final int n, final List policies) */ static SignaturePolicyEnvelope signedByFabricEntity(final String mspId, final MSPRoleType role) { // specify the principal: it's a member of the msp we just found - final MSPPrincipal principal = MSPPrincipal.newBuilder().setPrincipalClassification(Classification.ROLE) - .setPrincipal(MSPRole.newBuilder().setMspIdentifier(mspId).setRole(role).build().toByteString()).build(); + final MSPPrincipal principal = MSPPrincipal.newBuilder() + .setPrincipalClassification(Classification.ROLE) + .setPrincipal(MSPRole.newBuilder() + .setMspIdentifier(mspId) + .setRole(role) + .build() + .toByteString()) + .build(); // create the policy: it requires exactly 1 signature from the first (and only) // principal - return SignaturePolicyEnvelope.newBuilder().setVersion(0).setRule(nOutOf(1, Arrays.asList(signedBy(0)))).addIdentities(principal).build(); - + return SignaturePolicyEnvelope.newBuilder() + .setVersion(0) + .setRule(nOutOf(1, Arrays.asList(signedBy(0)))) + .addIdentities(principal) + .build(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java index f4f3bb511..329c3a350 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java @@ -1,6 +1,6 @@ -/* - * Copyright 2023 IBM All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.hyperledger.fabric.shim.ext.sbe.impl; +/* + * Copyright 2023 IBM All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.fabric.shim.ext.sbe.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java index 50735e070..15c86c685 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * Provides an interface for creating and modifying state-based endorsement policies. - */ +/** Provides an interface for creating and modifying state-based endorsement policies. */ package org.hyperledger.fabric.shim.ext.sbe; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java index 8cafebdbe..1f502b366 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java @@ -9,31 +9,30 @@ import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.ERROR; import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.RESPONSE; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.StatusCode; +import java.security.NoSuchAlgorithmException; import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.logging.Logger; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.StatusCode; import org.hyperledger.fabric.Logging; +import org.hyperledger.fabric.contract.ContractRuntimeException; import org.hyperledger.fabric.protos.peer.ChaincodeMessage; import org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type; import org.hyperledger.fabric.shim.Chaincode; import org.hyperledger.fabric.shim.ChaincodeStub; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; import org.hyperledger.fabric.traces.Traces; -/** - * A 'Callable' implementation the has the job of invoking the chaincode, and - * matching the response and requests. - */ +/** A 'Callable' implementation the has the job of invoking the chaincode, and matching the response and requests. */ +@SuppressWarnings("PMD.MoreThanOneLogger") public class ChaincodeInvocationTask implements Callable { - private static Logger logger = Logger.getLogger(ChaincodeInvocationTask.class.getName()); - private static Logger perfLogger = Logger.getLogger(Logging.PERFLOGGER); + private static final Logger LOGGER = Logger.getLogger(ChaincodeInvocationTask.class.getName()); + private static final Logger PERFLOGGER = Logger.getLogger(Logging.PERFLOGGER); private final String key; private final Type type; @@ -45,23 +44,22 @@ public class ChaincodeInvocationTask implements Callable { // up if there's no body waiting. // // Usual case should be the main thread is waiting for something to come back - private final ArrayBlockingQueue postbox = new ArrayBlockingQueue<>(2, true); + private final BlockingQueue postbox = new ArrayBlockingQueue<>(2, true); private final ChaincodeMessage message; private final Chaincode chaincode; /** - * - * @param message The incoming message that has triggered this task into - * execution - * @param type Is this init or invoke? (v2 Fabric deprecates init) - * @param outgoingMessage The Consumer functional interface to send any requests - * for ledger state - * @param chaincode A instance of the end users chaincode - * + * @param message The incoming message that has triggered this task into execution + * @param type Is this init or invoke? (v2 Fabric deprecates init) + * @param outgoingMessage The Consumer functional interface to send any requests for ledger state + * @param chaincode A instance of the end users chaincode */ - public ChaincodeInvocationTask(final ChaincodeMessage message, final Type type, - final Consumer outgoingMessage, final Chaincode chaincode) { + public ChaincodeInvocationTask( + final ChaincodeMessage message, + final Type type, + final Consumer outgoingMessage, + final Chaincode chaincode) { this.key = message.getChannelId() + message.getTxid(); this.type = type; @@ -71,17 +69,16 @@ public ChaincodeInvocationTask(final ChaincodeMessage message, final Type type, this.message = message; } - /** - * Main method to power the invocation of the chaincode. - */ + /** Main method to power the invocation of the chaincode. */ @Override + @SuppressWarnings("PMD.AvoidCatchingGenericException") public ChaincodeMessage call() { ChaincodeMessage finalResponseMessage; Span span = null; try { try { - perfLogger.fine(() -> "> task:start TX::" + this.txId); + PERFLOGGER.fine(() -> "> task:start TX::" + this.txId); // A key interface for the chaincode's invoke() method implementation // is the 'ChaincodeStub' interface. An instance of this is created @@ -95,8 +92,7 @@ public ChaincodeMessage call() { // result is what will be sent to the peer as a response to this invocation final Chaincode.Response result; - - perfLogger.fine(() -> "> task:invoke TX::" + this.txId); + PERFLOGGER.fine(() -> "> task:invoke TX::" + this.txId); // Call chaincode's invoke // Note in Fabric v2, there won't be any INIT @@ -106,28 +102,31 @@ public ChaincodeMessage call() { result = chaincode.invoke(stub); } - perfLogger.fine(() -> "< task:invoke TX::" + this.txId); + PERFLOGGER.fine(() -> "< task:invoke TX::" + this.txId); if (result.getStatus().getCode() >= Chaincode.Response.Status.INTERNAL_SERVER_ERROR.getCode()) { // Send ERROR with entire result.Message as payload - logger.severe(() -> String.format("[%-8.8s] Invoke failed with error code %d. Sending %s", + LOGGER.severe(() -> String.format( + "[%-8.8s] Invoke failed with error code %d. Sending %s", message.getTxid(), result.getStatus().getCode(), ERROR)); - finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(message.getChannelId(), - message.getTxid(), result, stub.getEvent()); + finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage( + message.getChannelId(), message.getTxid(), result, stub.getEvent()); if (span != null) { span.setStatus(StatusCode.ERROR, result.getMessage()); } } else { // Send COMPLETED with entire result as payload - logger.fine(() -> String.format("[%-8.8s] Invoke succeeded. Sending %s", message.getTxid(), COMPLETED)); - finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(message.getChannelId(), - message.getTxid(), result, stub.getEvent()); + LOGGER.fine( + () -> String.format("[%-8.8s] Invoke succeeded. Sending %s", message.getTxid(), COMPLETED)); + finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage( + message.getChannelId(), message.getTxid(), result, stub.getEvent()); } - } catch (InvalidProtocolBufferException | RuntimeException e) { - logger.severe(() -> String.format("[%-8.8s] Invoke failed. Sending %s: %s", message.getTxid(), ERROR, e)); - finalResponseMessage = ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(), - message.getTxid(), e); + } catch (InvalidProtocolBufferException | NoSuchAlgorithmException | RuntimeException e) { + LOGGER.severe( + () -> String.format("[%-8.8s] Invoke failed. Sending %s: %s", message.getTxid(), ERROR, e)); + finalResponseMessage = + ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(), message.getTxid(), e); if (span != null) { span.setStatus(StatusCode.ERROR, e.getMessage()); } @@ -135,7 +134,7 @@ public ChaincodeMessage call() { // send the final response message to the peer outgoingMessageConsumer.accept(finalResponseMessage); - perfLogger.fine(() -> "< task:end TX::" + this.txId); + PERFLOGGER.fine(() -> "< task:end TX::" + this.txId); } finally { if (span != null) { span.end(); @@ -157,19 +156,30 @@ public String getTxKey() { /** * Use the Key as to determine equality. * - * @param task + * @param other * @return equality */ - public boolean equals(final ChaincodeInvocationTask task) { - return key.equals(task.getTxKey()); + @Override + public boolean equals(final Object other) { + if (!(other instanceof ChaincodeInvocationTask)) { + return false; + } + + ChaincodeInvocationTask that = (ChaincodeInvocationTask) other; + return this.key.equals(that.getTxKey()); + } + + @Override + public int hashCode() { + return key.hashCode(); } /** - * Posts the message that the peer has responded with to this task's request - * Uses an 'ArrayBlockingQueue'. This lets the producer post messages without waiting - * for the consumer. And the consumer can block until a message is posted. + * Posts the message that the peer has responded with to this task's request Uses an 'ArrayBlockingQueue'. This lets + * the producer post messages without waiting for the consumer. And the consumer can block until a message is + * posted. * - * In this case the data is only passed to the executing tasks. + *

In this case the data is only passed to the executing tasks. * * @param msg Chaincode message to pass pack * @throws InterruptedException should something really really go wrong @@ -182,50 +192,49 @@ public void postMessage(final ChaincodeMessage msg) throws InterruptedException /** * Send the chaincode message back to the peer. * - * Implementation of the Functional interface 'InvokeChaincodeSupport' + *

Implementation of the Functional interface 'InvokeChaincodeSupport' * - * It will send the message, via the outgoingMessageConsumer, and then block on - * the 'Exchanger' to wait for the response to come. + *

It will send the message, via the outgoingMessageConsumer, and then block on the 'Exchanger' to wait for the + * response to come. * - * This Exchange is an atomic operation between the thread that is running this - * task, and the thread that is handling the communication from the peer. + *

This Exchange is an atomic operation between the thread that is running this task, and the thread that is + * handling the communication from the peer. * * @param message The chaincode message from the peer * @return ByteString to be parsed by the caller - * */ protected ByteString invoke(final ChaincodeMessage message) { // send the message - logger.fine(() -> "Task Sending message to the peer " + message.getTxid()); + LOGGER.fine(() -> "Task Sending message to the peer " + message.getTxid()); outgoingMessageConsumer.accept(message); // wait for response ChaincodeMessage response; try { - perfLogger.fine(() -> "> task:answer TX::" + message.getTxid()); + PERFLOGGER.fine(() -> "> task:answer TX::" + message.getTxid()); response = postbox.take(); - perfLogger.fine(() -> "< task:answer TX::" + message.getTxid()); + PERFLOGGER.fine(() -> "< task:answer TX::" + message.getTxid()); } catch (final InterruptedException e) { - logger.severe(() -> "Interrupted exchanging messages "); - throw new RuntimeException(String.format("[%-8.8s]InterruptedException received.", txId), e); + LOGGER.severe(() -> "Interrupted exchanging messages "); + throw new ContractRuntimeException(String.format("[%-8.8s]InterruptedException received.", txId), e); } // handle response switch (response.getType()) { case RESPONSE: - logger.fine(() -> String.format("[%-8.8s] Successful response received.", txId)); + LOGGER.fine(() -> String.format("[%-8.8s] Successful response received.", txId)); return response.getPayload(); case ERROR: - logger.severe(() -> String.format("[%-8.8s] Unsuccessful response received.", txId)); - throw new RuntimeException(String.format("[%-8.8s]Unsuccessful response received.", txId)); + LOGGER.severe(() -> String.format("[%-8.8s] Unsuccessful response received.", txId)); + throw new ContractRuntimeException(String.format("[%-8.8s]Unsuccessful response received.", txId)); default: - logger.severe(() -> String.format("[%-8.8s] Unexpected %s response received. Expected %s or %s.", txId, - response.getType(), RESPONSE, ERROR)); - throw new RuntimeException(String.format("[%-8.8s] Unexpected %s response received. Expected %s or %s.", + LOGGER.severe(() -> String.format( + "[%-8.8s] Unexpected %s response received. Expected %s or %s.", + txId, response.getType(), RESPONSE, ERROR)); + throw new IllegalStateException(String.format( + "[%-8.8s] Unexpected %s response received. Expected %s or %s.", txId, response.getType(), RESPONSE, ERROR)); } - } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java index 831e22773..199a1b75c 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java @@ -16,11 +16,11 @@ import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.PUT_STATE_METADATA; import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER; +import com.google.protobuf.ByteString; import java.io.PrintWriter; import java.io.StringWriter; - -import org.hyperledger.fabric.protos.peer.ChaincodeID; import org.hyperledger.fabric.protos.peer.ChaincodeEvent; +import org.hyperledger.fabric.protos.peer.ChaincodeID; import org.hyperledger.fabric.protos.peer.ChaincodeMessage; import org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type; import org.hyperledger.fabric.protos.peer.DelState; @@ -28,82 +28,167 @@ import org.hyperledger.fabric.protos.peer.GetStateMetadata; import org.hyperledger.fabric.protos.peer.PutState; import org.hyperledger.fabric.protos.peer.PutStateMetadata; -import org.hyperledger.fabric.protos.peer.StateMetadata; import org.hyperledger.fabric.protos.peer.Response; import org.hyperledger.fabric.protos.peer.Response.Builder; +import org.hyperledger.fabric.protos.peer.StateMetadata; import org.hyperledger.fabric.shim.Chaincode; -import com.google.protobuf.ByteString; - public final class ChaincodeMessageFactory { - private ChaincodeMessageFactory() { - } - - protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { - return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); - } - - protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { - return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); - } - - protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { - return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); - } - - protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, + private ChaincodeMessageFactory() {} + + static ChaincodeMessage newGetPrivateDataHashEventMessage( + final String channelId, final String txId, final String collection, final String key) { + return newEventMessage( + GET_PRIVATE_DATA_HASH, + channelId, + txId, + GetState.newBuilder() + .setCollection(collection) + .setKey(key) + .build() + .toByteString()); + } + + static ChaincodeMessage newGetStateEventMessage( + final String channelId, final String txId, final String collection, final String key) { + return newEventMessage( + GET_STATE, + channelId, + txId, + GetState.newBuilder() + .setCollection(collection) + .setKey(key) + .build() + .toByteString()); + } + + static ChaincodeMessage newGetStateMetadataEventMessage( + final String channelId, final String txId, final String collection, final String key) { + return newEventMessage( + GET_STATE_METADATA, + channelId, + txId, + GetStateMetadata.newBuilder() + .setCollection(collection) + .setKey(key) + .build() + .toByteString()); + } + + static ChaincodeMessage newPutStateEventMessage( + final String channelId, + final String txId, + final String collection, + final String key, final ByteString value) { - return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); - } - - protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, - final String metakey, final ByteString value) { - return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) - .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); - } - - protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { - return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); - } - - protected static ChaincodeMessage newPurgeStateEventMessage(final String channelId, final String txId, final String collection, final String key) { - return newEventMessage(Type.PURGE_PRIVATE_DATA, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); - } - - protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { + return newEventMessage( + PUT_STATE, + channelId, + txId, + PutState.newBuilder() + .setCollection(collection) + .setKey(key) + .setValue(value) + .build() + .toByteString()); + } + + static ChaincodeMessage newPutStateMetadataEventMessage( + final String channelId, + final String txId, + final String collection, + final String key, + final String metakey, + final ByteString value) { + return newEventMessage( + PUT_STATE_METADATA, + channelId, + txId, + PutStateMetadata.newBuilder() + .setCollection(collection) + .setKey(key) + .setMetadata(StateMetadata.newBuilder() + .setMetakey(metakey) + .setValue(value) + .build()) + .build() + .toByteString()); + } + + static ChaincodeMessage newDeleteStateEventMessage( + final String channelId, final String txId, final String collection, final String key) { + return newEventMessage( + DEL_STATE, + channelId, + txId, + DelState.newBuilder() + .setCollection(collection) + .setKey(key) + .build() + .toByteString()); + } + + static ChaincodeMessage newPurgeStateEventMessage( + final String channelId, final String txId, final String collection, final String key) { + return newEventMessage( + Type.PURGE_PRIVATE_DATA, + channelId, + txId, + DelState.newBuilder() + .setCollection(collection) + .setKey(key) + .build() + .toByteString()); + } + + static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } - protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message) { + static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message) { return newErrorEventMessage(channelId, txId, message, null); } - protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message, final ChaincodeEvent event) { + static ChaincodeMessage newErrorEventMessage( + final String channelId, final String txId, final String message, final ChaincodeEvent event) { return newEventMessage(ERROR, channelId, txId, ByteString.copyFromUtf8(message), event); } - protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, - final ChaincodeEvent event) { - final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); - return message; + static ChaincodeMessage newCompletedEventMessage( + final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { + return newEventMessage( + COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); } - protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { + static ChaincodeMessage newInvokeChaincodeMessage( + final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } - protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { - return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); + static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { + return ChaincodeMessage.newBuilder() + .setType(REGISTER) + .setPayload(chaincodeId.toByteString()) + .build(); } - protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { + static ChaincodeMessage newEventMessage( + final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } - protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload, + static ChaincodeMessage newEventMessage( + final Type type, + final String channelId, + final String txId, + final ByteString payload, final ChaincodeEvent event) { - final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder().setType(type).setChannelId(channelId).setTxid(txId).setPayload(payload); + final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder() + .setType(type) + .setChannelId(channelId) + .setTxid(txId) + .setPayload(payload); if (event != null) { builder.setChaincodeEvent(event); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java index 7216ad307..b55a64f4f 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java @@ -5,33 +5,28 @@ */ package org.hyperledger.fabric.shim.impl; +import io.grpc.ClientInterceptor; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.logging.Logger; - -import io.grpc.ClientInterceptor; import org.hyperledger.fabric.Logging; import org.hyperledger.fabric.protos.peer.ChaincodeMessage; import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc; import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc.ChaincodeSupportStub; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.stub.StreamObserver; import org.hyperledger.fabric.traces.Traces; public class ChaincodeSupportClient { private static final int DEFAULT_TIMEOUT = 5; - private static final Logger LOGGER = Logger.getLogger(ChaincodeSupportClient.class.getName()); - private static Logger perflogger = Logger.getLogger(Logging.PERFLOGGER); + private static final Logger PERFLOGGER = Logger.getLogger(Logging.PERFLOGGER); private final ManagedChannel channel; private final ChaincodeSupportStub stub; - /** - * @param channelBuilder - */ + /** @param channelBuilder */ public ChaincodeSupportClient(final ManagedChannelBuilder channelBuilder) { ClientInterceptor interceptor = Traces.getProvider().createInterceptor(); if (interceptor != null) { @@ -41,10 +36,7 @@ public ChaincodeSupportClient(final ManagedChannelBuilder channelBuilder) { this.stub = ChaincodeSupportGrpc.newStub(channel); } - /** - * - * @param itm - */ + /** @param itm */ public void shutdown(final InvocationTaskManager itm) { // first shutdown the thread pool @@ -59,16 +51,15 @@ public void shutdown(final InvocationTaskManager itm) { channel.shutdownNow(); Thread.currentThread().interrupt(); } - } /** - * * @param itm * @param requestObserver * @throws IOException verify parameters error */ - public void start(final InvocationTaskManager itm, final StreamObserver requestObserver) throws IOException { + public void start(final InvocationTaskManager itm, final StreamObserver requestObserver) + throws IOException { if (requestObserver == null) { throw new IOException("StreamObserver 'requestObserver' for chat with peer can't be null"); } @@ -85,19 +76,14 @@ public void start(final InvocationTaskManager itm, final StreamObserver consumer = new Consumer() { - - // create a lock, with fair property - private final ReentrantLock lock = new ReentrantLock(true); - - @Override - public void accept(final ChaincodeMessage t) { - lock.lock(); - perflogger.fine(() -> "> sendToPeer TX::" + t.getTxid()); - requestObserver.onNext(t); - perflogger.fine(() -> "< sendToPeer TX::" + t.getTxid()); - lock.unlock(); - } + // create a lock, with fair property + final ReentrantLock lock = new ReentrantLock(true); + final Consumer consumer = t -> { + lock.lock(); + PERFLOGGER.fine(() -> "> sendToPeer TX::" + t.getTxid()); + requestObserver.onNext(t); + PERFLOGGER.fine(() -> "< sendToPeer TX::" + t.getTxid()); + lock.unlock(); }; // Pass a Consumer interface back to the the task manager. This is for tasks to @@ -105,11 +91,13 @@ public void accept(final ChaincodeMessage t) { // // NOTE the register() - very important - as this triggers the ITM to send the // first message to the peer; otherwise the both sides will sit there waiting - itm.setResponseConsumer(consumer).register(); + itm.setResponseConsumer(consumer); + itm.register(); } /** * ChaincodeSupportStub. + * * @return stub */ public ChaincodeSupportStub getStub() { diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java index 08783272e..ec0b1ffcc 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java @@ -13,6 +13,10 @@ import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.GET_QUERY_RESULT; import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.GET_STATE_BY_RANGE; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Timestamp; +import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; @@ -22,31 +26,31 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collectors; - import org.hyperledger.fabric.protos.common.ChannelHeader; import org.hyperledger.fabric.protos.common.Header; import org.hyperledger.fabric.protos.common.HeaderType; import org.hyperledger.fabric.protos.common.SignatureHeader; import org.hyperledger.fabric.protos.ledger.queryresult.KV; +import org.hyperledger.fabric.protos.peer.ChaincodeEvent; import org.hyperledger.fabric.protos.peer.ChaincodeID; import org.hyperledger.fabric.protos.peer.ChaincodeInput; -import org.hyperledger.fabric.protos.peer.ChaincodeSpec; -import org.hyperledger.fabric.protos.peer.ChaincodeEvent; -import org.hyperledger.fabric.protos.peer.QueryMetadata; import org.hyperledger.fabric.protos.peer.ChaincodeMessage; +import org.hyperledger.fabric.protos.peer.ChaincodeProposalPayload; +import org.hyperledger.fabric.protos.peer.ChaincodeSpec; import org.hyperledger.fabric.protos.peer.GetQueryResult; import org.hyperledger.fabric.protos.peer.GetState; import org.hyperledger.fabric.protos.peer.GetStateByRange; -import org.hyperledger.fabric.protos.peer.QueryResultBytes; -import org.hyperledger.fabric.protos.peer.StateMetadataResult; -import org.hyperledger.fabric.protos.peer.ChaincodeProposalPayload; +import org.hyperledger.fabric.protos.peer.MetaDataKeys; import org.hyperledger.fabric.protos.peer.Proposal; -import org.hyperledger.fabric.protos.peer.SignedProposal; +import org.hyperledger.fabric.protos.peer.QueryMetadata; +import org.hyperledger.fabric.protos.peer.QueryResultBytes; import org.hyperledger.fabric.protos.peer.Response; -import org.hyperledger.fabric.protos.peer.MetaDataKeys; +import org.hyperledger.fabric.protos.peer.SignedProposal; +import org.hyperledger.fabric.protos.peer.StateMetadataResult; import org.hyperledger.fabric.shim.Chaincode; import org.hyperledger.fabric.shim.ChaincodeStub; import org.hyperledger.fabric.shim.ledger.CompositeKey; @@ -55,10 +59,7 @@ import org.hyperledger.fabric.shim.ledger.QueryResultsIterator; import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata; -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Timestamp; - +@SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.GodClass"}) class InvocationStubImpl implements ChaincodeStub { private static final String UNSPECIFIED_START_KEY = new String(Character.toChars(0x000001)); @@ -67,6 +68,24 @@ class InvocationStubImpl implements ChaincodeStub { public static final String MAX_UNICODE_RUNE = "\udbff\udfff"; private static final String CORE_PEER_LOCALMSPID = "CORE_PEER_LOCALMSPID"; + + private static final Function + QUERY_RESULT_BYTES_TO_KEY_MODIFICATION = queryResultBytes -> { + try { + return org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.parseFrom( + queryResultBytes.getResultBytes()); + } catch (final InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + }; + private static final Function QUERY_RESULT_BYTES_TO_KV = queryResultBytes -> { + try { + return KV.parseFrom(queryResultBytes.getResultBytes()); + } catch (final InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + }; + private final String channelId; private final String txId; private final ChaincodeInvocationTask handler; @@ -79,13 +98,12 @@ class InvocationStubImpl implements ChaincodeStub { private ChaincodeEvent event; /** - * * @param message * @param handler * @throws InvalidProtocolBufferException */ InvocationStubImpl(final ChaincodeMessage message, final ChaincodeInvocationTask handler) - throws InvalidProtocolBufferException { + throws InvalidProtocolBufferException, NoSuchAlgorithmException { this.channelId = message.getChannelId(); this.txId = message.getTxid(); this.handler = handler; @@ -93,30 +111,35 @@ class InvocationStubImpl implements ChaincodeStub { this.args = Collections.unmodifiableList(input.getArgsList()); this.signedProposal = message.getProposal(); - if (this.signedProposal == null || this.signedProposal.getProposalBytes().isEmpty()) { + if (this.signedProposal.getProposalBytes().isEmpty()) { this.creator = null; this.txTimestamp = null; this.transientMap = Collections.emptyMap(); this.binding = null; } else { - try { - final Proposal proposal = Proposal.parseFrom(signedProposal.getProposalBytes()); - final Header header = Header.parseFrom(proposal.getHeader()); - final ChannelHeader channelHeader = ChannelHeader.parseFrom(header.getChannelHeader()); - validateProposalType(channelHeader); - final SignatureHeader signatureHeader = SignatureHeader.parseFrom(header.getSignatureHeader()); - final ChaincodeProposalPayload chaincodeProposalPayload = ChaincodeProposalPayload - .parseFrom(proposal.getPayload()); - final Timestamp timestamp = channelHeader.getTimestamp(); - - this.txTimestamp = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); - this.creator = signatureHeader.getCreator(); - this.transientMap = chaincodeProposalPayload.getTransientMapMap(); - this.binding = computeBinding(channelHeader, signatureHeader); - } catch (InvalidProtocolBufferException | NoSuchAlgorithmException e) { - throw new RuntimeException(e); + final Proposal proposal = Proposal.parseFrom(signedProposal.getProposalBytes()); + final Header header = Header.parseFrom(proposal.getHeader()); + final ChannelHeader channelHeader = ChannelHeader.parseFrom(header.getChannelHeader()); + validateProposalType(channelHeader); + final SignatureHeader signatureHeader = SignatureHeader.parseFrom(header.getSignatureHeader()); + final ChaincodeProposalPayload chaincodeProposalPayload = + ChaincodeProposalPayload.parseFrom(proposal.getPayload()); + final Timestamp timestamp = channelHeader.getTimestamp(); + + this.txTimestamp = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); + this.creator = signatureHeader.getCreator(); + this.transientMap = chaincodeProposalPayload.getTransientMapMap(); + this.binding = computeBinding(channelHeader, signatureHeader); + } + } + + private static boolean isEmptyString(final String str) { + for (int i = 0; i < str.length(); i++) { + if (!Character.isWhitespace(str.charAt(i))) { + return false; } } + return true; } private byte[] computeBinding(final ChannelHeader channelHeader, final SignatureHeader signatureHeader) @@ -124,8 +147,8 @@ private byte[] computeBinding(final ChannelHeader channelHeader, final Signature final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(signatureHeader.getNonce().asReadOnlyByteBuffer()); messageDigest.update(this.creator.asReadOnlyByteBuffer()); - final ByteBuffer epochBytes = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN) - .putLong(channelHeader.getEpoch()); + final ByteBuffer epochBytes = + ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(channelHeader.getEpoch()); epochBytes.flip(); messageDigest.update(epochBytes); return messageDigest.digest(); @@ -133,28 +156,28 @@ private byte[] computeBinding(final ChannelHeader channelHeader, final Signature private void validateProposalType(final ChannelHeader channelHeader) { switch (HeaderType.forNumber(channelHeader.getType())) { - case ENDORSER_TRANSACTION: - case CONFIG: - return; - default: - throw new RuntimeException( - String.format("Unexpected transaction type: %s", HeaderType.forNumber(channelHeader.getType()))); + case ENDORSER_TRANSACTION: + case CONFIG: + return; + default: + throw new IllegalArgumentException(String.format( + "Unexpected transaction type: %s", HeaderType.forNumber(channelHeader.getType()))); } } @Override public List getArgs() { - return args.stream().map(x -> x.toByteArray()).collect(Collectors.toList()); + return args.stream().map(ByteString::toByteArray).collect(toList()); } @Override public List getStringArgs() { - return args.stream().map(x -> x.toStringUtf8()).collect(Collectors.toList()); + return args.stream().map(ByteString::toStringUtf8).collect(toList()); } @Override public String getFunction() { - return getStringArgs().size() > 0 ? getStringArgs().get(0) : null; + return getStringArgs().isEmpty() ? null : getStringArgs().get(0); } @Override @@ -164,11 +187,13 @@ public List getParameters() { @Override public void setEvent(final String name, final byte[] payload) { - if (name == null || name.trim().isEmpty()) { + if (null == name || isEmptyString(name)) { throw new IllegalArgumentException("event name can not be nil string"); } if (payload != null) { - this.event = ChaincodeEvent.newBuilder().setEventName(name).setPayload(ByteString.copyFrom(payload)) + this.event = ChaincodeEvent.newBuilder() + .setEventName(name) + .setPayload(ByteString.copyFrom(payload)) .build(); } else { this.event = ChaincodeEvent.newBuilder().setEventName(name).build(); @@ -192,32 +217,35 @@ public String getTxId() { @Override public byte[] getState(final String key) { - return this.handler.invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", key)) + return this.handler + .invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", key)) .toByteArray(); } @Override + @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") public byte[] getStateValidationParameter(final String key) { - final ByteString payload = handler - .invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, "", key)); + final ByteString payload = + handler.invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, "", key)); try { final StateMetadataResult stateMetadataResult = StateMetadataResult.parseFrom(payload); final Map stateMetadataMap = new HashMap<>(); - stateMetadataResult.getEntriesList() + stateMetadataResult + .getEntriesList() .forEach(entry -> stateMetadataMap.put(entry.getMetakey(), entry.getValue())); if (stateMetadataMap.containsKey(MetaDataKeys.VALIDATION_PARAMETER.toString())) { - return stateMetadataMap.get(MetaDataKeys.VALIDATION_PARAMETER.toString()) + return stateMetadataMap + .get(MetaDataKeys.VALIDATION_PARAMETER.toString()) .toByteArray(); } } catch (final InvalidProtocolBufferException e) { - LOGGER.severe(String.format("[%-8.8s] unmarshalling error", txId)); - throw new RuntimeException("Error unmarshalling StateMetadataResult.", e); + LOGGER.severe(() -> String.format("[%-8.8s] unmarshalling error", txId)); + throw new UncheckedIOException("Error unmarshalling StateMetadataResult.", e); } return null; - } @Override @@ -230,8 +258,8 @@ public void putState(final String key, final byte[] value) { @Override public void setStateValidationParameter(final String key, final byte[] value) { validateKey(key); - final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, "", key, - MetaDataKeys.VALIDATION_PARAMETER.toString(), ByteString.copyFrom(value)); + final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage( + channelId, txId, "", key, MetaDataKeys.VALIDATION_PARAMETER.toString(), ByteString.copyFrom(value)); this.handler.invoke(msg); } @@ -257,36 +285,27 @@ public QueryResultsIterator getStateByRange(final String startKey, fin return executeGetStateByRange("", start, end); } - private QueryResultsIterator executeGetStateByRange(final String collection, final String startKey, - final String endKey) { + private QueryResultsIterator executeGetStateByRange( + final String collection, final String startKey, final String endKey) { - final ByteString requestPayload = GetStateByRange.newBuilder().setCollection(collection).setStartKey(startKey) - .setEndKey(endKey).build().toByteString(); + final ByteString requestPayload = GetStateByRange.newBuilder() + .setCollection(collection) + .setStartKey(startKey) + .setEndKey(endKey) + .build() + .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, - txId, requestPayload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, txId, requestPayload); final ByteString response = handler.invoke(requestMessage); - return new QueryResultsIteratorImpl(this.handler, channelId, txId, response, - queryResultBytesToKv.andThen(KeyValueImpl::new)); - + return new QueryResultsIteratorImpl<>( + this.handler, channelId, txId, response, QUERY_RESULT_BYTES_TO_KV.andThen(KeyValueImpl::new)); } - private final Function queryResultBytesToKv = new Function() { - @Override - public KV apply(final QueryResultBytes queryResultBytes) { - try { - return KV.parseFrom(queryResultBytes.getResultBytes()); - } catch (final InvalidProtocolBufferException e) { - throw new RuntimeException(e); - } - } - - }; - @Override - public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(final String startKey, - final String endKey, final int pageSize, final String bookmark) { + public QueryResultsIteratorWithMetadata getStateByRangeWithPagination( + final String startKey, final String endKey, final int pageSize, final String bookmark) { String start = startKey; String end = endKey; @@ -300,26 +319,32 @@ public QueryResultsIteratorWithMetadata getStateByRangeWithPagination( CompositeKey.validateSimpleKeys(start, end); - final QueryMetadata queryMetadata = QueryMetadata.newBuilder().setBookmark(bookmark) - .setPageSize(pageSize).build(); + final QueryMetadata queryMetadata = QueryMetadata.newBuilder() + .setBookmark(bookmark) + .setPageSize(pageSize) + .build(); return executeGetStateByRangeWithMetadata("", start, end, queryMetadata.toByteString()); } - private QueryResultsIteratorWithMetadataImpl executeGetStateByRangeWithMetadata(final String collection, - final String startKey, final String endKey, final ByteString metadata) { + private QueryResultsIteratorWithMetadataImpl executeGetStateByRangeWithMetadata( + final String collection, final String startKey, final String endKey, final ByteString metadata) { - final ByteString payload = GetStateByRange.newBuilder().setCollection(collection).setStartKey(startKey) - .setEndKey(endKey).setMetadata(metadata).build().toByteString(); + final ByteString payload = GetStateByRange.newBuilder() + .setCollection(collection) + .setStartKey(startKey) + .setEndKey(endKey) + .setMetadata(metadata) + .build() + .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, - txId, payload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, txId, payload); final ByteString response = this.handler.invoke(requestMessage); - return new QueryResultsIteratorWithMetadataImpl<>(this.handler, getChannelId(), getTxId(), response, - queryResultBytesToKv.andThen(KeyValueImpl::new)); - + return new QueryResultsIteratorWithMetadataImpl<>( + this.handler, getChannelId(), getTxId(), response, QUERY_RESULT_BYTES_TO_KV.andThen(KeyValueImpl::new)); } @Override @@ -337,8 +362,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final String } @Override - public QueryResultsIterator getStateByPartialCompositeKey(final String objectType, - final String... attributes) { + public QueryResultsIterator getStateByPartialCompositeKey( + final String objectType, final String... attributes) { return getStateByPartialCompositeKey(new CompositeKey(objectType, attributes)); } @@ -368,11 +393,13 @@ public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyW cKeyAsString = compositeKey.toString(); } - final QueryMetadata queryMetadata = QueryMetadata.newBuilder().setBookmark(bookmark) - .setPageSize(pageSize).build(); + final QueryMetadata queryMetadata = QueryMetadata.newBuilder() + .setBookmark(bookmark) + .setPageSize(pageSize) + .build(); - return executeGetStateByRangeWithMetadata("", cKeyAsString, cKeyAsString + MAX_UNICODE_RUNE, - queryMetadata.toByteString()); + return executeGetStateByRangeWithMetadata( + "", cKeyAsString, cKeyAsString + MAX_UNICODE_RUNE, queryMetadata.toByteString()); } @Override @@ -388,63 +415,67 @@ public CompositeKey splitCompositeKey(final String compositeKey) { @Override public QueryResultsIterator getQueryResult(final String query) { - final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(query).build() + final ByteString requestPayload = GetQueryResult.newBuilder() + .setCollection("") + .setQuery(query) + .build() .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, - txId, requestPayload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload); final ByteString response = handler.invoke(requestMessage); - return new QueryResultsIteratorImpl(this.handler, channelId, txId, response, - queryResultBytesToKv.andThen(KeyValueImpl::new)); + return new QueryResultsIteratorImpl<>( + this.handler, channelId, txId, response, QUERY_RESULT_BYTES_TO_KV.andThen(KeyValueImpl::new)); } @Override - public QueryResultsIteratorWithMetadata getQueryResultWithPagination(final String query, - final int pageSize, final String bookmark) { + public QueryResultsIteratorWithMetadata getQueryResultWithPagination( + final String query, final int pageSize, final String bookmark) { - final ByteString queryMetadataPayload = QueryMetadata.newBuilder().setBookmark(bookmark) - .setPageSize(pageSize).build().toByteString(); - final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(query) - .setMetadata(queryMetadataPayload).build().toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, - txId, requestPayload); + final ByteString queryMetadataPayload = QueryMetadata.newBuilder() + .setBookmark(bookmark) + .setPageSize(pageSize) + .build() + .toByteString(); + final ByteString requestPayload = GetQueryResult.newBuilder() + .setCollection("") + .setQuery(query) + .setMetadata(queryMetadataPayload) + .build() + .toByteString(); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload); final ByteString response = handler.invoke(requestMessage); - return new QueryResultsIteratorWithMetadataImpl(this.handler, channelId, txId, response, - queryResultBytesToKv.andThen(KeyValueImpl::new)); - + return new QueryResultsIteratorWithMetadataImpl<>( + this.handler, channelId, txId, response, QUERY_RESULT_BYTES_TO_KV.andThen(KeyValueImpl::new)); } @Override public QueryResultsIterator getHistoryForKey(final String key) { - final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(key).build() + final ByteString requestPayload = GetQueryResult.newBuilder() + .setCollection("") + .setQuery(key) + .build() .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_HISTORY_FOR_KEY, channelId, - txId, requestPayload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_HISTORY_FOR_KEY, channelId, txId, requestPayload); final ByteString response = handler.invoke(requestMessage); - return new QueryResultsIteratorImpl(this.handler, channelId, txId, response, - queryResultBytesToKeyModification.andThen(KeyModificationImpl::new)); - + return new QueryResultsIteratorImpl<>( + this.handler, + channelId, + txId, + response, + QUERY_RESULT_BYTES_TO_KEY_MODIFICATION.andThen(KeyModificationImpl::new)); } - private final Function queryResultBytesToKeyModification = - new Function() { - @Override - public org.hyperledger.fabric.protos.ledger.queryresult.KeyModification apply(final QueryResultBytes queryResultBytes) { - try { - return org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.parseFrom(queryResultBytes.getResultBytes()); - } catch (final InvalidProtocolBufferException e) { - throw new RuntimeException(e); - } - } - }; - @Override public byte[] getPrivateData(final String collection, final String key) { validateCollection(collection); - return this.handler.invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key)) + return this.handler + .invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key)) .toByteArray(); } @@ -453,33 +484,39 @@ public byte[] getPrivateDataHash(final String collection, final String key) { validateCollection(collection); - final ByteString requestPayload = GetState.newBuilder().setCollection(collection).setKey(key).build() + final ByteString requestPayload = GetState.newBuilder() + .setCollection(collection) + .setKey(key) + .build() .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_PRIVATE_DATA_HASH, - channelId, txId, requestPayload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, requestPayload); return handler.invoke(requestMessage).toByteArray(); } @Override + @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") public byte[] getPrivateDataValidationParameter(final String collection, final String key) { validateCollection(collection); - final ByteString payload = handler - .invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key)); + final ByteString payload = handler.invoke( + ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key)); try { final StateMetadataResult stateMetadataResult = StateMetadataResult.parseFrom(payload); final Map stateMetadataMap = new HashMap<>(); - stateMetadataResult.getEntriesList() + stateMetadataResult + .getEntriesList() .forEach(entry -> stateMetadataMap.put(entry.getMetakey(), entry.getValue())); if (stateMetadataMap.containsKey(MetaDataKeys.VALIDATION_PARAMETER.toString())) { - return stateMetadataMap.get(MetaDataKeys.VALIDATION_PARAMETER.toString()) + return stateMetadataMap + .get(MetaDataKeys.VALIDATION_PARAMETER.toString()) .toByteArray(); } } catch (final InvalidProtocolBufferException e) { - LOGGER.severe(String.format("[%-8.8s] unmarshalling error", txId)); - throw new RuntimeException("Error unmarshalling StateMetadataResult.", e); + LOGGER.severe(() -> String.format("[%-8.8s] unmarshalling error", txId)); + throw new UncheckedIOException("Error unmarshalling StateMetadataResult.", e); } return null; @@ -489,16 +526,20 @@ public byte[] getPrivateDataValidationParameter(final String collection, final S public void putPrivateData(final String collection, final String key, final byte[] value) { validateKey(key); validateCollection(collection); - this.handler.invoke(ChaincodeMessageFactory.newPutStateEventMessage(channelId, txId, collection, key, - ByteString.copyFrom(value))); + this.handler.invoke(ChaincodeMessageFactory.newPutStateEventMessage( + channelId, txId, collection, key, ByteString.copyFrom(value))); } @Override public void setPrivateDataValidationParameter(final String collection, final String key, final byte[] value) { validateKey(key); validateCollection(collection); - final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, - collection, key, MetaDataKeys.VALIDATION_PARAMETER.toString(), + final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage( + channelId, + txId, + collection, + key, + MetaDataKeys.VALIDATION_PARAMETER.toString(), ByteString.copyFrom(value)); this.handler.invoke(msg); } @@ -506,22 +547,22 @@ public void setPrivateDataValidationParameter(final String collection, final Str @Override public void delPrivateData(final String collection, final String key) { validateCollection(collection); - final ChaincodeMessage msg = ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, - key); + final ChaincodeMessage msg = + ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, key); this.handler.invoke(msg); } @Override public void purgePrivateData(final String collection, final String key) { validateCollection(collection); - final ChaincodeMessage msg = ChaincodeMessageFactory.newPurgeStateEventMessage(channelId, txId, collection, - key); + final ChaincodeMessage msg = + ChaincodeMessageFactory.newPurgeStateEventMessage(channelId, txId, collection, key); this.handler.invoke(msg); } @Override - public QueryResultsIterator getPrivateDataByRange(final String collection, final String startKey, - final String endKey) { + public QueryResultsIterator getPrivateDataByRange( + final String collection, final String startKey, final String endKey) { String start = startKey; String end = endKey; @@ -538,8 +579,8 @@ public QueryResultsIterator getPrivateDataByRange(final String collect } @Override - public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, - final String compositeKey) { + public QueryResultsIterator getPrivateDataByPartialCompositeKey( + final String collection, final String compositeKey) { CompositeKey key; @@ -555,8 +596,8 @@ public QueryResultsIterator getPrivateDataByPartialCompositeKey(final } @Override - public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, - final CompositeKey compositeKey) { + public QueryResultsIterator getPrivateDataByPartialCompositeKey( + final String collection, final CompositeKey compositeKey) { String cKeyAsString; if (compositeKey == null) { cKeyAsString = new CompositeKey(UNSPECIFIED_START_KEY).toString(); @@ -568,29 +609,33 @@ public QueryResultsIterator getPrivateDataByPartialCompositeKey(final } @Override - public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, - final String objectType, final String... attributes) { + public QueryResultsIterator getPrivateDataByPartialCompositeKey( + final String collection, final String objectType, final String... attributes) { return getPrivateDataByPartialCompositeKey(collection, new CompositeKey(objectType, attributes)); } @Override public QueryResultsIterator getPrivateDataQueryResult(final String collection, final String query) { validateCollection(collection); - final ByteString requestPayload = GetQueryResult.newBuilder().setCollection(collection).setQuery(query).build() + final ByteString requestPayload = GetQueryResult.newBuilder() + .setCollection(collection) + .setQuery(query) + .build() .toByteString(); - final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, - txId, requestPayload); + final ChaincodeMessage requestMessage = + ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload); final ByteString response = handler.invoke(requestMessage); - return new QueryResultsIteratorImpl(this.handler, channelId, txId, response, - queryResultBytesToKv.andThen(KeyValueImpl::new)); + return new QueryResultsIteratorImpl<>( + this.handler, channelId, txId, response, QUERY_RESULT_BYTES_TO_KV.andThen(KeyValueImpl::new)); } @Override - public Chaincode.Response invokeChaincode(final String chaincodeName, final List args, final String channel) { + public Chaincode.Response invokeChaincode( + final String chaincodeName, final List args, final String channel) { // internally we handle chaincode name as a composite name final String compositeName; - if (channel != null && !channel.trim().isEmpty()) { + if (channel != null && !isEmptyString(channel)) { compositeName = chaincodeName + "/" + channel; } else { compositeName = chaincodeName; @@ -600,11 +645,13 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List final ByteString invocationSpecPayload = ChaincodeSpec.newBuilder() .setChaincodeId(ChaincodeID.newBuilder().setName(compositeName).build()) .setInput(ChaincodeInput.newBuilder() - .addAllArgs(args.stream().map(ByteString::copyFrom).collect(Collectors.toList())).build()) - .build().toByteString(); + .addAllArgs(args.stream().map(ByteString::copyFrom).collect(toList())) + .build()) + .build() + .toByteString(); - final ChaincodeMessage invokeChaincodeMessage = ChaincodeMessageFactory - .newInvokeChaincodeMessage(this.channelId, this.txId, invocationSpecPayload); + final ChaincodeMessage invokeChaincodeMessage = + ChaincodeMessageFactory.newInvokeChaincodeMessage(this.channelId, this.txId, invocationSpecPayload); final ByteString response = this.handler.invoke(invokeChaincodeMessage); try { @@ -613,24 +660,24 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List final ChaincodeMessage responseMessage = ChaincodeMessage.parseFrom(response); // the actual response message must be of type COMPLETED - LOGGER.fine(String.format("[%-8.8s] %s response received from other chaincode.", txId, - responseMessage.getType())); + LOGGER.fine(() -> String.format( + "[%-8.8s] %s response received from other chaincode.", txId, responseMessage.getType())); if (responseMessage.getType() == COMPLETED) { // success - final Response r = Response - .parseFrom(responseMessage.getPayload()); - return new Chaincode.Response(Chaincode.Response.Status.forCode(r.getStatus()), r.getMessage(), - r.getPayload() == null ? null : r.getPayload().toByteArray()); + final Response r = Response.parseFrom(responseMessage.getPayload()); + return new Chaincode.Response( + Chaincode.Response.Status.forCode(r.getStatus()), + r.getMessage(), + r.getPayload().toByteArray()); } else { // error final String message = responseMessage.getPayload().toStringUtf8(); return new Chaincode.Response(Chaincode.Response.Status.INTERNAL_SERVER_ERROR, message, null); } } catch (final InvalidProtocolBufferException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } - } @Override @@ -644,6 +691,7 @@ public Instant getTxTimestamp() { } @Override + @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") public byte[] getCreator() { if (creator == null) { return null; @@ -654,27 +702,24 @@ public byte[] getCreator() { @Override public Map getTransient() { return transientMap.entrySet().stream() - .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().toByteArray())); + .collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().toByteArray())); } @Override + @SuppressWarnings("PMD.MethodReturnsInternalArray") public byte[] getBinding() { return this.binding; } private void validateKey(final String key) { - if (key == null) { - throw new NullPointerException("key cannot be null"); - } - if (key.length() == 0) { + Objects.requireNonNull(key, "key cannot be null"); + if (key.isEmpty()) { throw new IllegalArgumentException("key cannot not be an empty string"); } } private void validateCollection(final String collection) { - if (collection == null) { - throw new NullPointerException("collection cannot be null"); - } + Objects.requireNonNull(collection, "collection cannot be null"); if (collection.isEmpty()) { throw new IllegalArgumentException("collection must not be an empty string"); } @@ -685,6 +730,6 @@ public String getMspId() { if (System.getenv().containsKey(CORE_PEER_LOCALMSPID)) { return System.getenv(CORE_PEER_LOCALMSPID); } - throw new RuntimeException("CORE_PEER_LOCALMSPID is unset in chaincode process"); + throw new IllegalStateException("CORE_PEER_LOCALMSPID is unset in chaincode process"); } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java index 97d68fbd1..1267ac4fb 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java @@ -12,19 +12,15 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Logger; - import org.hyperledger.fabric.metrics.TaskMetricsCollector; -/** - * - * - * - */ +/** */ public final class InvocationTaskExecutor extends ThreadPoolExecutor implements TaskMetricsCollector { private static Logger logger = Logger.getLogger(InvocationTaskExecutor.class.getName()); + private final AtomicInteger count = new AtomicInteger(); + /** - * * @param corePoolSize * @param maximumPoolSize * @param keepAliveTime @@ -33,20 +29,23 @@ public final class InvocationTaskExecutor extends ThreadPoolExecutor implements * @param factory * @param handler */ - public InvocationTaskExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, - final BlockingQueue workQueue, final ThreadFactory factory, final RejectedExecutionHandler handler) { + public InvocationTaskExecutor( + final int corePoolSize, + final int maximumPoolSize, + final long keepAliveTime, + final TimeUnit unit, + final BlockingQueue workQueue, + final ThreadFactory factory, + final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory, handler); prestartCoreThread(); logger.info("Thread pool created"); } - private final AtomicInteger count = new AtomicInteger(); - @Override protected void beforeExecute(final Thread thread, final Runnable task) { super.beforeExecute(thread, task); count.incrementAndGet(); - } @Override @@ -64,5 +63,4 @@ public int getCurrentTaskCount() { public int getCurrentQueueCount() { return this.getQueue().size(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java index 424f3a841..aecc8e64d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java @@ -8,6 +8,7 @@ import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY; import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTERED; +import java.util.Map; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; @@ -22,7 +23,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.logging.Logger; - import org.hyperledger.fabric.Logging; import org.hyperledger.fabric.metrics.Metrics; import org.hyperledger.fabric.protos.peer.ChaincodeID; @@ -31,35 +31,24 @@ import org.hyperledger.fabric.shim.ChaincodeBase; /** - * The InvocationTask Manager handles the message level communication with the - * peer. - * - * In the current 1.4 Fabric Protocol this is in practice a singleton - because - * the peer will ignore multiple 'register' calls. And an instance of this will - * be created per register call for a given chaincodeID. + * The InvocationTask Manager handles the message level communication with the peer. * + *

In the current 1.4 Fabric Protocol this is in practice a singleton - because the peer will ignore multiple + * 'register' calls. And an instance of this will be created per register call for a given chaincodeID. */ +@SuppressWarnings("PMD.MoreThanOneLogger") public final class InvocationTaskManager { - private static Logger logger = Logger.getLogger(InvocationTaskManager.class.getName()); - private static Logger perflogger = Logger.getLogger(Logging.PERFLOGGER); - - /** - * Get an instance of the Invocation Task Manager. - * - * @param chaincode Chaincode Instance - * @param chaincodeId ID of the chaincode - * @return InvocationTaskManager - */ - public static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId) { - return new InvocationTaskManager(chaincode, chaincodeId); - } + private static final Logger LOGGER = Logger.getLogger(InvocationTaskManager.class.getName()); + private static final Logger PERFLOGGER = Logger.getLogger(Logging.PERFLOGGER); + private static final String CANNOT_HANDLE_FORMAT = "[%-8.8s] Received %s: cannot handle"; + private static final int SHUTDOWN_TIMEOUT = 60; // Keeping a map here of the tasks that are currently ongoing, and the key // // Key = txid + channleid // One task = one transaction invocation - private final ConcurrentHashMap innvocationTasks = new ConcurrentHashMap<>(); + private final Map innvocationTasks = new ConcurrentHashMap<>(); // Way to send back the events and data that make up the requests private Consumer outgoingMessage; @@ -73,18 +62,18 @@ public static InvocationTaskManager getManager(final ChaincodeBase chaincode, fi private final int maximumPoolSize; private final int corePoolSize; private final long keepAliveTime; - private final TimeUnit unit = TimeUnit.MILLISECONDS; + private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; private final BlockingQueue workQueue; // Minor customization of the ThreadFactory to give a more recognizable name to the threads private final ThreadFactory threadFactory = new ThreadFactory() { - private AtomicInteger next = new AtomicInteger(0); + private final AtomicInteger next = new AtomicInteger(0); + @Override public Thread newThread(final Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName("fabric-txinvoke:" + next.incrementAndGet()); return thread; - } }; @@ -99,10 +88,21 @@ public Thread newThread(final Runnable r) { private final InvocationTaskExecutor taskService; + /** + * Get an instance of the Invocation Task Manager. + * + * @param chaincode Chaincode Instance + * @param chaincodeId ID of the chaincode + * @return InvocationTaskManager + */ + public static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId) { + return new InvocationTaskManager(chaincode, chaincodeId); + } + /** * New InvocationTaskManager. * - * @param chaincode Chaincode Instance + * @param chaincode Chaincode Instance * @param chaincodeId ID of the chaincode */ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId) { @@ -122,17 +122,16 @@ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID ch corePoolSize = Integer.parseInt((String) props.getOrDefault("TP_CORE_POOL_SIZE", "5")); keepAliveTime = Long.parseLong((String) props.getOrDefault("TP_KEEP_ALIVE_MS", "5000")); - logger.info(() -> "Max Pool Size [TP_MAX_POOL_SIZE]" + maximumPoolSize); - logger.info(() -> "Queue Size [TP_CORE_POOL_SIZE]" + queueSize); - logger.info(() -> "Core Pool Size [TP_QUEUE_SIZE]" + corePoolSize); - logger.info(() -> "Keep Alive Time [TP_KEEP_ALIVE_MS]" + keepAliveTime); + LOGGER.info(() -> "Max Pool Size [TP_MAX_POOL_SIZE]" + maximumPoolSize); + LOGGER.info(() -> "Queue Size [TP_CORE_POOL_SIZE]" + queueSize); + LOGGER.info(() -> "Core Pool Size [TP_QUEUE_SIZE]" + corePoolSize); + LOGGER.info(() -> "Keep Alive Time [TP_KEEP_ALIVE_MS]" + keepAliveTime); - workQueue = new LinkedBlockingQueue(queueSize); - taskService = new InvocationTaskExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, - threadFactory, handler); + workQueue = new LinkedBlockingQueue<>(queueSize); + taskService = new InvocationTaskExecutor( + corePoolSize, maximumPoolSize, keepAliveTime, UNIT, workQueue, threadFactory, handler); Metrics.getProvider().setTaskMetricsCollector(taskService); - } /** @@ -141,42 +140,15 @@ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID ch * @throws IllegalArgumentException validation fields and arguments * @param chaincodeMessage ChaincodeMessage */ - public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws IllegalArgumentException { - if (chaincodeMessage == null) { + @SuppressWarnings("PMD.AvoidCatchingGenericException") + public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { + if (null == chaincodeMessage) { throw new IllegalArgumentException("chaincodeMessage is null"); } - logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); + LOGGER.fine(() -> + String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { - final Type msgType = chaincodeMessage.getType(); - switch (chaincode.getState()) { - case CREATED: - if (msgType == REGISTERED) { - chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); - logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", - chaincodeMessage.getTxid())); - } else { - logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", - chaincodeMessage.getTxid(), msgType)); - } - break; - case ESTABLISHED: - if (msgType == READY) { - chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); - logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", - chaincodeMessage.getTxid())); - } else { - logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", - chaincodeMessage.getTxid(), msgType)); - } - break; - case READY: - handleMsg(chaincodeMessage, msgType); - break; - default: - logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", - chaincodeMessage.getTxid(), chaincodeMessage.getType())); - break; - } + processChaincodeMessage(chaincodeMessage); } catch (final RuntimeException e) { // catch any issues with say the comms dropping or something else completely // unknown @@ -186,15 +158,45 @@ public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws I } } + private void processChaincodeMessage(final ChaincodeMessage chaincodeMessage) { + final Type msgType = chaincodeMessage.getType(); + + switch (chaincode.getState()) { + case CREATED: + if (msgType == REGISTERED) { + chaincode.setState(ChaincodeBase.CCState.ESTABLISHED); + LOGGER.fine(() -> String.format( + "[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); + } else { + LOGGER.warning(() -> String.format(CANNOT_HANDLE_FORMAT, chaincodeMessage.getTxid(), msgType)); + } + break; + case ESTABLISHED: + if (msgType == READY) { + chaincode.setState(ChaincodeBase.CCState.READY); + LOGGER.fine(() -> String.format( + "[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); + } else { + LOGGER.warning(() -> String.format(CANNOT_HANDLE_FORMAT, chaincodeMessage.getTxid(), msgType)); + } + break; + case READY: + handleMsg(chaincodeMessage, msgType); + break; + default: + LOGGER.warning(() -> String.format(CANNOT_HANDLE_FORMAT, chaincodeMessage.getTxid(), msgType)); + break; + } + } + /** - * Key method to take the message, determine if it is a new transaction or an - * answer (good or bad) to a stub api. + * Key method to take the message, determine if it is a new transaction or an answer (good or bad) to a stub api. * * @param message * @param msgType */ private void handleMsg(final ChaincodeMessage message, final Type msgType) { - logger.fine(() -> String.format("[%-8.8s] Received %s", message.getTxid(), msgType.toString())); + LOGGER.fine(() -> String.format("[%-8.8s] Received %s", message.getTxid(), msgType.toString())); switch (msgType) { case RESPONSE: case ERROR: @@ -205,64 +207,66 @@ private void handleMsg(final ChaincodeMessage message, final Type msgType) { newTask(message, msgType); break; default: - logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", message.getTxid(), - message.getType())); + LOGGER.warning(() -> String.format(CANNOT_HANDLE_FORMAT, message.getTxid(), message.getType())); break; } } /** - * Send a message from the peer to the correct task. This will be a response to - * something like a getState() call. + * Send a message from the peer to the correct task. This will be a response to something like a getState() call. * * @param message ChaincodeMessage from the peer */ private void sendToTask(final ChaincodeMessage message) { try { - perflogger.fine(() -> "> sendToTask TX::" + message.getTxid()); + PERFLOGGER.fine(() -> "> sendToTask TX::" + message.getTxid()); final String key = message.getChannelId() + message.getTxid(); final ChaincodeInvocationTask task = this.innvocationTasks.get(key); if (task == null) { - throw new InterruptedException("Task hasmap missing entry"); + sendFailure(message, new InterruptedException("Task map missing entry: " + key)); + } else { + task.postMessage(message); + PERFLOGGER.fine(() -> "< sendToTask TX::" + message.getTxid()); } - task.postMessage(message); - - perflogger.fine(() -> "< sendToTask TX::" + message.getTxid()); } catch (final InterruptedException e) { - logger.severe( - () -> "Failed to send response to the task task " + message.getTxid() + Logging.formatError(e)); - - final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(), - message.getTxid(), "Failed to send response to task"); - this.outgoingMessage.accept(m); + sendFailure(message, e); } } + private void sendFailure(final ChaincodeMessage message, final InterruptedException e) { + LOGGER.severe(() -> "Failed to send response to the task task " + message.getTxid() + Logging.formatError(e)); + + final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage( + message.getChannelId(), message.getTxid(), "Failed to send response to task"); + this.outgoingMessage.accept(m); + } + /** * Create a new task to handle this transaction function. * * @param message ChaincodeMessage to process - * @param type Type of message = INIT or INVOKE. INIT is deprecated in future - * versions + * @param type Type of message = INIT or INVOKE. INIT is deprecated in future versions * @throws InterruptedException */ private void newTask(final ChaincodeMessage message, final Type type) { String txid = message.getTxid(); - final ChaincodeInvocationTask task = new ChaincodeInvocationTask(message, type, this.outgoingMessage, - this.chaincode); + final ChaincodeInvocationTask task = + new ChaincodeInvocationTask(message, type, this.outgoingMessage, this.chaincode); - perflogger.fine(() -> "> newTask:created TX::" + txid); + PERFLOGGER.fine(() -> "> newTask:created TX::" + txid); this.innvocationTasks.put(task.getTxKey(), task); try { - perflogger.fine(() -> "> newTask:submitting TX::" + txid); + PERFLOGGER.fine(() -> "> newTask:submitting TX::" + txid); // submit the task to run, with the taskService providing the // threading support. - final CompletableFuture response = CompletableFuture.runAsync(() -> { - task.call(); - }, taskService); + final CompletableFuture response = CompletableFuture.runAsync( + () -> { + task.call(); + }, + taskService); // we have a future of the chaincode message that should be returned. // but waiting for this does not need to block this thread @@ -270,22 +274,21 @@ private void newTask(final ChaincodeMessage message, final Type type) { // list response.thenRun(() -> { innvocationTasks.remove(task.getTxKey()); - perflogger.fine(() -> "< newTask:completed TX::" + txid); + PERFLOGGER.fine(() -> "< newTask:completed TX::" + txid); }); - perflogger.fine(() -> "< newTask:submitted TX::" + txid); + PERFLOGGER.fine(() -> "< newTask:submitted TX::" + txid); } catch (final RejectedExecutionException e) { - logger.warning(() -> "Failed to submit task " + txid + Logging.formatError(e)); + LOGGER.warning(() -> "Failed to submit task " + txid + Logging.formatError(e)); // this means that there is no way that this can be handed off to another // thread for processing, and there's no space left in the queue to hold // it pending - final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(), txid, - "Failed to submit task for processing"); + final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage( + message.getChannelId(), txid, "Failed to submit task for processing"); this.outgoingMessage.accept(m); } - } /** @@ -294,35 +297,27 @@ private void newTask(final ChaincodeMessage message, final Type type) { * @param outgoingMessage * @return InvocationTaskManager */ - public InvocationTaskManager setResponseConsumer(final Consumer outgoingMessage) { + public void setResponseConsumer(final Consumer outgoingMessage) { this.outgoingMessage = outgoingMessage; - - return this; } /** * Send the initial protocol message for the 'register' phase. * * @throws IllegalArgumentException validation fields and arguments - * @return InvocationTaskManager */ - public InvocationTaskManager register() throws IllegalArgumentException { + public void register() { if (outgoingMessage == null) { throw new IllegalArgumentException("outgoingMessage is null"); } - logger.info(() -> "Registering new chaincode " + this.chaincodeId); + LOGGER.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); - - return this; } - private static final int SHUTDOWN_TIMEOUT = 60; - - /** - * - */ + /** */ + @SuppressWarnings("PMD.SystemPrintln") public void shutdown() { // Recommended shutdown process from // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html @@ -345,5 +340,4 @@ public void shutdown() { Thread.currentThread().interrupt(); } } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyModificationImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyModificationImpl.java index 42f77f738..2bbcca43e 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyModificationImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyModificationImpl.java @@ -5,23 +5,22 @@ */ package org.hyperledger.fabric.shim.impl; +import com.google.protobuf.ByteString; import java.time.Instant; - import org.hyperledger.fabric.shim.ledger.KeyModification; -import com.google.protobuf.ByteString; - public final class KeyModificationImpl implements KeyModification { private final String txId; private final ByteString value; - private final java.time.Instant timestamp; + private final Instant timestamp; private final boolean deleted; KeyModificationImpl(final org.hyperledger.fabric.protos.ledger.queryresult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); - this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); + this.timestamp = Instant.ofEpochSecond( + km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } @@ -41,7 +40,7 @@ public String getStringValue() { } @Override - public java.time.Instant getTimestamp() { + public Instant getTimestamp() { return timestamp; } @@ -53,39 +52,29 @@ public boolean isDeleted() { @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + (deleted ? 1231 : 1237); - result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); - result = prime * result + ((txId == null) ? 0 : txId.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); + int result = Boolean.hashCode(deleted); + result = prime * result + timestamp.hashCode(); + result = prime * result + txId.hashCode(); + result = prime * result + value.hashCode(); return result; } @Override - public boolean equals(final Object obj) { - if (this == obj) { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final KeyModificationImpl other = (KeyModificationImpl) obj; - if (deleted != other.deleted) { - return false; - } - if (!timestamp.equals(other.timestamp)) { + if (other == null) { return false; } - if (!txId.equals(other.txId)) { + if (getClass() != other.getClass()) { return false; } - if (!value.equals(other.value)) { - return false; - } - return true; - } + final KeyModificationImpl that = (KeyModificationImpl) other; + return this.deleted == that.deleted + && this.timestamp.equals(that.timestamp) + && this.txId.equals(that.txId) + && this.value.equals(that.value); + } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyValueImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyValueImpl.java index df9903cb4..e158fc967 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyValueImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/KeyValueImpl.java @@ -5,11 +5,10 @@ */ package org.hyperledger.fabric.shim.impl; +import com.google.protobuf.ByteString; import org.hyperledger.fabric.protos.ledger.queryresult.KV; import org.hyperledger.fabric.shim.ledger.KeyValue; -import com.google.protobuf.ByteString; - class KeyValueImpl implements KeyValue { private final String key; @@ -38,31 +37,24 @@ public String getStringValue() { @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); + int result = key.hashCode(); + result = prime * result + value.hashCode(); return result; } @Override - public boolean equals(final Object obj) { - if (this == obj) { + public boolean equals(final Object other) { + if (this == other) { return true; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { + if (other == null) { return false; } - final KeyValueImpl other = (KeyValueImpl) obj; - if (!key.equals(other.key)) { + if (getClass() != other.getClass()) { return false; } - if (!value.equals(other.value)) { - return false; - } - return true; - } + final KeyValueImpl that = (KeyValueImpl) other; + return this.key.equals(that.key) && this.value.equals(that.value); + } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorImpl.java index a319d84b9..893502040 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorImpl.java @@ -9,11 +9,13 @@ import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.QUERY_STATE_CLOSE; import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.QUERY_STATE_NEXT; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.UncheckedIOException; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Function; - import org.hyperledger.fabric.protos.peer.ChaincodeMessage; import org.hyperledger.fabric.protos.peer.QueryResponse; import org.hyperledger.fabric.protos.peer.QueryResultBytes; @@ -21,17 +23,13 @@ import org.hyperledger.fabric.protos.peer.QueryStateNext; import org.hyperledger.fabric.shim.ledger.QueryResultsIterator; -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; - /** * This class provides an ITERABLE object of query results. * - * NOTE the class name - * is misleading - as this class is not an iterator itself, rather it implements + *

NOTE the class name is misleading - as this class is not an iterator itself, rather it implements * java.lang.Iterable via the QueryResultsIterator * - * public interface QueryResultsIterator extends Iterable, AutoCloseable + *

public interface QueryResultsIterator extends Iterable, AutoCloseable * * @param */ @@ -42,9 +40,13 @@ class QueryResultsIteratorImpl implements QueryResultsIterator { private final String txId; private Iterator currentIterator; private QueryResponse currentQueryResponse; - private Function mapper; + private final Function mapper; - QueryResultsIteratorImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId, final ByteString responseBuffer, + QueryResultsIteratorImpl( + final ChaincodeInvocationTask handler, + final String channelId, + final String txId, + final ByteString responseBuffer, final Function mapper) { try { @@ -55,13 +57,13 @@ class QueryResultsIteratorImpl implements QueryResultsIterator { this.currentIterator = currentQueryResponse.getResultsList().iterator(); this.mapper = mapper; } catch (final InvalidProtocolBufferException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } } @Override public Iterator iterator() { - return new Iterator() { + return new Iterator<>() { @Override public boolean hasNext() { @@ -83,35 +85,40 @@ public T next() { // get more results from peer - final ByteString requestPayload = QueryStateNext.newBuilder().setId(currentQueryResponse.getId()).build().toByteString(); - final ChaincodeMessage requestNextMessage = ChaincodeMessageFactory.newEventMessage(QUERY_STATE_NEXT, channelId, txId, requestPayload); + final ByteString requestPayload = QueryStateNext.newBuilder() + .setId(currentQueryResponse.getId()) + .build() + .toByteString(); + final ChaincodeMessage requestNextMessage = + ChaincodeMessageFactory.newEventMessage(QUERY_STATE_NEXT, channelId, txId, requestPayload); final ByteString responseMessage = QueryResultsIteratorImpl.this.handler.invoke(requestNextMessage); try { currentQueryResponse = QueryResponse.parseFrom(responseMessage); } catch (final InvalidProtocolBufferException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } currentIterator = currentQueryResponse.getResultsList().iterator(); // return next fetched result return mapper.apply(currentIterator.next()); - } - }; } @Override public void close() throws Exception { - final ByteString requestPayload = QueryStateClose.newBuilder().setId(currentQueryResponse.getId()).build().toByteString(); + final ByteString requestPayload = QueryStateClose.newBuilder() + .setId(currentQueryResponse.getId()) + .build() + .toByteString(); - final ChaincodeMessage requestNextMessage = ChaincodeMessageFactory.newEventMessage(QUERY_STATE_CLOSE, channelId, txId, requestPayload); + final ChaincodeMessage requestNextMessage = + ChaincodeMessageFactory.newEventMessage(QUERY_STATE_CLOSE, channelId, txId, requestPayload); this.handler.invoke(requestNextMessage); this.currentIterator = Collections.emptyIterator(); this.currentQueryResponse = QueryResponse.newBuilder().setHasMore(false).build(); } - } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImpl.java index 93b349db1..250435473 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImpl.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImpl.java @@ -6,48 +6,50 @@ package org.hyperledger.fabric.shim.impl; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.UncheckedIOException; import java.util.function.Function; import java.util.logging.Logger; - -import org.hyperledger.fabric.protos.peer.QueryResponseMetadata; import org.hyperledger.fabric.protos.peer.QueryResponse; +import org.hyperledger.fabric.protos.peer.QueryResponseMetadata; import org.hyperledger.fabric.protos.peer.QueryResultBytes; import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata; -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; - /** * QueryResult Iterator. * - * Implementation of {@link QueryResultsIteratorWithMetadata}, by extending - * {@link org.hyperledger.fabric.shim.ledger.QueryResultsIterator} - * implementations, {@link QueryResultsIteratorImpl} + *

Implementation of {@link QueryResultsIteratorWithMetadata}, by extending + * {@link org.hyperledger.fabric.shim.ledger.QueryResultsIterator} implementations, {@link QueryResultsIteratorImpl} * * @param */ -public final class QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl implements QueryResultsIteratorWithMetadata { - private static Logger logger = Logger.getLogger(QueryResultsIteratorWithMetadataImpl.class.getName()); +public final class QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl + implements QueryResultsIteratorWithMetadata { + private static final Logger LOGGER = Logger.getLogger(QueryResultsIteratorWithMetadataImpl.class.getName()); - private QueryResponseMetadata metadata; + private final QueryResponseMetadata metadata; /** - * * @param handler * @param channelId * @param txId * @param responseBuffer * @param mapper */ - public QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId, - final ByteString responseBuffer, final Function mapper) { + public QueryResultsIteratorWithMetadataImpl( + final ChaincodeInvocationTask handler, + final String channelId, + final String txId, + final ByteString responseBuffer, + final Function mapper) { super(handler, channelId, txId, responseBuffer, mapper); try { final QueryResponse queryResponse = QueryResponse.parseFrom(responseBuffer); metadata = QueryResponseMetadata.parseFrom(queryResponse.getMetadata()); } catch (final InvalidProtocolBufferException e) { - logger.warning("can't parse response metadata"); - throw new RuntimeException(e); + LOGGER.warning("can't parse response metadata"); + throw new UncheckedIOException(e); } } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/package-info.java index ee6912edc..1147f6292 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/package-info.java @@ -4,7 +4,5 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * - */ +/** */ package org.hyperledger.fabric.shim.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/CompositeKey.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/CompositeKey.java index 8b47b39e0..4c88c2374 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/CompositeKey.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/CompositeKey.java @@ -11,6 +11,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -21,17 +22,14 @@ public class CompositeKey { private static final String INVALID_SEGMENT_CHAR = new String(Character.toChars(Character.MAX_CODE_POINT)); private static final String INVALID_SEGMENT_PATTERN = String.format("(?:%s|%s)", INVALID_SEGMENT_CHAR, DELIMITER); - /** - * - */ + /** */ public static final String NAMESPACE = DELIMITER; private final String objectType; private final List attributes; - private final String compositeKey; + private final String key; /** - * * @param objectType * @param attributes */ @@ -40,45 +38,33 @@ public CompositeKey(final String objectType, final String... attributes) { } /** - * * @param objectType * @param attributes */ public CompositeKey(final String objectType, final List attributes) { - if (objectType == null) { - throw new NullPointerException("objectType cannot be null"); - } + Objects.requireNonNull(objectType, "objectType cannot be null"); this.objectType = objectType; this.attributes = attributes; - this.compositeKey = generateCompositeKeyString(objectType, attributes); + this.key = generateCompositeKeyString(objectType, attributes); } - /** - * - * @return object type - */ + /** @return object type */ public String getObjectType() { return objectType; } - /** - * - * @return List of string arguments - */ + /** @return List of string arguments */ public List getAttributes() { return attributes; } - /** - * - */ + /** */ @Override public String toString() { - return compositeKey; + return key; } /** - * * @param compositeKey * @return Composite Key */ @@ -95,9 +81,8 @@ public static CompositeKey parseCompositeKey(final String compositeKey) { } /** - * To ensure that simple keys do not go into composite key namespace, we - * validate simple key to check whether the key starts with 0x00 (which is the - * namespace for compositeKey). This helps in avoiding simple/composite key + * To ensure that simple keys do not go into composite key namespace, we validate simple key to check whether the + * key starts with 0x00 (which is the namespace for compositeKey). This helps in avoiding simple/composite key * collisions. * * @param keys the list of simple keys @@ -124,7 +109,6 @@ private String generateCompositeKeyString(final String objectType, final List the type of elements returned by the iterator */ -public interface QueryResultsIterator extends Iterable, AutoCloseable { -} - +public interface QueryResultsIterator extends Iterable, AutoCloseable {} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIteratorWithMetadata.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIteratorWithMetadata.java index 80081c91b..b5c45cfa4 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIteratorWithMetadata.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/QueryResultsIteratorWithMetadata.java @@ -9,18 +9,13 @@ import org.hyperledger.fabric.protos.peer.QueryResponseMetadata; /** - * QueryResultsIteratorWithMetadata allows a chaincode to iterate over a set of - * key/value pairs returned by range, execute and history queries. In addition, - * it store - * {@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}, + * QueryResultsIteratorWithMetadata allows a chaincode to iterate over a set of key/value pairs returned by range, + * execute and history queries. In addition, it store {@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}, * returned by pagination range queries * * @param the type of elements returned by the iterator */ public interface QueryResultsIteratorWithMetadata extends Iterable, AutoCloseable { - /** - * - * @return Query Metadata - */ + /** @return Query Metadata */ QueryResponseMetadata getMetadata(); } diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/package-info.java index ed1ee6019..e47b1e4ac 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ledger/package-info.java @@ -10,4 +10,3 @@ * @see org.hyperledger.fabric.shim.ChaincodeStub */ package org.hyperledger.fabric.shim.ledger; - diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/package-info.java index 8ea4e804c..2fd3f3372 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/package-info.java @@ -7,11 +7,11 @@ /** * Provides interfaces and classes required for chaincode development and state variable access. * - *

- * It is possible to implement Java chaincode by extending the {@link org.hyperledger.fabric.shim.ChaincodeBase} class however new projects should should implement {@link org.hyperledger.fabric.contract.ContractInterface} and use the contract programming model instead. + *

It is possible to implement Java chaincode by extending the {@link org.hyperledger.fabric.shim.ChaincodeBase} + * class however new projects should should implement {@link org.hyperledger.fabric.contract.ContractInterface} and use + * the contract programming model instead. * * @see org.hyperledger.fabric.contract * @see org.hyperledger.fabric.shim.ChaincodeBase */ package org.hyperledger.fabric.shim; - diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/Traces.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/Traces.java index 2986f1692..60f3407a0 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/Traces.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/Traces.java @@ -5,19 +5,17 @@ */ package org.hyperledger.fabric.traces; -import org.hyperledger.fabric.traces.impl.DefaultTracesProvider; -import org.hyperledger.fabric.traces.impl.NullProvider; - -import java.lang.reflect.InvocationTargetException; import java.util.Properties; import java.util.logging.Logger; +import org.hyperledger.fabric.traces.impl.DefaultTracesProvider; +import org.hyperledger.fabric.traces.impl.NullProvider; /** * Traces Interface. * - * Traces setups up the provider in use from the configuration supplied + *

Traces setups up the provider in use from the configuration supplied * - * If not enabled, nothing happens. + *

If not enabled, nothing happens. */ public final class Traces { @@ -28,16 +26,13 @@ public final class Traces { private static TracesProvider provider; - - private Traces() { - - } + private Traces() {} /** - * * @param props the configuration of the chaincode * @return The traces provider */ + @SuppressWarnings("PMD.AvoidCatchingGenericException") public static TracesProvider initialize(final Properties props) { if (Boolean.parseBoolean((String) props.get(CHAINCODE_TRACES_ENABLED))) { try { @@ -46,32 +41,26 @@ public static TracesProvider initialize(final Properties props) { final String providerClass = (String) props.get(CHAINCODE_TRACES_PROVIDER); @SuppressWarnings("unchecked") // it must be this type otherwise an error - final - Class clazz = (Class) Class.forName(providerClass); + final Class clazz = (Class) Class.forName(providerClass); provider = clazz.getConstructor().newInstance(); } else { logger.info("Using default traces provider"); provider = new DefaultTracesProvider(); } - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e) { - throw new RuntimeException("Unable to start traces", e); + } catch (Exception e) { + throw new IllegalStateException("Unable to start traces", e); } } else { // return a 'null' provider logger.info("Traces disabled"); provider = new NullProvider(); - } provider.initialize(props); return provider; } - /** - * - * @return TracesProvider - */ + /** @return TracesProvider */ public static TracesProvider getProvider() { if (provider == null) { throw new IllegalStateException("No provider set, this should have been set"); diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/TracesProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/TracesProvider.java index 167120596..40c490862 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/TracesProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/TracesProvider.java @@ -8,25 +8,20 @@ import io.grpc.ClientInterceptor; import io.opentelemetry.api.trace.Span; -import org.hyperledger.fabric.shim.ChaincodeStub; - import java.util.Properties; +import org.hyperledger.fabric.shim.ChaincodeStub; /** - * Interface to be implemented to send traces on the chaincode to the - * 'backend-of-choice'. + * Interface to be implemented to send traces on the chaincode to the 'backend-of-choice'. * - * An instance of this will be created, and provided with the resources from - * which chaincode specific metrics can be collected. (via the no-argument - * constructor). + *

An instance of this will be created, and provided with the resources from which chaincode specific metrics can be + * collected. (via the no-argument constructor). * - * The choice of when, where and what to collect etc are within the remit of the - * provider. + *

The choice of when, where and what to collect etc are within the remit of the provider. * - * This is the effective call sequence. + *

This is the effective call sequence. * - * MyTracesProvider mmp = new MyTracesProvider() - * mmp.initialize(props_from_environment); // short while later.... + *

MyTracesProvider mmp = new MyTracesProvider() mmp.initialize(props_from_environment); // short while later.... * mmp.setTaskTracesCollector(taskService); */ public interface TracesProvider { @@ -37,21 +32,23 @@ public interface TracesProvider { * @param props */ default void initialize(final Properties props) { - }; + // Do nothing by default + } /** * Creates a span with metadata of the current chaincode execution, possibly linked to the execution arguments. + * * @param stub the context of the chaincode execution - * @return a new span if traces are enabled, or null. - * The caller is responsible for closing explicitly the span. + * @return a new span if traces are enabled, or null. The caller is responsible for closing explicitly the span. */ default Span createSpan(ChaincodeStub stub) { return null; } /** - * Creates an interceptor of gRPC messages that can be injected in processing incoming messages to extract - * trace information. + * Creates an interceptor of gRPC messages that can be injected in processing incoming messages to extract trace + * information. + * * @return a new client interceptor, or null if no interceptor is set. */ default ClientInterceptor createInterceptor() { diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/DefaultTracesProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/DefaultTracesProvider.java index 1ea5b982a..0153cc9c0 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/DefaultTracesProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/DefaultTracesProvider.java @@ -7,5 +7,4 @@ import org.hyperledger.fabric.traces.TracesProvider; -public final class DefaultTracesProvider implements TracesProvider { -} +public final class DefaultTracesProvider implements TracesProvider {} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/NullProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/NullProvider.java index 15818d5ea..fa851edd9 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/NullProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/NullProvider.java @@ -7,5 +7,4 @@ import org.hyperledger.fabric.traces.TracesProvider; -public final class NullProvider implements TracesProvider { -} +public final class NullProvider implements TracesProvider {} diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryProperties.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryProperties.java index 38c0fb722..da954aee6 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryProperties.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryProperties.java @@ -7,8 +7,6 @@ import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; - -import javax.annotation.Nullable; import java.time.Duration; import java.util.AbstractMap; import java.util.Arrays; @@ -18,86 +16,79 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import javax.annotation.Nullable; final class OpenTelemetryProperties implements ConfigProperties { private final Map config; - OpenTelemetryProperties(final Map... arrayOfProperties) { + @SafeVarargs + OpenTelemetryProperties(final Map... arrayOfProperties) { Map config = new HashMap<>(); - for (Map props : arrayOfProperties) { - props.forEach((key, value) -> - config.put(((String) key).toLowerCase(Locale.ROOT).replace('-', '.'), (String) value)); + for (Map props : arrayOfProperties) { + props.forEach( + (key, value) -> config.put(key.toLowerCase(Locale.ROOT).replace('-', '.'), value)); } this.config = config; } @Override - @Nullable - public String getString(final String name) { + @Nullable public String getString(final String name) { return config.get(name); } @Override - @Nullable - public Boolean getBoolean(final String name) { + @Nullable public Boolean getBoolean(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { return null; } - return Boolean.parseBoolean(value); + return Boolean.valueOf(value); } @Override - @Nullable - @SuppressWarnings("UnusedException") - public Integer getInt(final String name) { + @Nullable public Integer getInt(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { return null; } try { - return Integer.parseInt(value); + return Integer.valueOf(value); } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "integer"); + throw newInvalidPropertyException(name, value, "integer", ex); } } @Override - @Nullable - @SuppressWarnings("UnusedException") - public Long getLong(final String name) { + @Nullable public Long getLong(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { return null; } try { - return Long.parseLong(value); + return Long.valueOf(value); } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "long"); + throw newInvalidPropertyException(name, value, "long", ex); } } @Override - @Nullable - @SuppressWarnings("UnusedException") - public Double getDouble(final String name) { + @Nullable public Double getDouble(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { return null; } try { - return Double.parseDouble(value); + return Double.valueOf(value); } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "double"); + throw newInvalidPropertyException(name, value, "double", ex); } } @Override - @Nullable - @SuppressWarnings("UnusedException") - public Duration getDuration(final String name) { + @Nullable public Duration getDuration(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { return null; @@ -106,19 +97,15 @@ public Duration getDuration(final String name) { String numberString = value.substring(0, value.length() - unitString.length()); try { long rawNumber = Long.parseLong(numberString.trim()); - TimeUnit unit = getDurationUnit(unitString.trim()); + TimeUnit unit = getDurationUnit(unitString.trim()) + .orElseThrow(() -> new ConfigurationException( + "Invalid duration property " + name + "=" + value + ". Invalid duration unit.")); return Duration.ofMillis(TimeUnit.MILLISECONDS.convert(rawNumber, unit)); } catch (NumberFormatException ex) { - throw new ConfigurationException( - "Invalid duration property " - + name - + "=" - + value - + ". Expected number, found: " - + numberString); - } catch (ConfigurationException ex) { - throw new ConfigurationException( - "Invalid duration property " + name + "=" + value + ". " + ex.getMessage()); + var e = new ConfigurationException( + "Invalid duration property " + name + "=" + value + ". Expected number, found: " + numberString); + e.addSuppressed(ex); + throw e; } } @@ -132,58 +119,55 @@ public List getList(final String name) { } @Override + @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public Map getMap(final String name) { return getList(name).stream() .map(keyValuePair -> filterBlanksAndNulls(keyValuePair.split("=", 2))) - .map( - splitKeyValuePairs -> { - if (splitKeyValuePairs.size() != 2) { - throw new ConfigurationException( - "Invalid map property: " + name + "=" + config.get(name)); - } - return new AbstractMap.SimpleImmutableEntry<>( - splitKeyValuePairs.get(0), splitKeyValuePairs.get(1)); - }) + .map(splitKeyValuePairs -> { + if (splitKeyValuePairs.size() != 2) { + throw new ConfigurationException("Invalid map property: " + name + "=" + config.get(name)); + } + return new AbstractMap.SimpleImmutableEntry<>(splitKeyValuePairs.get(0), splitKeyValuePairs.get(1)); + }) // If duplicate keys, prioritize later ones similar to duplicate system properties on a // Java command line. - .collect( - Collectors.toMap( - Map.Entry::getKey, Map.Entry::getValue, (first, next) -> next, LinkedHashMap::new)); + .collect(Collectors.toMap( + Map.Entry::getKey, Map.Entry::getValue, (first, next) -> next, LinkedHashMap::new)); } private static ConfigurationException newInvalidPropertyException( - final String name, final String value, final String type) { - throw new ConfigurationException( + final String name, final String value, final String type, final Exception cause) { + var e = new ConfigurationException( "Invalid value for property " + name + "=" + value + ". Must be a " + type + "."); + e.addSuppressed(cause); + throw e; } private static List filterBlanksAndNulls(final String[] values) { - return Arrays.stream(values) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toList()); + return Arrays.stream(values).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList()); } /** * Returns the TimeUnit associated with a unit string. Defaults to milliseconds. + * * @param unitString the time unit as a string * @return the parsed TimeUnit */ - private static TimeUnit getDurationUnit(final String unitString) { + private static Optional getDurationUnit(final String unitString) { switch (unitString) { case "": // Fallthrough expected case "ms": - return TimeUnit.MILLISECONDS; + return Optional.of(TimeUnit.MILLISECONDS); case "s": - return TimeUnit.SECONDS; + return Optional.of(TimeUnit.SECONDS); case "m": - return TimeUnit.MINUTES; + return Optional.of(TimeUnit.MINUTES); case "h": - return TimeUnit.HOURS; + return Optional.of(TimeUnit.HOURS); case "d": - return TimeUnit.DAYS; + return Optional.of(TimeUnit.DAYS); default: - throw new ConfigurationException("Invalid duration string, found: " + unitString); + return Optional.empty(); } } @@ -191,6 +175,7 @@ private static TimeUnit getDurationUnit(final String unitString) { * Fragments the 'units' portion of a config value from the 'value' portion. * *

E.g. "1ms" would return the string "ms". + * * @param rawValue the raw value of a unit and value * @return the unit string */ diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProvider.java index 696aececb..54a3034f0 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProvider.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProvider.java @@ -14,13 +14,11 @@ import io.opentelemetry.instrumentation.grpc.v1_6.GrpcTelemetry; import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; import io.opentelemetry.semconv.ResourceAttributes; - -import org.hyperledger.fabric.shim.ChaincodeStub; -import org.hyperledger.fabric.traces.TracesProvider; - import java.util.HashMap; import java.util.Map; import java.util.Properties; +import org.hyperledger.fabric.shim.ChaincodeStub; +import org.hyperledger.fabric.traces.TracesProvider; public final class OpenTelemetryTracesProvider implements TracesProvider { diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/package-info.java index b8aef10b1..dd29ef78d 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/impl/package-info.java @@ -1,6 +1,6 @@ -/* - * Copyright 2023 IBM All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.hyperledger.fabric.traces.impl; +/* + * Copyright 2023 IBM All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.fabric.traces.impl; diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/package-info.java index 07ffd3eeb..147b57951 100644 --- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/package-info.java +++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/traces/package-info.java @@ -5,15 +5,12 @@ */ /** - *

* Supports collection of traces - *

- * This creates traces at the root level of chaincode calls. * + *

This creates traces at the root level of chaincode calls. * - * To enable traces ensure that there is a standard format Java properties file - * called `config.props` in the root of your contract code. For example this - * path + *

To enable traces ensure that there is a standard format Java properties file called `config.props` in the root of + * your contract code. For example this path * *

  * myjava - contract - project / java / src / main / resources / config.props
@@ -25,15 +22,11 @@
  * CHAINCODE_TRACES_ENABLED=true
  * 
* - * The traces enabled flag will turn on default traces logging. (it's off by - * default). + * The traces enabled flag will turn on default traces logging. (it's off by default). * - * If no file is supplied traces are not enabled, the values shown for the - * thread pool are used. + *

If no file is supplied traces are not enabled, the values shown for the thread pool are used. * - *

Open Telemetry

- * - * To use Open Telemetry, set the following properties: + *

Open Telemetry To use Open Telemetry, set the following properties: * *

  * CHAINCODE_TRACES_ENABLED=true
@@ -43,7 +36,8 @@
  * Additionally, you can set properties after the specification:
  * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md
  *
- * Example:
+ * 

Example: + * *

  * OTEL_EXPORTER_OTLP_ENDPOINT=otelcollector:4317
  * OTEL_EXPORTER_OTLP_INSECURE=true
diff --git a/fabric-chaincode-shim/src/test/java/ChaincodeWithoutPackageTest.java b/fabric-chaincode-shim/src/test/java/ChaincodeWithoutPackageTest.java
index f62b044ce..60d7c5fff 100644
--- a/fabric-chaincode-shim/src/test/java/ChaincodeWithoutPackageTest.java
+++ b/fabric-chaincode-shim/src/test/java/ChaincodeWithoutPackageTest.java
@@ -4,6 +4,13 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
 import org.hyperledger.fabric.shim.ChaincodeBase;
 import org.hyperledger.fabric.shim.mock.peer.ChaincodeMockPeer;
 import org.hyperledger.fabric.shim.mock.peer.RegisterStep;
@@ -11,19 +18,11 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
-
-public final class ChaincodeWithoutPackageTest {
+final class ChaincodeWithoutPackageTest {
     private ChaincodeMockPeer server;
 
     @AfterEach
-    public void afterTest() throws Exception {
+    void afterTest() throws Exception {
         if (server != null) {
             server.stop();
             server = null;
@@ -31,7 +30,7 @@ public void afterTest() throws Exception {
     }
 
     @Test
-    public void testRegisterChaincodeWithoutPackage() throws Exception {
+    void testRegisterChaincodeWithoutPackage() throws Exception {
         final ChaincodeBase cb = new EmptyChaincodeWithoutPackage();
 
         final List scenario = new ArrayList<>();
@@ -39,12 +38,11 @@ public void testRegisterChaincodeWithoutPackage() throws Exception {
 
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         assertThat(server.getLastMessageSend().getType()).isEqualTo(READY);
         assertThat(server.getLastMessageRcvd().getType()).isEqualTo(REGISTER);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/contract/Greeting.java b/fabric-chaincode-shim/src/test/java/contract/Greeting.java
index b2c3bc7f2..ac49bf4fa 100644
--- a/fabric-chaincode-shim/src/test/java/contract/Greeting.java
+++ b/fabric-chaincode-shim/src/test/java/contract/Greeting.java
@@ -5,6 +5,8 @@
  */
 package contract;
 
+import static org.assertj.core.api.Assertions.assertThat;
+
 import org.hyperledger.fabric.contract.annotation.DataType;
 import org.hyperledger.fabric.contract.annotation.Property;
 import org.json.JSONObject;
@@ -53,18 +55,11 @@ public Greeting(final String text) {
     public static void validate(final Greeting greeting) {
         final String text = greeting.text;
 
-        if (text.length() != greeting.textLength) {
-            throw new Error("Length incorrectly set");
-        }
-
-        if (text.split(" ").length != greeting.wordCount) {
-            throw new Error("Word count incorrectly set");
-        }
-
+        assertThat(text).as("greeting length").hasSize(greeting.textLength);
+        assertThat(text.split(" ")).as("word count").hasSize(greeting.wordCount);
     }
 
     public String toJSONString() {
         return new JSONObject(this).toString();
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/contract/SampleContract.java b/fabric-chaincode-shim/src/test/java/contract/SampleContract.java
index c10b41548..426aab7c8 100644
--- a/fabric-chaincode-shim/src/test/java/contract/SampleContract.java
+++ b/fabric-chaincode-shim/src/test/java/contract/SampleContract.java
@@ -6,7 +6,6 @@
 package contract;
 
 import java.util.List;
-
 import org.hyperledger.fabric.contract.Context;
 import org.hyperledger.fabric.contract.ContractInterface;
 import org.hyperledger.fabric.contract.annotation.Contact;
@@ -19,14 +18,13 @@
 
 @Contract(
         name = "samplecontract",
-        info = @Info(
-                contact = @Contact(
-                        email = "fred@example.com"),
-                license = @License(
-                        name = "fred",
-                        url = "http://fred.me"),
-                version = "0.0.1",
-                title = "samplecontract"))
+        info =
+                @Info(
+                        contact = @Contact(email = "fred@example.com"),
+                        license = @License(name = "fred", url = "http://fred.me"),
+                        version = "0.0.1",
+                        title = "samplecontract"))
+@SuppressWarnings("PMD.SystemPrintln")
 @Default()
 public class SampleContract implements ContractInterface {
     public static int getBeforeInvoked() {
@@ -112,7 +110,7 @@ public String t3(final Context ctx, final String exception, final String message
                 throw new ChaincodeException(message, "T3ERR1");
             }
         } else {
-            throw new RuntimeException(message);
+            throw new IllegalArgumentException(message);
         }
     }
 
@@ -127,9 +125,7 @@ public String t2(final Context ctx) {
         return "Transaction 2";
     }
 
-    /**
-     * @param ctx
-     */
+    /** @param ctx */
     @Transaction
     public void noReturn(final Context ctx) {
         System.out.println("SampleContract::noReturn done");
@@ -150,17 +146,13 @@ public String t1(final Context ctx, final String arg1) {
         return args.get(1);
     }
 
-    /**
-     *
-     */
+    /** */
     @Override
     public void beforeTransaction(final Context ctx) {
         beforeInvoked++;
     }
 
-    /**
-     *
-     */
+    /** */
     @Override
     public void afterTransaction(final Context ctx, final Object value) {
         afterInvoked++;
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggerTest.java
index cd99c74cc..90c327d66 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggerTest.java
@@ -9,15 +9,15 @@
 import org.hyperledger.fabric.contract.ContractRuntimeException;
 import org.junit.jupiter.api.Test;
 
-public class LoggerTest {
+class LoggerTest {
     @Test
-    public void logger() {
+    void logger() {
         Logger.getLogger(LoggerTest.class);
         Logger.getLogger(LoggerTest.class.getName());
     }
 
     @Test
-    public void testContractException() {
+    void testContractException() {
         final Logger logger = Logger.getLogger(LoggerTest.class);
 
         final ContractRuntimeException cre1 = new ContractRuntimeException("");
@@ -29,11 +29,10 @@ public void testContractException() {
 
         logger.error("all gone wrong");
         logger.error(() -> "all gone wrong");
-
     }
 
     @Test
-    public void testDebug() {
+    void testDebug() {
         Logger.getLogger(LoggerTest.class).debug("debug message");
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggingTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggingTest.java
index 6c69de43d..98c5dde8b 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggingTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/LoggingTest.java
@@ -5,20 +5,19 @@
  */
 package org.hyperledger.fabric;
 
-import org.hamcrest.CoreMatchers;
-import org.junit.jupiter.api.Test;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.logging.Level;
+import org.hamcrest.CoreMatchers;
+import org.junit.jupiter.api.Test;
 
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-public final class LoggingTest {
+final class LoggingTest {
     @Test
-    public void testMapLevel() {
+    void testMapLevel() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
 
         assertEquals(Level.SEVERE, proxyMapLevel("ERROR"), "Error maps");
         assertEquals(Level.SEVERE, proxyMapLevel("critical"), "Critical maps");
@@ -31,21 +30,15 @@ public void testMapLevel() {
         assertEquals(Level.INFO, proxyMapLevel(new Object[] {null}), "Info maps");
     }
 
-    public Object proxyMapLevel(final Object... args) {
-
-        try {
-            final Method m = Logging.class.getDeclaredMethod("mapLevel", String.class);
-            m.setAccessible(true);
-            return m.invoke(null, args);
-        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
-                | InvocationTargetException e) {
-            throw new RuntimeException(e);
-        }
-
+    private Object proxyMapLevel(final Object... args)
+            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+        final Method m = Logging.class.getDeclaredMethod("mapLevel", String.class);
+        m.setAccessible(true);
+        return m.invoke(null, args);
     }
 
     @Test
-    public void testFormatError() {
+    void testFormatError() {
         final Exception e1 = new Exception("Computer says no");
 
         assertThat(Logging.formatError(e1), containsString("Computer says no"));
@@ -60,7 +53,7 @@ public void testFormatError() {
     }
 
     @Test
-    public void testSetLogLevel() {
+    void testSetLogLevel() {
 
         final java.util.logging.Logger l = java.util.logging.Logger.getLogger("org.hyperledger.fabric.test");
         final java.util.logging.Logger another = java.util.logging.Logger.getLogger("acme.wibble");
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/TestUtil.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/TestUtil.java
index ee448f661..2aa32cfe6 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/TestUtil.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/TestUtil.java
@@ -12,7 +12,6 @@
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.Base64;
-
 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
 import org.bouncycastle.cert.X509CertificateHolder;
 import org.bouncycastle.cert.X509v3CertificateBuilder;
@@ -21,47 +20,66 @@
 
 public final class TestUtil {
 
-    private TestUtil() {
-
-    }
+    private TestUtil() {}
 
     public static final String CERT_WITHOUT_ATTRS = "MIICXTCCAgSgAwIBAgIUeLy6uQnq8wwyElU/jCKRYz3tJiQwCgYIKoZIzj0EAwIw"
-            + "eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh" + "biBGcmFuY2lzY28xGTAXBgNVBAoTEEludGVybmV0IFdpZGdldHMxDDAKBgNVBAsT"
-            + "A1dXVzEUMBIGA1UEAxMLZXhhbXBsZS5jb20wHhcNMTcwOTA4MDAxNTAwWhcNMTgw" + "OTA4MDAxNTAwWjBdMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xp"
-            + "bmExFDASBgNVBAoTC0h5cGVybGVkZ2VyMQ8wDQYDVQQLEwZGYWJyaWMxDjAMBgNV" + "BAMTBWFkbWluMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFq/90YMuH4tWugHa"
-            + "oyZtt4Mbwgv6CkBSDfYulVO1CVInw1i/k16DocQ/KSDTeTfgJxrX1Ree1tjpaodG" + "1wWyM6OBhTCBgjAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4E"
-            + "FgQUhKs/VJ9IWJd+wer6sgsgtZmxZNwwHwYDVR0jBBgwFoAUIUd4i/sLTwYWvpVr" + "TApzcT8zv/kwIgYDVR0RBBswGYIXQW5pbHMtTWFjQm9vay1Qcm8ubG9jYWwwCgYI"
-            + "KoZIzj0EAwIDRwAwRAIgCoXaCdU8ZiRKkai0QiXJM/GL5fysLnmG2oZ6XOIdwtsC" + "IEmCsI8Mhrvx1doTbEOm7kmIrhQwUVDBNXCWX1t3kJVN";
+            + "eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh"
+            + "biBGcmFuY2lzY28xGTAXBgNVBAoTEEludGVybmV0IFdpZGdldHMxDDAKBgNVBAsT"
+            + "A1dXVzEUMBIGA1UEAxMLZXhhbXBsZS5jb20wHhcNMTcwOTA4MDAxNTAwWhcNMTgw"
+            + "OTA4MDAxNTAwWjBdMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xp"
+            + "bmExFDASBgNVBAoTC0h5cGVybGVkZ2VyMQ8wDQYDVQQLEwZGYWJyaWMxDjAMBgNV"
+            + "BAMTBWFkbWluMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFq/90YMuH4tWugHa"
+            + "oyZtt4Mbwgv6CkBSDfYulVO1CVInw1i/k16DocQ/KSDTeTfgJxrX1Ree1tjpaodG"
+            + "1wWyM6OBhTCBgjAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4E"
+            + "FgQUhKs/VJ9IWJd+wer6sgsgtZmxZNwwHwYDVR0jBBgwFoAUIUd4i/sLTwYWvpVr"
+            + "TApzcT8zv/kwIgYDVR0RBBswGYIXQW5pbHMtTWFjQm9vay1Qcm8ubG9jYWwwCgYI"
+            + "KoZIzj0EAwIDRwAwRAIgCoXaCdU8ZiRKkai0QiXJM/GL5fysLnmG2oZ6XOIdwtsC"
+            + "IEmCsI8Mhrvx1doTbEOm7kmIrhQwUVDBNXCWX1t3kJVN";
 
     public static final String CERT_WITH_ATTRS = "MIIB6TCCAY+gAwIBAgIUHkmY6fRP0ANTvzaBwKCkMZZPUnUwCgYIKoZIzj0EAwIw"
-            + "GzEZMBcGA1UEAxMQZmFicmljLWNhLXNlcnZlcjAeFw0xNzA5MDgwMzQyMDBaFw0x" + "ODA5MDgwMzQyMDBaMB4xHDAaBgNVBAMTE015VGVzdFVzZXJXaXRoQXR0cnMwWTAT"
-            + "BgcqhkjOPQIBBggqhkjOPQMBBwNCAATmB1r3CdWvOOP3opB3DjJnW3CnN8q1ydiR" + "dzmuA6A2rXKzPIltHvYbbSqISZJubsy8gVL6GYgYXNdu69RzzFF5o4GtMIGqMA4G"
-            + "A1UdDwEB/wQEAwICBDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBTYKLTAvJJK08OM" + "VGwIhjMQpo2DrjAfBgNVHSMEGDAWgBTEs/52DeLePPx1+65VhgTwu3/2ATAiBgNV"
-            + "HREEGzAZghdBbmlscy1NYWNCb29rLVByby5sb2NhbDAmBggqAwQFBgcIAQQaeyJh" + "dHRycyI6eyJhdHRyMSI6InZhbDEifX0wCgYIKoZIzj0EAwIDSAAwRQIhAPuEqWUp"
+            + "GzEZMBcGA1UEAxMQZmFicmljLWNhLXNlcnZlcjAeFw0xNzA5MDgwMzQyMDBaFw0x"
+            + "ODA5MDgwMzQyMDBaMB4xHDAaBgNVBAMTE015VGVzdFVzZXJXaXRoQXR0cnMwWTAT"
+            + "BgcqhkjOPQIBBggqhkjOPQMBBwNCAATmB1r3CdWvOOP3opB3DjJnW3CnN8q1ydiR"
+            + "dzmuA6A2rXKzPIltHvYbbSqISZJubsy8gVL6GYgYXNdu69RzzFF5o4GtMIGqMA4G"
+            + "A1UdDwEB/wQEAwICBDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBTYKLTAvJJK08OM"
+            + "VGwIhjMQpo2DrjAfBgNVHSMEGDAWgBTEs/52DeLePPx1+65VhgTwu3/2ATAiBgNV"
+            + "HREEGzAZghdBbmlscy1NYWNCb29rLVByby5sb2NhbDAmBggqAwQFBgcIAQQaeyJh"
+            + "dHRycyI6eyJhdHRyMSI6InZhbDEifX0wCgYIKoZIzj0EAwIDSAAwRQIhAPuEqWUp"
             + "svTTvBqLR5JeQSctJuz3zaqGRqSs2iW+QB3FAiAIP0mGWKcgSGRMMBvaqaLytBYo" + "9v3hRt1r8j8vN0pMcg==";
 
     public static final String CERT_WITH_DNS = "MIICGjCCAcCgAwIBAgIRAIPRwJHVLhHK47XK0BbFZJswCgYIKoZIzj0EAwIwczEL"
-            + "MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG" + "cmFuY2lzY28xGTAXBgNVBAoTEG9yZzIuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh"
-            + "Lm9yZzIuZXhhbXBsZS5jb20wHhcNMTcwNjIzMTIzMzE5WhcNMjcwNjIxMTIzMzE5" + "WjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN"
-            + "U2FuIEZyYW5jaXNjbzEfMB0GA1UEAwwWVXNlcjFAb3JnMi5leGFtcGxlLmNvbTBZ" + "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABBd9SsEiFH1/JIb3qMEPLR2dygokFVKW"
-            + "eINcB0Ni4TBRkfIWWUJeCANTUY11Pm/+5gs+fBTqBz8M2UzpJDVX7+2jTTBLMA4G" + "A1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIKfUfvpGproH"
-            + "cwyFD+0sE3XfJzYNcif0jNwvgOUFZ4AFMAoGCCqGSM49BAMCA0gAMEUCIQC8NIMw" + "e4ym/QRwCJb5umbONNLSVQuEpnPsJrM/ssBPvgIgQpe2oYa3yO3USro9nBHjpM3L"
+            + "MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG"
+            + "cmFuY2lzY28xGTAXBgNVBAoTEG9yZzIuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh"
+            + "Lm9yZzIuZXhhbXBsZS5jb20wHhcNMTcwNjIzMTIzMzE5WhcNMjcwNjIxMTIzMzE5"
+            + "WjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN"
+            + "U2FuIEZyYW5jaXNjbzEfMB0GA1UEAwwWVXNlcjFAb3JnMi5leGFtcGxlLmNvbTBZ"
+            + "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABBd9SsEiFH1/JIb3qMEPLR2dygokFVKW"
+            + "eINcB0Ni4TBRkfIWWUJeCANTUY11Pm/+5gs+fBTqBz8M2UzpJDVX7+2jTTBLMA4G"
+            + "A1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIKfUfvpGproH"
+            + "cwyFD+0sE3XfJzYNcif0jNwvgOUFZ4AFMAoGCCqGSM49BAMCA0gAMEUCIQC8NIMw"
+            + "e4ym/QRwCJb5umbONNLSVQuEpnPsJrM/ssBPvgIgQpe2oYa3yO3USro9nBHjpM3L"
             + "KsFQrpVnF8O6hoHOYZQ=";
 
-    public static final String CERT_MULTIPLE_ATTRIBUTES = "MIIChzCCAi6gAwIBAgIURilAHeqwLu/fNUv8eZoGPRh3H4IwCgYIKoZIzj0EAwIw"
-            + "czELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh" + "biBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT"
-            + "E2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTkwNzMxMTYxNzAwWhcNMjAwNzMwMTYy" + "MjAwWjAgMQ8wDQYDVQQLEwZjbGllbnQxDTALBgNVBAMTBHRlc3QwWTATBgcqhkjO"
-            + "PQIBBggqhkjOPQMBBwNCAAR2taQK8w7D3hr3gBxCz+8eV4KSv7pFQfNjDHMMe9J9" + "LJwcLpVTT5hYiLLRaqQonLBxBE3Ey0FneySvFuBScas3o4HyMIHvMA4GA1UdDwEB"
-            + "/wQEAwIHgDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBQi3mhXS/WzcjBniwAmPdYP" + "kHqVVzArBgNVHSMEJDAigCC7VXjmSEugjAB/A0S6vfMxLsUIgag9WVNwtwwebnRC"
-            + "7TCBggYIKgMEBQYHCAEEdnsiYXR0cnMiOnsiYXR0cjEiOiJ2YWwxIiwiZm9vIjoi" + "YmFyIiwiaGVsbG8iOiJ3b3JsZCIsImhmLkFmZmlsaWF0aW9uIjoiIiwiaGYuRW5y"
-            + "b2xsbWVudElEIjoidGVzdCIsImhmLlR5cGUiOiJjbGllbnQifX0wCgYIKoZIzj0E" + "AwIDRwAwRAIgQxEFvnZTEsf3CSZmp9IYsxcnEOtVYleOd86LAKtk1wICIH7XOPwW"
-            + "/RE4Z8WLZzFei/78Oezbx6obOvBxPMsVWRe5";
+    public static final String CERT_MULTIPLE_ATTRIBUTES =
+            "MIIChzCCAi6gAwIBAgIURilAHeqwLu/fNUv8eZoGPRh3H4IwCgYIKoZIzj0EAwIw"
+                    + "czELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh"
+                    + "biBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT"
+                    + "E2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTkwNzMxMTYxNzAwWhcNMjAwNzMwMTYy"
+                    + "MjAwWjAgMQ8wDQYDVQQLEwZjbGllbnQxDTALBgNVBAMTBHRlc3QwWTATBgcqhkjO"
+                    + "PQIBBggqhkjOPQMBBwNCAAR2taQK8w7D3hr3gBxCz+8eV4KSv7pFQfNjDHMMe9J9"
+                    + "LJwcLpVTT5hYiLLRaqQonLBxBE3Ey0FneySvFuBScas3o4HyMIHvMA4GA1UdDwEB"
+                    + "/wQEAwIHgDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBQi3mhXS/WzcjBniwAmPdYP"
+                    + "kHqVVzArBgNVHSMEJDAigCC7VXjmSEugjAB/A0S6vfMxLsUIgag9WVNwtwwebnRC"
+                    + "7TCBggYIKgMEBQYHCAEEdnsiYXR0cnMiOnsiYXR0cjEiOiJ2YWwxIiwiZm9vIjoi"
+                    + "YmFyIiwiaGVsbG8iOiJ3b3JsZCIsImhmLkFmZmlsaWF0aW9uIjoiIiwiaGYuRW5y"
+                    + "b2xsbWVudElEIjoidGVzdCIsImhmLlR5cGUiOiJjbGllbnQifX0wCgYIKoZIzj0E"
+                    + "AwIDRwAwRAIgQxEFvnZTEsf3CSZmp9IYsxcnEOtVYleOd86LAKtk1wICIH7XOPwW"
+                    + "/RE4Z8WLZzFei/78Oezbx6obOvBxPMsVWRe5";
 
     /**
      * Function to create a certificate with dummy attributes
      *
-     * @param attributeValue {String} value to be written to the identity attributes
-     *                       section of the certificate
+     * @param attributeValue {String} value to be written to the identity attributes section of the certificate
      * @return encodedCert {String} encoded certificate with re-written attributes
      */
     public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception {
@@ -90,7 +108,6 @@ public static String createCertWithIdentityAttributes(final String attributeValu
         final X509CertificateHolder builtCert = certBuilder.build(contentSigner);
         final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509")
                 .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded()));
-        final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded());
-        return encodedCert;
+        return Base64.getEncoder().encodeToString(certificate.getEncoded());
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/AllTypesAsset.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/AllTypesAsset.java
index 6852d616a..4b4ed224c 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/AllTypesAsset.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/AllTypesAsset.java
@@ -27,7 +27,8 @@ public final class AllTypesAsset {
     private float theFloat = 3.1415926535_8979323846_2643383279_5028841971_6939937510_5820974944_5923078164f;
 
     @Property
-    private double theDouble = 3.1415926535_8979323846_2643383279_5028841971_6939937510_5820974944_5923078164_0628620899_8628034825_3421170679d;
+    private double theDouble =
+            3.1415926535_8979323846_2643383279_5028841971_6939937510_5820974944_5923078164_0628620899_8628034825_3421170679d;
 
     @Property
     private boolean theBoolean = false;
@@ -121,25 +122,34 @@ public void setTheCustomObject(final MyType customObject) {
         this.theCustomObject = customObject;
     }
 
-    public boolean equals(final AllTypesAsset obj) {
-        return theByte == obj.getTheByte() && theShort == obj.getTheShort() && theInt == obj.getTheInt() && theLong == obj.getTheLong()
-                && theFloat == obj.getTheFloat() && theDouble == obj.getTheDouble() && theBoolean == obj.isTheBoolean() && theString.equals(obj.getTheString());
+    @Override
+    public boolean equals(final Object other) {
+        if (!(other instanceof AllTypesAsset)) {
+            return false;
+        }
+
+        AllTypesAsset obj = (AllTypesAsset) other;
+        return theByte == obj.getTheByte()
+                && theShort == obj.getTheShort()
+                && theInt == obj.getTheInt()
+                && theLong == obj.getTheLong()
+                && theFloat == obj.getTheFloat()
+                && theDouble == obj.getTheDouble()
+                && theBoolean == obj.isTheBoolean()
+                && theString.equals(obj.getTheString());
     }
 
     @Override
     public String toString() {
-        final StringBuilder builder = new StringBuilder(System.lineSeparator());
-        builder.append("byte=" + theByte).append(System.lineSeparator());
-        builder.append("short=" + theShort).append(System.lineSeparator());
-        builder.append("int=" + theInt).append(System.lineSeparator());
-        builder.append("long=" + theLong).append(System.lineSeparator());
-        builder.append("float=" + theFloat).append(System.lineSeparator());
-        builder.append("double=" + theDouble).append(System.lineSeparator());
-        builder.append("boolean=" + theBoolean).append(System.lineSeparator());
-        builder.append("char=" + theChar).append(System.lineSeparator());
-        builder.append("String=" + theString).append(System.lineSeparator());
-        builder.append("Mytype=" + theCustomObject).append(System.lineSeparator());
-
-        return builder.toString();
+        return System.lineSeparator() + "byte=" + theByte + System.lineSeparator() + "short="
+                + theShort + System.lineSeparator() + "int="
+                + theInt + System.lineSeparator() + "long="
+                + theLong + System.lineSeparator() + "float="
+                + theFloat + System.lineSeparator() + "double="
+                + theDouble + System.lineSeparator() + "boolean="
+                + theBoolean + System.lineSeparator() + "char="
+                + theChar + System.lineSeparator() + "String="
+                + theString + System.lineSeparator() + "Mytype="
+                + theCustomObject + System.lineSeparator();
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ChaincodeStubNaiveImpl.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ChaincodeStubNaiveImpl.java
index dcd7c2ffb..ad4757301 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ChaincodeStubNaiveImpl.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ChaincodeStubNaiveImpl.java
@@ -5,6 +5,7 @@
  */
 package org.hyperledger.fabric.contract;
 
+import com.google.protobuf.ByteString;
 import java.nio.charset.StandardCharsets;
 import java.time.Instant;
 import java.util.ArrayList;
@@ -13,7 +14,6 @@
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
-
 import org.hyperledger.fabric.TestUtil;
 import org.hyperledger.fabric.protos.msp.SerializedIdentity;
 import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
@@ -26,8 +26,6 @@
 import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;
 import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata;
 
-import com.google.protobuf.ByteString;
-
 public final class ChaincodeStubNaiveImpl implements ChaincodeStub {
     private List args;
     private List argsAsByte;
@@ -62,7 +60,9 @@ public ChaincodeStubNaiveImpl() {
     @Override
     public List getArgs() {
         if (argsAsByte == null) {
-            argsAsByte = args.stream().map(i -> i.getBytes()).collect(Collectors.toList());
+            argsAsByte = args.stream()
+                    .map(arg -> arg.getBytes(StandardCharsets.UTF_8))
+                    .collect(Collectors.toList());
         }
         return argsAsByte;
     }
@@ -93,7 +93,8 @@ public String getChannelId() {
     }
 
     @Override
-    public Chaincode.Response invokeChaincode(final String chaincodeName, final List args, final String channel) {
+    public Chaincode.Response invokeChaincode(
+            final String chaincodeName, final List args, final String channel) {
         return resp;
     }
 
@@ -110,13 +111,10 @@ public byte[] getStateValidationParameter(final String key) {
     @Override
     public void putState(final String key, final byte[] value) {
         state.put(key, ByteString.copyFrom(value));
-
     }
 
     @Override
-    public void setStateValidationParameter(final String key, final byte[] value) {
-
-    }
+    public void setStateValidationParameter(final String key, final byte[] value) {}
 
     @Override
     public void delState(final String key) {
@@ -129,8 +127,8 @@ public QueryResultsIterator getStateByRange(final String startKey, fin
     }
 
     @Override
-    public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(final String startKey, final String endKey, final int pageSize,
-            final String bookmark) {
+    public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(
+            final String startKey, final String endKey, final int pageSize, final String bookmark) {
         return null;
     }
 
@@ -140,7 +138,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final String
     }
 
     @Override
-    public QueryResultsIterator getStateByPartialCompositeKey(final String objectType, final String... attributes) {
+    public QueryResultsIterator getStateByPartialCompositeKey(
+            final String objectType, final String... attributes) {
         return null;
     }
 
@@ -150,8 +149,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final Compos
     }
 
     @Override
-    public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(final CompositeKey compositeKey, final int pageSize,
-            final String bookmark) {
+    public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(
+            final CompositeKey compositeKey, final int pageSize, final String bookmark) {
         return null;
     }
 
@@ -171,7 +170,8 @@ public QueryResultsIterator getQueryResult(final String query) {
     }
 
     @Override
-    public QueryResultsIteratorWithMetadata getQueryResultWithPagination(final String query, final int pageSize, final String bookmark) {
+    public QueryResultsIteratorWithMetadata getQueryResultWithPagination(
+            final String query, final int pageSize, final String bookmark) {
         return null;
     }
 
@@ -196,42 +196,38 @@ public byte[] getPrivateDataValidationParameter(final String collection, final S
     }
 
     @Override
-    public void putPrivateData(final String collection, final String key, final byte[] value) {
-
-    }
+    public void putPrivateData(final String collection, final String key, final byte[] value) {}
 
     @Override
-    public void setPrivateDataValidationParameter(final String collection, final String key, final byte[] value) {
-
-    }
+    public void setPrivateDataValidationParameter(final String collection, final String key, final byte[] value) {}
 
     @Override
-    public void delPrivateData(final String collection, final String key) {
-
-    }
+    public void delPrivateData(final String collection, final String key) {}
 
     @Override
-    public void purgePrivateData(final String collection, final String key) {
-
-    }
+    public void purgePrivateData(final String collection, final String key) {}
 
     @Override
-    public QueryResultsIterator getPrivateDataByRange(final String collection, final String startKey, final String endKey) {
+    public QueryResultsIterator getPrivateDataByRange(
+            final String collection, final String startKey, final String endKey) {
         return null;
     }
 
     @Override
-    public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final String compositeKey) {
+    public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+            final String collection, final String compositeKey) {
         return null;
     }
 
     @Override
-    public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final CompositeKey compositeKey) {
+    public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+            final String collection, final CompositeKey compositeKey) {
         return null;
     }
 
     @Override
-    public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final String objectType, final String... attributes) {
+    public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+            final String collection, final String objectType, final String... attributes) {
         return null;
     }
 
@@ -241,9 +237,7 @@ public QueryResultsIterator getPrivateDataQueryResult(final String col
     }
 
     @Override
-    public void setEvent(final String name, final byte[] payload) {
-
-    }
+    public void setEvent(final String name, final byte[] payload) {}
 
     @Override
     public ChaincodeEvent getEvent() {
@@ -267,7 +261,7 @@ public byte[] getCreator() {
 
     @Override
     public Map getTransient() {
-        return null;
+        return new HashMap<>();
     }
 
     @Override
@@ -277,7 +271,7 @@ public byte[] getBinding() {
 
     void setStringArgs(final List args) {
         this.args = args;
-        this.argsAsByte = args.stream().map(i -> i.getBytes()).collect(Collectors.toList());
+        this.argsAsByte = args.stream().map(String::getBytes).collect(Collectors.toList());
     }
 
     public byte[] buildSerializedIdentity() {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ClientIdentityTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ClientIdentityTest.java
index f9dae17a4..f1da45edf 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ClientIdentityTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ClientIdentityTest.java
@@ -6,41 +6,40 @@
 
 package org.hyperledger.fabric.contract;
 
-import org.hyperledger.fabric.TestUtil;
-import org.hyperledger.fabric.shim.ChaincodeStub;
-import org.junit.jupiter.api.Test;
-
-import java.math.BigInteger;
-
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-public class ClientIdentityTest {
-    /**
-     * Test client identity can be created using certificate without attributes
-     */
+import java.math.BigInteger;
+import org.hyperledger.fabric.TestUtil;
+import org.hyperledger.fabric.shim.ChaincodeStub;
+import org.junit.jupiter.api.Test;
+
+final class ClientIdentityTest {
+    /** Test client identity can be created using certificate without attributes */
     @Test
-    public void clientIdentityWithoutAttributes() throws Exception {
+    void clientIdentityWithoutAttributes() throws Exception {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         final ClientIdentity identity = new ClientIdentity(stub);
         assertEquals(identity.getMSPID(), "testMSPID");
-        assertEquals(identity.getId(),
+        assertEquals(
+                identity.getId(),
                 "x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina, C=US::CN=example.com,"
                         + " OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US");
         assertEquals(identity.getAttributeValue("attr1"), null);
         assertEquals(identity.getAttributeValue("val1"), null);
-        assertEquals(identity.getX509Certificate().getSubjectX500Principal().toString(),
+        assertEquals(
+                identity.getX509Certificate().getSubjectX500Principal().toString(),
                 "CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina, C=US");
-        assertEquals(identity.getX509Certificate().getSerialNumber(), new BigInteger("689287698446788666856807436918134903862142510628"));
+        assertEquals(
+                identity.getX509Certificate().getSerialNumber(),
+                new BigInteger("689287698446788666856807436918134903862142510628"));
     }
 
-    /**
-     * Test client identity can be created using certificate with attributes
-     */
+    /** Test client identity can be created using certificate with attributes */
     @Test
-    public void clientIdentityWithAttributes() throws Exception {
+    void clientIdentityWithAttributes() throws Exception {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         ((ChaincodeStubNaiveImpl) stub).setCertificate(TestUtil.CERT_WITH_ATTRS);
         final ClientIdentity identity = new ClientIdentity(stub);
@@ -52,20 +51,21 @@ public void clientIdentityWithAttributes() throws Exception {
         assertEquals(identity.assertAttributeValue("attr1", "val2"), false);
         assertEquals(identity.assertAttributeValue("attr2", "val1"), false);
         assertEquals(identity.getX509Certificate().getSubjectX500Principal().toString(), "CN=MyTestUserWithAttrs");
-        assertEquals(identity.getX509Certificate().getSerialNumber(), new BigInteger("172910998202207082780622887076293058980152824437"));
+        assertEquals(
+                identity.getX509Certificate().getSerialNumber(),
+                new BigInteger("172910998202207082780622887076293058980152824437"));
     }
 
-    /**
-     * Test client identity can be created using certificate with multiple
-     * attributes
-     */
+    /** Test client identity can be created using certificate with multiple attributes */
     @Test
-    public void clientIdentityWithMultipleAttributes() throws Exception {
+    void clientIdentityWithMultipleAttributes() throws Exception {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         ((ChaincodeStubNaiveImpl) stub).setCertificate(TestUtil.CERT_MULTIPLE_ATTRIBUTES);
         final ClientIdentity identity = new ClientIdentity(stub);
         assertEquals(identity.getMSPID(), "testMSPID");
-        assertEquals(identity.getId(), "x509::CN=test, OU=client::CN=ca.org1.example.com, O=org1.example.com, L=San Francisco, ST=California, C=US");
+        assertEquals(
+                identity.getId(),
+                "x509::CN=test, OU=client::CN=ca.org1.example.com, O=org1.example.com, L=San Francisco, ST=California, C=US");
         assertEquals(identity.getAttributeValue("hello"), "world");
         assertEquals(identity.getAttributeValue("foo"), "bar");
         assertEquals(identity.getAttributeValue("attr1"), "val1");
@@ -74,50 +74,48 @@ public void clientIdentityWithMultipleAttributes() throws Exception {
         assertEquals(identity.assertAttributeValue("attr1", "val2"), false);
         assertEquals(identity.assertAttributeValue("hello", "val1"), false);
         assertEquals(identity.getX509Certificate().getSubjectX500Principal().toString(), "CN=test, OU=client");
-        assertEquals(identity.getX509Certificate().getSerialNumber(), new BigInteger("400549269877250942864348502164024974865235124098"));
+        assertEquals(
+                identity.getX509Certificate().getSerialNumber(),
+                new BigInteger("400549269877250942864348502164024974865235124098"));
     }
 
-    /**
-     * Test client identity can be created using certificate with long distinguished
-     * name
-     */
+    /** Test client identity can be created using certificate with long distinguished name */
     @Test
-    public void clientIdentityWithLongDNs() throws Exception {
+    void clientIdentityWithLongDNs() throws Exception {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         ((ChaincodeStubNaiveImpl) stub).setCertificate(TestUtil.CERT_WITH_DNS);
         final ClientIdentity identity = new ClientIdentity(stub);
         assertEquals(identity.getMSPID(), "testMSPID");
-        assertEquals(identity.getId(),
+        assertEquals(
+                identity.getId(),
                 "x509::CN=User1@org2.example.com, L=San Francisco, ST=California,"
-                + " C=US::CN=ca.org2.example.com, O=org2.example.com, L=San Francisco, ST=California, C=US");
-        assertEquals(identity.getX509Certificate().getSubjectX500Principal().toString(), "CN=User1@org2.example.com, L=San Francisco, ST=California, C=US");
-        assertEquals(identity.getX509Certificate().getSerialNumber(), new BigInteger("175217963267961225716341475631843075227"));
+                        + " C=US::CN=ca.org2.example.com, O=org2.example.com, L=San Francisco, ST=California, C=US");
+        assertEquals(
+                identity.getX509Certificate().getSubjectX500Principal().toString(),
+                "CN=User1@org2.example.com, L=San Francisco, ST=California, C=US");
+        assertEquals(
+                identity.getX509Certificate().getSerialNumber(),
+                new BigInteger("175217963267961225716341475631843075227"));
     }
 
-    /**
-     * Test client identity throws a ContractRuntimeException when creating a
-     * serialized identity fails
-     */
+    /** Test client identity throws a ContractRuntimeException when creating a serialized identity fails */
     @Test
-    public void catchInvalidProtocolBufferException() {
+    void catchInvalidProtocolBufferException() {
         final ChaincodeStub stub = mock(ChaincodeStub.class);
         when(stub.getCreator()).thenReturn("somethingInvalid".getBytes());
 
         assertThatThrownBy(() -> ContextFactory.getInstance().createContext(stub))
                 .isInstanceOf(ContractRuntimeException.class)
                 .hasMessage("Could not create new client identity");
-
     }
 
-    /**
-     * Test client identity attributes are empty when using a certificate with dummy
-     * attributes
-     */
+    /** Test client identity attributes are empty when using a certificate with dummy attributes */
     @Test
-    public void createClientIdentityWithDummyAttributesCert() throws Exception {
+    void createClientIdentityWithDummyAttributesCert() throws Exception {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         // Create a certificate with rubbish attributes
-        final String certWithDummyAttrs = TestUtil.createCertWithIdentityAttributes("{gsdhrlxhvcilgwoueglfs,djhzxo;vjs.dcx }");
+        final String certWithDummyAttrs =
+                TestUtil.createCertWithIdentityAttributes("{gsdhrlxhvcilgwoueglfs,djhzxo;vjs.dcx }");
         ((ChaincodeStubNaiveImpl) stub).setCertificate(certWithDummyAttrs);
         final ClientIdentity identity = new ClientIdentity(stub);
 
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextFactoryTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextFactoryTest.java
index a10ef5de9..4686080ba 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextFactoryTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextFactoryTest.java
@@ -5,27 +5,26 @@
  */
 package org.hyperledger.fabric.contract;
 
-import org.hyperledger.fabric.shim.ChaincodeStub;
-import org.junit.jupiter.api.Test;
-
-import java.util.Collections;
-
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
 
-public class ContextFactoryTest {
+import java.util.Collections;
+import org.hyperledger.fabric.shim.ChaincodeStub;
+import org.junit.jupiter.api.Test;
+
+final class ContextFactoryTest {
 
     @Test
-    public void getInstance() {
+    void getInstance() {
         final ContextFactory f1 = ContextFactory.getInstance();
         final ContextFactory f2 = ContextFactory.getInstance();
         assertThat(f1, sameInstance(f2));
     }
 
     @Test
-    public void createContext() {
+    void createContext() {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         final Context ctx = ContextFactory.getInstance().createContext(stub);
 
@@ -35,7 +34,8 @@ public void createContext() {
         assertThat(stub.getParameters(), is(equalTo(ctx.getStub().getParameters())));
         assertThat(stub.getTxId(), is(equalTo(ctx.getStub().getTxId())));
         assertThat(stub.getChannelId(), is(equalTo(ctx.getStub().getChannelId())));
-        assertThat(stub.invokeChaincode("cc", Collections.emptyList(), "ch0"),
+        assertThat(
+                stub.invokeChaincode("cc", Collections.emptyList(), "ch0"),
                 is(equalTo(ctx.getStub().invokeChaincode("cc", Collections.emptyList(), "ch0"))));
 
         assertThat(stub.getState("a"), is(equalTo(ctx.getStub().getState("a"))));
@@ -43,8 +43,9 @@ public void createContext() {
         assertThat(stub.getStringState("b"), is(equalTo(ctx.getStub().getStringState("b"))));
 
         assertThat(ctx.clientIdentity.getMSPID(), is(equalTo("testMSPID")));
-        assertThat(ctx.clientIdentity.getId(), is(equalTo(
-                "x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina,"
-                + " C=US::CN=example.com, OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US")));
+        assertThat(
+                ctx.clientIdentity.getId(),
+                is(equalTo("x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina,"
+                        + " C=US::CN=example.com, OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US")));
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextTest.java
index 2d3bf0886..85aa8b751 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContextTest.java
@@ -5,33 +5,28 @@
  */
 package org.hyperledger.fabric.contract;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.sameInstance;
+
 import org.hyperledger.fabric.shim.ChaincodeStub;
 import org.junit.jupiter.api.Test;
 
-import static org.hamcrest.Matchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class ContextTest {
+final class ContextTest {
 
-    /**
-     * Test creating a new context returns what we expect
-     */
+    /** Test creating a new context returns what we expect */
     @Test
-    public void getInstance() {
+    void getInstance() {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         final Context context1 = new Context(stub);
         final Context context2 = new Context(stub);
         assertThat(context1.getStub(), sameInstance(context2.getStub()));
     }
 
-    /**
-     * Test identity created in Context constructor matches getClientIdentity
-     */
+    /** Test identity created in Context constructor matches getClientIdentity */
     @Test
-    public void getSetClientIdentity() {
+    void getSetClientIdentity() {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         final Context context = ContextFactory.getInstance().createContext(stub);
         assertThat(context.getClientIdentity(), sameInstance(context.clientIdentity));
-
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractInterfaceTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractInterfaceTest.java
index a3b468fe0..7df683c47 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractInterfaceTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractInterfaceTest.java
@@ -5,25 +5,24 @@
  */
 package org.hyperledger.fabric.contract;
 
-import org.hyperledger.fabric.shim.ChaincodeException;
-import org.junit.jupiter.api.Test;
-
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.instanceOf;
 import static org.hamcrest.Matchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
 
-public class ContractInterfaceTest {
+import org.hyperledger.fabric.shim.ChaincodeException;
+import org.junit.jupiter.api.Test;
+
+final class ContractInterfaceTest {
     @Test
-    public void createContext() {
-        assertThat((new ContractInterface() {
-        }).createContext(new ChaincodeStubNaiveImpl()), is(instanceOf(Context.class)));
+    void createContext() {
+        assertThat(
+                new ContractInterface() {}.createContext(new ChaincodeStubNaiveImpl()), is(instanceOf(Context.class)));
     }
 
     @Test
-    public void unknownTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+    void unknownTransaction() {
+        final ContractInterface c = new ContractInterface() {};
 
         assertThatThrownBy(() -> c.unknownTransaction(c.createContext(new ChaincodeStubNaiveImpl())))
                 .isInstanceOf(ChaincodeException.class)
@@ -31,17 +30,15 @@ public void unknownTransaction() {
     }
 
     @Test
-    public void beforeTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+    void beforeTransaction() {
+        final ContractInterface c = new ContractInterface() {};
 
         c.beforeTransaction(c.createContext(new ChaincodeStubNaiveImpl()));
     }
 
     @Test
-    public void afterTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+    void afterTransaction() {
+        final ContractInterface c = new ContractInterface() {};
         c.afterTransaction(c.createContext(new ChaincodeStubNaiveImpl()), "ReturnValue");
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractRouterTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractRouterTest.java
index 987922f5c..210321be4 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractRouterTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/ContractRouterTest.java
@@ -5,7 +5,19 @@
  */
 package org.hyperledger.fabric.contract;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+
 import contract.SampleContract;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
 import org.hyperledger.fabric.contract.annotation.Contract;
 import org.hyperledger.fabric.contract.execution.ExecutionFactory;
 import org.hyperledger.fabric.contract.execution.InvocationRequest;
@@ -16,31 +28,18 @@
 import org.hyperledger.fabric.shim.NettyChaincodeServer;
 import org.junit.jupiter.api.Test;
 
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.hamcrest.Matchers.nullValue;
-
-public class ContractRouterTest {
+final class ContractRouterTest {
     @Test
-    public void testCreateFailsWithoutValidOptions() {
-        assertThatThrownBy(() -> new ContractRouter(new String[]{}))
+    void testCreateFailsWithoutValidOptions() {
+        assertThatThrownBy(() -> new ContractRouter(new String[] {}))
                 .isInstanceOf(IllegalArgumentException.class)
                 .hasMessageContaining("The chaincode id must be specified using either the -i or --i command "
                         + "line options or the CORE_CHAINCODE_ID_NAME environment variable.");
     }
 
     @Test
-    public void testCreateAndScan() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testCreateAndScan() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -50,15 +49,17 @@ public void testCreateAndScan() {
         args.add("asdf");
         ((ChaincodeStubNaiveImpl) s).setStringArgs(args);
         final InvocationRequest request = ExecutionFactory.getInstance().createRequest(s);
-        assertThat(request.getNamespace(), is(equalTo(SampleContract.class.getAnnotation(Contract.class).name())));
+        assertThat(
+                request.getNamespace(),
+                is(equalTo(SampleContract.class.getAnnotation(Contract.class).name())));
         assertThat(request.getMethod(), is(equalTo("t1")));
         assertThat(request.getRequestName(), is(equalTo("samplecontract:t1")));
         assertThat(request.getArgs(), is(contains(s.getArgs().get(1))));
     }
 
     @Test
-    public void testInit() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInit() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -83,13 +84,10 @@ public void testInit() {
         assertThat(SampleContract.getT1Invoked(), is(1));
     }
 
-    /**
-     * Test invoking two transaction functions in a contract via fully qualified
-     * name
-     */
+    /** Test invoking two transaction functions in a contract via fully qualified name */
     @Test
-    public void testInvokeTwoTxnsThatExist() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTwoTxnsThatExist() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -135,8 +133,8 @@ public void testInvokeTwoTxnsThatExist() {
     }
 
     @Test
-    public void testInvokeTxnWithDefinedName() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnWithDefinedName() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -161,12 +159,10 @@ public void testInvokeTxnWithDefinedName() {
         assertThat(SampleContract.getT1Invoked(), is(0));
     }
 
-    /**
-     * Test invoking two transaction functions in a contract via default name name
-     */
+    /** Test invoking two transaction functions in a contract via default name name */
     @Test
-    public void testInvokeTwoTxnsWithDefaultNamespace() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTwoTxnsWithDefaultNamespace() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -212,8 +208,8 @@ public void testInvokeTwoTxnsWithDefaultNamespace() {
     }
 
     @Test
-    public void testInvokeTxnWithDefinedNameUsingMethodName() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnWithDefinedNameUsingMethodName() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -239,8 +235,8 @@ public void testInvokeTxnWithDefinedNameUsingMethodName() {
     }
 
     @Test
-    public void testInvokeContractThatDoesNotExist() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeContractThatDoesNotExist() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -266,8 +262,8 @@ public void testInvokeContractThatDoesNotExist() {
     }
 
     @Test
-    public void testInvokeTxnThatDoesNotExist() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnThatDoesNotExist() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -293,8 +289,8 @@ public void testInvokeTxnThatDoesNotExist() {
     }
 
     @Test
-    public void testInvokeTxnThatReturnsNullString() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnThatReturnsNullString() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -320,8 +316,8 @@ public void testInvokeTxnThatReturnsNullString() {
     }
 
     @Test
-    public void testInvokeTxnThatThrowsAnException() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnThatThrowsAnException() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -335,7 +331,6 @@ public void testInvokeTxnThatThrowsAnException() {
         SampleContract.setAfterInvoked(0);
         SampleContract.setDoWorkInvoked(0);
 
-
         final Chaincode.Response response = r.invoke(s);
         assertThat(response, is(notNullValue()));
         assertThat(response.getStatus(), is(Chaincode.Response.Status.INTERNAL_SERVER_ERROR));
@@ -347,8 +342,8 @@ public void testInvokeTxnThatThrowsAnException() {
     }
 
     @Test
-    public void testInvokeTxnThatThrowsAChaincodeException() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+    void testInvokeTxnThatThrowsAChaincodeException() {
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -362,7 +357,6 @@ public void testInvokeTxnThatThrowsAChaincodeException() {
         SampleContract.setAfterInvoked(0);
         SampleContract.setDoWorkInvoked(0);
 
-
         final Chaincode.Response response = r.invoke(s);
         assertThat(response, is(notNullValue()));
         assertThat(response.getStatus(), is(Chaincode.Response.Status.INTERNAL_SERVER_ERROR));
@@ -373,31 +367,29 @@ public void testInvokeTxnThatThrowsAChaincodeException() {
         assertThat(SampleContract.getDoWorkInvoked(), is(0));
     }
 
-    /**
-     * Test confirming ContractRuntimeExceptions can be created.
-     */
+    /** Test confirming ContractRuntimeExceptions can be created. */
     @Test
-    public void createContractRuntimeExceptions() {
+    void createContractRuntimeExceptions() {
         final ContractRuntimeException cre1 = new ContractRuntimeException("failure");
         new ContractRuntimeException("another failure", cre1);
         new ContractRuntimeException(new Exception("cause"));
     }
 
     @Test
-    public void testStartingContractRouterWithStartingAChaincodeServer() throws IOException {
+    void testStartingContractRouterWithStartingAChaincodeServer() throws IOException {
         ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
         chaincodeServerProperties.setServerAddress(new InetSocketAddress("0.0.0.0", 9999));
-        final ContractRouter r = new ContractRouter(new String[]{"-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-i", "testId"});
         ChaincodeServer chaincodeServer = new NettyChaincodeServer(r, chaincodeServerProperties);
 
         new Thread(() -> {
-            try {
-                r.startRouterWithChaincodeServer(chaincodeServer);
-            } catch (IOException | InterruptedException e) {
-                e.printStackTrace();
-            }
-        }
-        ).start();
+                    try {
+                        r.startRouterWithChaincodeServer(chaincodeServer);
+                    } catch (IOException | InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                })
+                .start();
 
         try {
             Thread.sleep(5000);
@@ -405,12 +397,12 @@ public void testStartingContractRouterWithStartingAChaincodeServer() throws IOEx
             e.printStackTrace();
         }
 
-        final ChaincodeStub s = new ChaincodeStubNaiveImpl();
+        final ChaincodeStubNaiveImpl s = new ChaincodeStubNaiveImpl();
 
         final List args = new ArrayList<>();
         args.add("samplecontract:t1");
         args.add("asdf");
-        ((ChaincodeStubNaiveImpl) s).setStringArgs(args);
+        s.setStringArgs(args);
 
         SampleContract.setBeforeInvoked(0);
         SampleContract.setAfterInvoked(0);
@@ -419,8 +411,10 @@ public void testStartingContractRouterWithStartingAChaincodeServer() throws IOEx
 
         final Chaincode.Response response = r.init(s);
         assertThat(response, is(notNullValue()));
-        assertThat(response.getMessage() + " " + response.getStringPayload() + response.toString(),
-                response.getStatus(), is(Chaincode.Response.Status.SUCCESS));
+        assertThat(
+                response.getMessage() + " " + response.getStringPayload() + response.toString(),
+                response.getStatus(),
+                is(Chaincode.Response.Status.SUCCESS));
         assertThat(response.getMessage(), is(nullValue()));
         assertThat(response.getStringPayload(), is(equalTo("asdf")));
         assertThat(SampleContract.getBeforeInvoked(), is(1));
@@ -430,5 +424,4 @@ public void testStartingContractRouterWithStartingAChaincodeServer() throws IOEx
 
         chaincodeServer.stop();
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType.java
index 956f774a8..6cc39f0ea 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType.java
@@ -18,8 +18,8 @@ public final class MyType {
 
     private String state = "";
 
-    public static final  String STARTED = "STARTED";
-    public static final  String STOPPED = "STOPPED";
+    public static final String STARTED = "STARTED";
+    public static final String STOPPED = "STOPPED";
 
     public void setState(final String state) {
         this.state = state;
@@ -27,12 +27,12 @@ public void setState(final String state) {
 
     @JSONPropertyIgnore()
     public boolean isStarted() {
-        return state.equals(STARTED);
+        return STARTED.equals(state);
     }
 
     @JSONPropertyIgnore()
     public boolean isStopped() {
-        return state.equals(STARTED);
+        return STOPPED.equals(state);
     }
 
     public MyType setValue(final String value) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType2.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType2.java
index 53cc5fcc8..9da03bbc4 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType2.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/MyType2.java
@@ -15,7 +15,21 @@ public final class MyType2 {
     @Property()
     private String value;
 
-    @Property(schema = {"title", "MrProperty", "Pattern", "[a-z]", "uniqueItems", "false", "required", "true,false", "enum", "a,bee,cee,dee", "minimum", "42"})
+    @Property(
+            schema = {
+                "title",
+                "MrProperty",
+                "Pattern",
+                "[a-z]",
+                "uniqueItems",
+                "false",
+                "required",
+                "true,false",
+                "enum",
+                "a,bee,cee,dee",
+                "minimum",
+                "42"
+            })
     private String constrainedValue;
 
     public MyType2 setValue(final String value) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/TransactionExceptionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/TransactionExceptionTest.java
index edd4e7993..dcf619ada 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/TransactionExceptionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/TransactionExceptionTest.java
@@ -5,14 +5,14 @@
  */
 package org.hyperledger.fabric.contract;
 
-import org.hyperledger.fabric.shim.ChaincodeException;
-import org.junit.jupiter.api.Test;
-
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
 
-public class TransactionExceptionTest {
+import org.hyperledger.fabric.shim.ChaincodeException;
+import org.junit.jupiter.api.Test;
+
+final class TransactionExceptionTest {
 
     class MyTransactionException extends ChaincodeException {
 
@@ -33,21 +33,21 @@ public byte[] getPayload() {
     }
 
     @Test
-    public void testNoArgConstructor() {
+    void testNoArgConstructor() {
         final ChaincodeException e = new ChaincodeException();
         assertThat(e.getMessage(), is(nullValue()));
         assertThat(e.getPayload(), is(nullValue()));
     }
 
     @Test
-    public void testMessageArgConstructor() {
+    void testMessageArgConstructor() {
         final ChaincodeException e = new ChaincodeException("Failure");
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(nullValue()));
     }
 
     @Test
-    public void testCauseArgConstructor() {
+    void testCauseArgConstructor() {
         final ChaincodeException e = new ChaincodeException(new Error("Cause"));
         assertThat(e.getMessage(), is("java.lang.Error: Cause"));
         assertThat(e.getPayload(), is(nullValue()));
@@ -55,7 +55,7 @@ public void testCauseArgConstructor() {
     }
 
     @Test
-    public void testMessageAndCauseArgConstructor() {
+    void testMessageAndCauseArgConstructor() {
         final ChaincodeException e = new ChaincodeException("Failure", new Error("Cause"));
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(nullValue()));
@@ -63,29 +63,30 @@ public void testMessageAndCauseArgConstructor() {
     }
 
     @Test
-    public void testMessageAndPayloadArgConstructor() {
+    void testMessageAndPayloadArgConstructor() {
         final ChaincodeException e = new ChaincodeException("Failure", new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'});
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}));
     }
 
     @Test
-    public void testMessagePayloadAndCauseArgConstructor() {
-        final ChaincodeException e = new ChaincodeException("Failure", new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}, new Error("Cause"));
+    void testMessagePayloadAndCauseArgConstructor() {
+        final ChaincodeException e =
+                new ChaincodeException("Failure", new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}, new Error("Cause"));
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}));
         assertThat(e.getCause().getMessage(), is("Cause"));
     }
 
     @Test
-    public void testMessageAndStringPayloadArgConstructor() {
+    void testMessageAndStringPayloadArgConstructor() {
         final ChaincodeException e = new ChaincodeException("Failure", "Payload");
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}));
     }
 
     @Test
-    public void testMessageStringPayloadAndCauseArgConstructor() {
+    void testMessageStringPayloadAndCauseArgConstructor() {
         final ChaincodeException e = new ChaincodeException("Failure", "Payload", new Error("Cause"));
         assertThat(e.getMessage(), is("Failure"));
         assertThat(e.getPayload(), is(new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}));
@@ -93,7 +94,7 @@ public void testMessageStringPayloadAndCauseArgConstructor() {
     }
 
     @Test
-    public void testSubclass() {
+    void testSubclass() {
         final ChaincodeException e = new MyTransactionException(1);
         assertThat(e.getMessage(), is("MyTransactionException"));
         assertThat(e.getPayload(), is(new byte[] {'E', '0', '0', '1'}));
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/ContractExecutionServiceTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/ContractExecutionServiceTest.java
index cbf1f2ce7..124ccbf9f 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/ContractExecutionServiceTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/ContractExecutionServiceTest.java
@@ -6,7 +6,19 @@
 
 package org.hyperledger.fabric.contract.execution;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import contract.SampleContract;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.util.ArrayList;
+import java.util.Collections;
 import org.hyperledger.fabric.contract.ChaincodeStubNaiveImpl;
 import org.hyperledger.fabric.contract.Context;
 import org.hyperledger.fabric.contract.ContractInterface;
@@ -21,23 +33,11 @@
 import org.hyperledger.fabric.shim.ChaincodeStub;
 import org.junit.jupiter.api.Test;
 
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Parameter;
-import java.util.ArrayList;
-import java.util.Collections;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public final class ContractExecutionServiceTest {
+final class ContractExecutionServiceTest {
     @Test
-    public void noReturnValue()
-            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    void noReturnValue()
+            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
+                    SecurityException {
         JSONTransactionSerializer jts = new JSONTransactionSerializer();
         SerializerRegistryImpl serializerRegistry = spy(new SerializerRegistryImpl());
         ContractExecutionService ces = new ContractExecutionService(serializerRegistry);
@@ -50,19 +50,20 @@ public void noReturnValue()
         ChaincodeStub stub = new ChaincodeStubNaiveImpl();
 
         when(txFn.getRouting()).thenReturn(routing);
-        when(req.getArgs()).thenReturn(new ArrayList());
-        when(routing.getMethod()).thenReturn(SampleContract.class.getMethod("noReturn", new Class[] {Context.class}));
+        when(req.getArgs()).thenReturn(new ArrayList<>());
+        when(routing.getMethod())
+                .thenReturn(SampleContract.class.getMethod("noReturn", new Class[] {Context.class}));
         when(routing.getContractInstance()).thenReturn(contract);
         when(serializerRegistry.getSerializer(any(), any())).thenReturn(jts);
         ces.executeRequest(txFn, req, stub);
 
         verify(contract).beforeTransaction(any());
-
     }
 
     @Test()
-    public void failureToInvoke()
-            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    void failureToInvoke()
+            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
+                    SecurityException {
         JSONTransactionSerializer jts = new JSONTransactionSerializer();
         SerializerRegistryImpl serializerRegistry = spy(new SerializerRegistryImpl());
         ContractExecutionService ces = new ContractExecutionService(serializerRegistry);
@@ -74,10 +75,8 @@ public void failureToInvoke()
 
         ChaincodeStub stub = mock(ChaincodeStub.class);
 
-
         when(txFn.getRouting()).thenReturn(routing);
-        when(req.getArgs()).thenReturn(new ArrayList() {
-        });
+        when(req.getArgs()).thenReturn(new ArrayList<>() {});
 
         when(routing.getContractInstance()).thenThrow(IllegalAccessException.class);
         when(routing.toString()).thenReturn("MockMethodName:MockClassName");
@@ -89,7 +88,7 @@ public void failureToInvoke()
     }
 
     @Test()
-    public void invokeWithDifferentSerializers()
+    void invokeWithDifferentSerializers()
             throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
         JSONTransactionSerializer defaultSerializer = spy(new JSONTransactionSerializer());
         SerializerInterface customSerializer = mock(SerializerInterface.class);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializerTest.java
index 169ad41fc..15d0a52a0 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/execution/JSONTransactionSerializerTest.java
@@ -6,12 +6,11 @@
 
 package org.hyperledger.fabric.contract.execution;
 
-import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.nio.charset.StandardCharsets;
-
 import org.hyperledger.fabric.contract.AllTypesAsset;
 import org.hyperledger.fabric.contract.MyType;
 import org.hyperledger.fabric.contract.metadata.MetadataBuilder;
@@ -22,9 +21,9 @@
 import org.junit.jupiter.api.Nested;
 import org.junit.jupiter.api.Test;
 
-public class JSONTransactionSerializerTest {
+final class JSONTransactionSerializerTest {
     @Test
-    public void toBuffer() {
+    void toBuffer() {
         final TypeRegistry tr = TypeRegistry.getRegistry();
 
         tr.addDataType(MyType.class);
@@ -54,14 +53,12 @@ public void toBuffer() {
 
         final byte[] buffer = "[{\"value\":\"hello\"},{\"value\":\"world\"}]".getBytes(StandardCharsets.UTF_8);
 
-        System.out.println(new String(buffer, StandardCharsets.UTF_8));
-        System.out.println(new String(bytes, StandardCharsets.UTF_8));
         assertThat(bytes, equalTo(buffer));
     }
 
     @Nested
     @DisplayName("Complex Data types")
-    class ComplexDataTypes {
+    final class ComplexDataTypes {
 
         @Test
         public void alltypes() {
@@ -75,22 +72,18 @@ public void alltypes() {
             final AllTypesAsset all = new AllTypesAsset();
 
             final TypeSchema ts = TypeSchema.typeConvert(AllTypesAsset.class);
-            System.out.println("TS = " + ts);
             final byte[] bytes = serializer.toBuffer(all, ts);
-            System.out.println("Data as toBuffer-ed " + new String(bytes, StandardCharsets.UTF_8));
 
             final AllTypesAsset returned = (AllTypesAsset) serializer.fromBuffer(bytes, ts);
-            System.out.println("Start object = " + all);
-            System.out.println("Returned object = " + returned);
             assertTrue(all.equals(returned));
         }
     }
 
     @Nested
     @DisplayName("Primitive Arrays")
-    class PrimitiveArrays {
+    final class PrimitiveArrays {
         @Test
-        public void ints() {
+        void ints() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             // convert array of primitive
             final int[] intarray = new int[] {42, 83};
@@ -102,7 +95,7 @@ public void ints() {
         }
 
         @Test
-        public void bytes() {
+        void bytes() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             // convert array of primitive
             final byte[] array = new byte[] {42, 83};
@@ -114,7 +107,7 @@ public void bytes() {
         }
 
         @Test
-        public void floats() {
+        void floats() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             // convert array of primitive
             final float[] array = new float[] {42.5F, 83.5F};
@@ -126,7 +119,7 @@ public void floats() {
         }
 
         @Test
-        public void booleans() {
+        void booleans() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             // convert array of primitive
             final boolean[] array = new boolean[] {true, false, true};
@@ -138,7 +131,7 @@ public void booleans() {
         }
 
         @Test
-        public void chars() {
+        void chars() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             // convert array of primitive
             final char[] array = new char[] {'a', 'b', 'c'};
@@ -152,9 +145,9 @@ public void chars() {
 
     @Nested
     @DisplayName("Nested Arrays")
-    class NestedArrays {
+    final class NestedArrays {
         @Test
-        public void ints() {
+        void ints() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             final int[][] array = new int[][] {{42, 83}, {83, 42}};
             final byte[] bytes = serializer.toBuffer(array, TypeSchema.typeConvert(int[][].class));
@@ -165,7 +158,7 @@ public void ints() {
         }
 
         @Test
-        public void longs() {
+        void longs() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             final long[][] array = new long[][] {{42L, 83L}, {83L, 42L}};
             final byte[] bytes = serializer.toBuffer(array, TypeSchema.typeConvert(long[][].class));
@@ -176,7 +169,7 @@ public void longs() {
         }
 
         @Test
-        public void doubles() {
+        void doubles() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             final double[][] array = new double[][] {{42.42d, 83.83d}, {83.23d, 42.33d}};
             final byte[] bytes = serializer.toBuffer(array, TypeSchema.typeConvert(double[][].class));
@@ -187,7 +180,7 @@ public void doubles() {
         }
 
         @Test
-        public void bytes() {
+        void bytes() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             final byte[][] array = new byte[][] {{42, 83}, {83, 42}};
             final byte[] bytes = serializer.toBuffer(array, TypeSchema.typeConvert(byte[][].class));
@@ -198,7 +191,7 @@ public void bytes() {
         }
 
         @Test
-        public void shorts() {
+        void shorts() {
             final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
             final short[][] array = new short[][] {{42, 83}, {83, 42}};
             final byte[] bytes = serializer.toBuffer(array, TypeSchema.typeConvert(short[][].class));
@@ -210,7 +203,7 @@ public void shorts() {
     }
 
     @Test
-    public void fromBufferObject() {
+    void fromBufferObject() {
         final byte[] buffer = "[{\"value\":\"hello\"},{\"value\":\"world\"}]".getBytes(StandardCharsets.UTF_8);
 
         final TypeRegistry tr = TypeRegistry.getRegistry();
@@ -224,11 +217,10 @@ public void fromBufferObject() {
         final MyType[] o = (MyType[]) serializer.fromBuffer(buffer, ts);
         assertThat(o[0].toString(), equalTo("++++ MyType: hello"));
         assertThat(o[1].toString(), equalTo("++++ MyType: world"));
-
     }
 
     @Test
-    public void toBufferPrimitive() {
+    void toBufferPrimitive() {
         final TypeRegistry tr = TypeRegistry.getRegistry();
         final JSONTransactionSerializer serializer = new JSONTransactionSerializer();
 
@@ -269,7 +261,7 @@ public void toBufferPrimitive() {
     }
 
     @Test
-    public void fromBufferErrors() {
+    void fromBufferErrors() {
         final TypeRegistry tr = new TypeRegistryImpl();
         tr.addDataType(MyType.class);
         MetadataBuilder.addComponent(tr.getDataType("MyType"));
@@ -279,8 +271,5 @@ public void fromBufferErrors() {
         serializer.toBuffer(null, ts);
     }
 
-    class MyTestObject {
-
-    }
-
+    class MyTestObject {}
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/MetadataBuilderTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/MetadataBuilderTest.java
index 8204b3433..2c55d199b 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/MetadataBuilderTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/MetadataBuilderTest.java
@@ -6,6 +6,9 @@
 package org.hyperledger.fabric.contract.metadata;
 
 import contract.SampleContract;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.util.HashMap;
 import org.everit.json.schema.loader.SchemaClient;
 import org.everit.json.schema.loader.internal.DefaultSchemaClient;
 import org.hyperledger.fabric.contract.ChaincodeStubNaiveImpl;
@@ -18,46 +21,27 @@
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-import java.io.InputStream;
-import java.io.Serializable;
-import java.lang.reflect.Field;
-import java.util.HashMap;
-
-public final class MetadataBuilderTest {
-    private final String expectedMetadataString = "    {\n" + "       \"components\": {\"schemas\": {}},\n"
-            + "       \"$schema\": \"https://fabric-shim.github.io/contract-schema.json\",\n" + "       \"contracts\": {\"SampleContract\": {\n"
-            + "          \"name\": \"SampleContract\",\n" + "          \"transactions\": [],\n" + "          \"info\": {\n"
-            + "             \"license\": {\"name\": \"\"},\n" + "             \"description\": \"\",\n" + "             \"termsOfService\": \"\",\n"
-            + "             \"title\": \"\",\n" + "             \"version\": \"\",\n" + "             \"contact\": {\"email\": \"fred@example.com\"}\n"
-            + "          }\n" + "       }},\n" + "       \"info\": {\n" + "          \"license\": {\"name\": \"\"},\n" + "          \"description\": \"\",\n"
-            + "          \"termsOfService\": \"\",\n" + "          \"title\": \"\",\n" + "          \"version\": \"\",\n"
-            + "          \"contact\": {\"email\": \"fred@example.com\"}\n" + "       }\n" + "    }\n" + "";
-
+final class MetadataBuilderTest {
     // fields are private, so use reflection to bypass this for unit testing
-    private void setMetadataBuilderField(final String name, final Object value) {
-        try {
-            final Field f = MetadataBuilder.class.getDeclaredField(name);
-            f.setAccessible(true);
-            f.set(null, value);
-        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
-            e.printStackTrace();
-            throw new RuntimeException("Unable to set field " + e.getMessage());
-        }
+    private void setMetadataBuilderField(final String name, final Object value)
+            throws NoSuchFieldException, IllegalAccessException {
+        final Field f = MetadataBuilder.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(null, value);
     }
 
     @BeforeEach
     @AfterEach
-    public void beforeAndAfterEach() {
+    void beforeAndAfterEach() throws NoSuchFieldException, IllegalAccessException {
 
-        setMetadataBuilderField("componentMap", new HashMap());
-        setMetadataBuilderField("contractMap", new HashMap>());
-        setMetadataBuilderField("overallInfoMap", new HashMap());
+        setMetadataBuilderField("componentMap", new HashMap<>());
+        setMetadataBuilderField("contractMap", new HashMap<>());
+        setMetadataBuilderField("overallInfoMap", new HashMap<>());
         setMetadataBuilderField("schemaClient", new DefaultSchemaClient());
-
     }
 
     @Test
-    public void systemContract() {
+    void systemContract() {
 
         final SystemContract system = new SystemContract();
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
@@ -65,18 +49,16 @@ public void systemContract() {
     }
 
     @Test
-    public void defaultSchemasNotLoadedFromNetwork() {
+    void defaultSchemasNotLoadedFromNetwork() throws NoSuchFieldException, IllegalAccessException {
         final ContractDefinition contractDefinition = new ContractDefinitionImpl(SampleContract.class);
         MetadataBuilder.addContract(contractDefinition);
         setMetadataBuilderField("schemaClient", new SchemaClient() {
 
             @Override
             public InputStream get(final String uri) {
-                throw new RuntimeException("Refusing to load schema: " + uri);
+                throw new IllegalStateException("Refusing to load schema: " + uri);
             }
-
         });
         MetadataBuilder.validate();
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/TypeSchemaTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/TypeSchemaTest.java
index d06e6d6d8..7274e6541 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/TypeSchemaTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/metadata/TypeSchemaTest.java
@@ -5,8 +5,8 @@
  */
 package org.hyperledger.fabric.contract.metadata;
 
-import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import org.hyperledger.fabric.contract.annotation.DataType;
@@ -18,33 +18,29 @@
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-public class TypeSchemaTest {
+final class TypeSchemaTest {
 
     @BeforeEach
-    public void beforeEach() {
-    }
+    void beforeEach() {}
 
     @Test
-    public void putIfNotNull() {
+    void putIfNotNull() {
         final TypeSchema ts = new TypeSchema();
 
-        System.out.println("Key - value");
         ts.putIfNotNull("Key", "value");
 
-        System.out.println("Key - null");
         final String nullstr = null;
         ts.putIfNotNull("Key", nullstr);
 
         assertThat(ts.get("Key"), equalTo("value"));
 
-        System.out.println("Key - ");
         ts.putIfNotNull("Key", "");
 
         assertThat(ts.get("Key"), equalTo("value"));
     }
 
     @Test
-    public void getType() {
+    void getType() {
         final TypeSchema ts = new TypeSchema();
         ts.put("type", "MyType");
         assertThat(ts.getType(), equalTo("MyType"));
@@ -55,7 +51,7 @@ public void getType() {
     }
 
     @Test
-    public void getFormat() {
+    void getFormat() {
         final TypeSchema ts = new TypeSchema();
         ts.put("format", "MyFormat");
         assertThat(ts.getFormat(), equalTo("MyFormat"));
@@ -66,7 +62,7 @@ public void getFormat() {
     }
 
     @Test
-    public void getRef() {
+    void getRef() {
         final TypeSchema ts = new TypeSchema();
         ts.put("$ref", "#/ref/to/MyType");
         assertThat(ts.getRef(), equalTo("#/ref/to/MyType"));
@@ -77,7 +73,7 @@ public void getRef() {
     }
 
     @Test
-    public void getItems() {
+    void getItems() {
         final TypeSchema ts1 = new TypeSchema();
 
         final TypeSchema ts = new TypeSchema();
@@ -90,11 +86,10 @@ public void getItems() {
     }
 
     @DataType
-    class MyType {
-    }
+    class MyType {}
 
     @Test
-    public void getTypeClass() {
+    void getTypeClass() {
         final TypeSchema ts = new TypeSchema();
 
         ts.put("type", "string");
@@ -138,11 +133,10 @@ public void getTypeClass() {
         array.put("type", "array");
         array.put("items", ts);
         assertThat(array.getTypeClass(mockRegistry), equalTo(MyType[].class));
-
     }
 
     @Test
-    public void unknownConversions() {
+    void unknownConversions() {
         assertThrows(RuntimeException.class, () -> {
             final TypeSchema ts = new TypeSchema();
             final TypeRegistry mockRegistry = new TypeRegistryImpl();
@@ -161,7 +155,7 @@ public void unknownConversions() {
     }
 
     @Test
-    public void typeConvertPrimitives() {
+    void typeConvertPrimitives() {
         TypeSchema rts;
 
         final String[] array = new String[] {};
@@ -188,11 +182,10 @@ public void typeConvertPrimitives() {
 
         rts = TypeSchema.typeConvert(boolean.class);
         assertThat(rts.getType(), equalTo("boolean"));
-
     }
 
     @Test
-    public void typeConvertObjects() {
+    void typeConvertObjects() {
         TypeSchema rts;
         rts = TypeSchema.typeConvert(String.class);
         assertThat(rts.getType(), equalTo("string"));
@@ -227,7 +220,7 @@ public void typeConvertObjects() {
     }
 
     @Test
-    public void validate() {
+    void validate() {
 
         final TypeSchema ts = TypeSchema.typeConvert(org.hyperledger.fabric.contract.MyType.class);
         final DataTypeDefinition dtd = new DataTypeDefinitionImpl(org.hyperledger.fabric.contract.MyType.class);
@@ -235,6 +228,5 @@ public void validate() {
         MetadataBuilder.addComponent(dtd);
         final JSONObject json = new JSONObject();
         ts.validate(json);
-
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ContractDefinitionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ContractDefinitionTest.java
index 0a5640132..fe57c1c9c 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ContractDefinitionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ContractDefinitionTest.java
@@ -5,78 +5,27 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
 import contract.SampleContract;
+import java.lang.reflect.Method;
 import org.hyperledger.fabric.contract.Context;
 import org.hyperledger.fabric.contract.ContractInterface;
 import org.hyperledger.fabric.contract.ContractRuntimeException;
-import org.hyperledger.fabric.contract.annotation.Contract;
-import org.hyperledger.fabric.contract.annotation.Info;
 import org.hyperledger.fabric.contract.routing.impl.ContractDefinitionImpl;
 import org.junit.jupiter.api.Test;
 
-import java.lang.reflect.Method;
-import java.security.Permission;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.startsWith;
-
-public class ContractDefinitionTest {
+final class ContractDefinitionTest {
     @Test
-    public void constructor() throws NoSuchMethodException, SecurityException {
+    void constructor() throws SecurityException {
 
         final ContractDefinition cf = new ContractDefinitionImpl(SampleContract.class);
-        assertThat(cf.toString(), startsWith("samplecontract:"));
-    }
-
-    @Contract(name = "", info = @Info())
-    public class FailureTestObject {
-
-    }
-
-    private boolean fail;
-    private final int step = 1;
-
-    @Test
-    public void unknownRoute() {
-
-        final SecurityManager tmp = new SecurityManager() {
-            private int count = 0;
-
-            @Override
-            public void checkPackageAccess(final String pkg) {
-
-                if (pkg.startsWith("org.hyperledger.fabric.contract")) {
-                    if (count >= step) {
-                        throw new SecurityException("Sorry I can't do that");
-                    }
-                    count++;
-                }
-                super.checkPackageAccess(pkg);
-            }
-
-            @Override
-            public void checkPermission(final Permission perm) {
-                return;
-            }
-        };
-
-        try {
-            final ContractDefinition cf = new ContractDefinitionImpl(SampleContract.class);
-            System.setSecurityManager(tmp);
-            this.fail = true;
-
-            cf.getUnknownRoute();
-        } catch (final Exception e) {
-            assertThat(e.getMessage(), equalTo("Failure to find unknownTransaction method"));
-        } finally {
-            System.setSecurityManager(null);
-        }
+        assertThat(cf.toString()).startsWith("samplecontract:");
     }
 
     @Test
-    public void duplicateTransaction() throws NoSuchMethodException, SecurityException {
+    void duplicateTransaction() throws NoSuchMethodException, SecurityException {
         final ContractDefinition cf = new ContractDefinitionImpl(SampleContract.class);
 
         final ContractInterface contract = new SampleContract();
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/DataTypeDefinitionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/DataTypeDefinitionTest.java
index 015357ece..84ca808cb 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/DataTypeDefinitionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/DataTypeDefinitionTest.java
@@ -5,40 +5,38 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+
+import java.util.Map;
 import org.hyperledger.fabric.contract.MyType2;
+import org.hyperledger.fabric.contract.metadata.TypeSchema;
 import org.hyperledger.fabric.contract.routing.impl.DataTypeDefinitionImpl;
 import org.junit.jupiter.api.Test;
 
-import java.util.Map;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.hasEntry;
-import static org.hamcrest.Matchers.hasKey;
-
-public class DataTypeDefinitionTest {
+final class DataTypeDefinitionTest {
     @Test
-    public void constructor() {
+    void constructor() {
         final DataTypeDefinitionImpl dtd = new DataTypeDefinitionImpl(MyType2.class);
-        assertThat(dtd.getTypeClass(), equalTo(MyType2.class));
-        assertThat(dtd.getName(), equalTo("org.hyperledger.fabric.contract.MyType2"));
-        assertThat(dtd.getSimpleName(), equalTo("MyType2"));
+        assertThat(dtd.getTypeClass()).isEqualTo(MyType2.class);
+        assertThat(dtd.getName()).isEqualTo("org.hyperledger.fabric.contract.MyType2");
+        assertThat(dtd.getSimpleName()).isEqualTo("MyType2");
 
         final Map properties = dtd.getProperties();
-        assertThat(properties.size(), equalTo(2));
-        assertThat(properties, hasKey("value"));
-        assertThat(properties, hasKey("constrainedValue"));
+        assertThat(properties.size()).isEqualTo(2);
+        assertThat(properties).containsKey("value");
+        assertThat(properties).containsKey("constrainedValue");
 
         final PropertyDefinition pd = properties.get("constrainedValue");
-        final Map ts = pd.getSchema();
-
-        assertThat(ts, hasEntry("title", "MrProperty"));
-        assertThat(ts, hasEntry("Pattern", "[a-z]"));
-        assertThat(ts, hasEntry("uniqueItems", false));
-        assertThat(ts, hasEntry("required", new String[] {"true", "false"}));
-        assertThat(ts, hasEntry("enum", new String[] {"a", "bee", "cee", "dee"}));
-        assertThat(ts, hasEntry("minimum", 42));
-
+        final TypeSchema ts = pd.getSchema();
+
+        assertThat(ts)
+                .contains(
+                        entry("title", "MrProperty"),
+                        entry("Pattern", "[a-z]"),
+                        entry("uniqueItems", false),
+                        entry("required", new String[] {"true", "false"}),
+                        entry("enum", new String[] {"a", "bee", "cee", "dee"}),
+                        entry("minimum", 42));
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ParameterDefinitionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ParameterDefinitionTest.java
index 823dd06fb..8349527b4 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ParameterDefinitionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/ParameterDefinitionTest.java
@@ -5,19 +5,19 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.lang.reflect.Parameter;
 import org.hyperledger.fabric.contract.metadata.TypeSchema;
 import org.hyperledger.fabric.contract.routing.impl.ParameterDefinitionImpl;
 import org.junit.jupiter.api.Test;
 
-import java.lang.reflect.Parameter;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-
-public class ParameterDefinitionTest {
+final class ParameterDefinitionTest {
     @Test
-    public void constructor() throws NoSuchMethodException, SecurityException {
-        final Parameter[] params = String.class.getMethod("concat", String.class).getParameters();
+    void constructor() throws NoSuchMethodException, SecurityException {
+        final Parameter[] params =
+                String.class.getMethod("concat", String.class).getParameters();
         final ParameterDefinition pd = new ParameterDefinitionImpl("test", String.class, new TypeSchema(), params[0]);
         assertThat(pd.toString(), equalTo("test-class java.lang.String-{}-java.lang.String arg0"));
         assertThat(pd.getTypeClass(), equalTo(String.class));
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/PropertyDefinitionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/PropertyDefinitionTest.java
index 28cd785eb..cb73dbca0 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/PropertyDefinitionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/PropertyDefinitionTest.java
@@ -5,18 +5,17 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.lang.reflect.Field;
 import org.hyperledger.fabric.contract.metadata.TypeSchema;
 import org.hyperledger.fabric.contract.routing.impl.PropertyDefinitionImpl;
 import org.junit.jupiter.api.Test;
 
-import java.lang.reflect.Field;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-
-public class PropertyDefinitionTest {
+final class PropertyDefinitionTest {
     @Test
-    public void constructor() throws NoSuchMethodException, SecurityException {
+    void constructor() throws NoSuchMethodException, SecurityException {
         final Field[] props = String.class.getFields();
         final TypeSchema ts = new TypeSchema();
         final PropertyDefinition pd = new PropertyDefinitionImpl("test", String.class, ts, props[0]);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TxFunctionTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TxFunctionTest.java
index 1096ceacd..d110dfa90 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TxFunctionTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TxFunctionTest.java
@@ -5,6 +5,14 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
 import org.hyperledger.fabric.contract.Context;
 import org.hyperledger.fabric.contract.ContractInterface;
 import org.hyperledger.fabric.contract.ContractRuntimeException;
@@ -16,41 +24,28 @@
 import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.startsWith;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-
-public class TxFunctionTest {
+final class TxFunctionTest {
     @Contract()
     class TestObject implements ContractInterface {
 
         @Transaction()
-        public void testMethod1(final Context ctx) {
-
-        }
+        public void testMethod1(final Context ctx) {}
 
         @Transaction()
-        public void testMethod2(final Context ctx, @Property(schema = {"a", "b"}) final int arg) {
-
-        }
+        public void testMethod2(final Context ctx, @Property(schema = {"a", "b"}) final int arg) {}
 
         @Transaction()
-        public void wibble(final String arg1) {
-
-        }
+        public void wibble(final String arg1) {}
     }
 
     @Test
-    public void constructor() throws NoSuchMethodException, SecurityException {
+    void constructor() throws NoSuchMethodException, SecurityException {
         final TestObject test = new TestObject();
         final ContractDefinition cd = mock(ContractDefinition.class);
         Mockito.when(cd.getAnnotation()).thenReturn(test.getClass().getAnnotation(Contract.class));
 
-        final TxFunction txfn = new TxFunctionImpl(test.getClass().getMethod("testMethod1", new Class[] {Context.class}), cd);
+        final TxFunction txfn =
+                new TxFunctionImpl(test.getClass().getMethod("testMethod1", new Class[] {Context.class}), cd);
         final String name = txfn.getName();
         assertEquals(name, "testMethod1");
 
@@ -58,11 +53,12 @@ public void constructor() throws NoSuchMethodException, SecurityException {
     }
 
     @Test
-    public void property() throws NoSuchMethodException, SecurityException {
+    void property() throws NoSuchMethodException, SecurityException {
         final TestObject test = new TestObject();
         final ContractDefinition cd = mock(ContractDefinition.class);
         Mockito.when(cd.getAnnotation()).thenReturn(test.getClass().getAnnotation(Contract.class));
-        final TxFunction txfn = new TxFunctionImpl(test.getClass().getMethod("testMethod2", new Class[] {Context.class, int.class}), cd);
+        final TxFunction txfn = new TxFunctionImpl(
+                test.getClass().getMethod("testMethod2", new Class[] {Context.class, int.class}), cd);
         final String name = txfn.getName();
         assertEquals(name, "testMethod2");
 
@@ -74,13 +70,11 @@ public void property() throws NoSuchMethodException, SecurityException {
         final TypeSchema ts = new TypeSchema();
         txfn.setReturnSchema(ts);
         final TypeSchema rts = txfn.getReturnSchema();
-        System.out.println(ts);
         assertEquals(ts, rts);
-
     }
 
     @Test
-    public void invaldtxfn() throws NoSuchMethodException, SecurityException {
+    void invaldtxfn() throws NoSuchMethodException, SecurityException {
         final TestObject test = new TestObject();
         final ContractDefinition cd = mock(ContractDefinition.class);
         Mockito.when(cd.getAnnotation()).thenReturn(test.getClass().getAnnotation(Contract.class));
@@ -88,5 +82,4 @@ public void invaldtxfn() throws NoSuchMethodException, SecurityException {
         assertThatThrownBy(() -> new TxFunctionImpl(test.getClass().getMethod("wibble", String.class), cd))
                 .isInstanceOf(ContractRuntimeException.class);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TypeRegistryTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TypeRegistryTest.java
index 0fc5f4195..7c38c01b1 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TypeRegistryTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/routing/TypeRegistryTest.java
@@ -5,18 +5,17 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.util.Collection;
 import org.hyperledger.fabric.contract.routing.impl.DataTypeDefinitionImpl;
 import org.hyperledger.fabric.contract.routing.impl.TypeRegistryImpl;
 import org.junit.jupiter.api.Test;
 
-import java.util.Collection;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-
-public class TypeRegistryTest {
+final class TypeRegistryTest {
     @Test
-    public void addDataType() {
+    void addDataType() {
         final TypeRegistryImpl tr = new TypeRegistryImpl();
         tr.addDataType(String.class);
 
@@ -25,7 +24,7 @@ public void addDataType() {
     }
 
     @Test
-    public void addDataTypeDefinition() {
+    void addDataTypeDefinition() {
         final DataTypeDefinitionImpl dtd = new DataTypeDefinitionImpl(String.class);
         final TypeRegistryImpl tr = new TypeRegistryImpl();
         tr.addDataType(dtd);
@@ -35,7 +34,7 @@ public void addDataTypeDefinition() {
     }
 
     @Test
-    public void getAllDataTypes() {
+    void getAllDataTypes() {
 
         final TypeRegistryImpl tr = new TypeRegistryImpl();
         tr.addDataType(String.class);
@@ -45,5 +44,4 @@ public void getAllDataTypes() {
         final Collection c = tr.getAllDataTypes();
         assertThat(c.size(), equalTo(3));
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/simplepath/ContractSimplePathTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/simplepath/ContractSimplePathTest.java
index 2286435d8..1b2926611 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/simplepath/ContractSimplePathTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/simplepath/ContractSimplePathTest.java
@@ -5,7 +5,15 @@
  */
 package org.hyperledger.fabric.contract.simplepath;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.TRANSACTION;
+
 import com.google.protobuf.ByteString;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
 import org.hyperledger.fabric.contract.ContractRouter;
 import org.hyperledger.fabric.protos.peer.ChaincodeInput;
 import org.hyperledger.fabric.protos.peer.ChaincodeInput.Builder;
@@ -22,24 +30,15 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.TRANSACTION;
-
 @ExtendWith(SystemStubsExtension.class)
-public final class ContractSimplePathTest {
+final class ContractSimplePathTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
     private ChaincodeMockPeer server;
 
     @AfterEach
-    public void afterTest() throws Exception {
+    void afterTest() throws Exception {
         if (server != null) {
             server.stop();
             server = null;
@@ -52,7 +51,7 @@ public void afterTest() throws Exception {
      * @throws Exception
      */
     @Test
-    public void testContract() throws Exception {
+    void testContract() throws Exception {
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -67,21 +66,22 @@ public void testContract() throws Exception {
         setLogLevel("INFO");
     }
 
-    public ChaincodeMessage newInvokeFn(final String[] args) {
+    private ChaincodeMessage newInvokeFn(final String[] args) {
         final Builder invokePayload = ChaincodeInput.newBuilder();
         for (final String arg : args) {
             invokePayload.addArgs(ByteString.copyFromUtf8(arg));
         }
 
-        return MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload.build().toByteString(), null);
+        return MessageUtil.newEventMessage(
+                TRANSACTION, "testChannel", "0", invokePayload.build().toByteString(), null);
     }
 
-    public String getLastReturnString() throws Exception {
+    private String getLastReturnString() throws Exception {
         final Response resp = Response.parseFrom(server.getLastMessageRcvd().getPayload());
-        return (resp.getPayload().toStringUtf8());
+        return resp.getPayload().toStringUtf8();
     }
 
-    public void setLogLevel(final String logLevel) {
+    private void setLogLevel(final String logLevel) {
         environmentVariables.set("CORE_CHAINCODE_LOGGING_SHIM", logLevel);
         environmentVariables.set("CORE_CHAINCODE_LOGGING_LEVEL", logLevel);
     }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/ledger/LedgerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/ledger/LedgerTest.java
index daa3a5119..fac772017 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/ledger/LedgerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/ledger/LedgerTest.java
@@ -12,10 +12,10 @@
 import org.hyperledger.fabric.contract.Context;
 import org.junit.jupiter.api.Test;
 
-public class LedgerTest {
+final class LedgerTest {
 
     @Test
-    public void getLedger() {
+    void getLedger() {
 
         final Context ctx = mock(Context.class);
         final Ledger ledger = Ledger.getLedger(ctx);
@@ -29,7 +29,7 @@ public void getLedger() {
     }
 
     @Test
-    public void getCollection() {
+    void getCollection() {
 
         final Context ctx = mock(Context.class);
         final Ledger ledger = Ledger.getLedger(ctx);
@@ -44,7 +44,7 @@ public void getCollection() {
     }
 
     @Test
-    public void getNamedCollection() {
+    void getNamedCollection() {
 
         final Context ctx = mock(Context.class);
         final Ledger ledger = Ledger.getLedger(ctx);
@@ -57,7 +57,7 @@ public void getNamedCollection() {
     }
 
     @Test
-    public void getOrganizationCollection() {
+    void getOrganizationCollection() {
 
         final Context ctx = mock(Context.class);
         final Ledger ledger = Ledger.getLedger(ctx);
@@ -68,5 +68,4 @@ public void getOrganizationCollection() {
         final Collection collection2 = ledger.getOrganizationCollection("org1");
         assertThat(collection2).isNotSameAs(collection);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/MetricsTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/MetricsTest.java
index b57c9e5c2..8da2694fc 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/MetricsTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/MetricsTest.java
@@ -10,64 +10,60 @@
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.util.Properties;
-
 import org.hyperledger.fabric.metrics.impl.DefaultProvider;
 import org.hyperledger.fabric.metrics.impl.NullProvider;
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Nested;
 import org.junit.jupiter.api.Test;
 
-public class MetricsTest {
-
-    public static class TestProvider implements MetricsProvider {
+final class MetricsTest {
 
-        public TestProvider() {
+    private static final class TestProvider implements MetricsProvider {
 
-        }
+        public TestProvider() {}
 
         @Override
-        public void setTaskMetricsCollector(final TaskMetricsCollector taskService) {
-        }
+        public void setTaskMetricsCollector(final TaskMetricsCollector taskService) {}
 
         @Override
-        public void initialize(final Properties props) {
-        }
-
+        public void initialize(final Properties props) {}
     }
 
     @Nested
     @DisplayName("Metrics initialize")
-    class Initialize {
+    final class Initialize {
 
         @Test
-        public void metricsDisabled() {
+        void metricsDisabled() {
             final MetricsProvider provider = Metrics.initialize(new Properties());
             assertThat(provider).isExactlyInstanceOf(NullProvider.class);
         }
 
         @Test
-        public void metricsEnabledUnknownProvider() {
+        void metricsEnabledUnknownProvider() {
             final Properties props = new Properties();
             props.put("CHAINCODE_METRICS_PROVIDER", "org.example.metrics.provider");
             props.put("CHAINCODE_METRICS_ENABLED", "true");
 
-            assertThrows(RuntimeException.class, () -> {
-                final MetricsProvider provider = Metrics.initialize(props);
-            }, "Unable to start metrics");
+            assertThrows(
+                    RuntimeException.class,
+                    () -> {
+                        final MetricsProvider provider = Metrics.initialize(props);
+                    },
+                    "Unable to start metrics");
         }
 
         @Test
-        public void metricsNoProvider() {
+        void metricsNoProvider() {
             final Properties props = new Properties();
             props.put("CHAINCODE_METRICS_ENABLED", "true");
 
             final MetricsProvider provider = Metrics.initialize(props);
             assertTrue(provider instanceof DefaultProvider);
-
         }
 
         @Test
-        public void metricsValid() {
+        void metricsValid() {
             final Properties props = new Properties();
             props.put("CHAINCODE_METRICS_PROVIDER", MetricsTest.TestProvider.class.getName());
             props.put("CHAINCODE_METRICS_ENABLED", "true");
@@ -75,7 +71,5 @@ public void metricsValid() {
 
             assertThat(provider).isExactlyInstanceOf(MetricsTest.TestProvider.class);
         }
-
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/impl/DefaultProviderTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/impl/DefaultProviderTest.java
index 985e4be4d..a3fecb8dc 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/impl/DefaultProviderTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/metrics/impl/DefaultProviderTest.java
@@ -13,18 +13,16 @@
 import java.util.logging.LogManager;
 import java.util.logging.LogRecord;
 import java.util.logging.Logger;
-
-import org.hyperledger.fabric.metrics.MetricsProvider;
 import org.hyperledger.fabric.metrics.TaskMetricsCollector;
 import org.junit.jupiter.api.Test;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 
-public class DefaultProviderTest {
+final class DefaultProviderTest {
 
     @Test
-    public void allMethods() {
-        MetricsProvider provider = new DefaultProvider();
+    void allMethods() throws InterruptedException {
+        DefaultProvider provider = new DefaultProvider();
         provider.setTaskMetricsCollector(new TaskMetricsCollector() {
 
             @Override
@@ -74,20 +72,16 @@ public int getActiveCount() {
             perfLogger.addHandler(mockHandler);
 
             provider.initialize(new Properties());
-            ((DefaultProvider) provider).logMetrics();
-            try {
-                Thread.sleep(6000);
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-                throw new RuntimeException(e);
-            }
+            provider.logMetrics();
+            Thread.sleep(6000);
             Mockito.verify(mockHandler, Mockito.atLeast(1)).publish(argumentCaptor.capture());
             LogRecord lr = argumentCaptor.getValue();
             String msg = lr.getMessage();
-            assertThat(msg).contains("{ \"active_count\":0 , \"pool_size\":0 , \"core_pool_size\":0 , \"current_task_count\":0 , \"current_queue_depth\":0 ");
+            assertThat(msg)
+                    .contains(
+                            "{ \"active_count\":0 , \"pool_size\":0 , \"core_pool_size\":0 , \"current_task_count\":0 , \"current_queue_depth\":0 ");
         } finally {
             perfLogger.setLevel(original);
         }
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeBaseTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeBaseTest.java
index 6fd7ef031..894c60fea 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeBaseTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeBaseTest.java
@@ -6,8 +6,19 @@
 
 package org.hyperledger.fabric.shim;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
 import io.grpc.ManagedChannelBuilder;
 import io.grpc.stub.StreamObserver;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.Properties;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.shim.chaincode.EmptyChaincode;
@@ -22,107 +33,129 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.Properties;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
 @ExtendWith(SystemStubsExtension.class)
-public class ChaincodeBaseTest {
+final class ChaincodeBaseTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
     @Test
-    public void testNewSuccessResponseEmpty() {
+    void testNewSuccessResponseEmpty() {
         final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse();
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
         assertThat(response.getMessage()).as("Response message").isNull();
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testNewSuccessResponseWithMessage() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message");
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
+    void testNewSuccessResponseWithMessage() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newSuccessResponse("Simple message");
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Simple message");
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testNewSuccessResponseWithPayload() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple payload".getBytes(Charset.defaultCharset()));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
+    void testNewSuccessResponseWithPayload() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newSuccessResponse("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
         assertThat(response.getMessage()).as("Response message").isNull();
-        assertThat(response.getPayload()).as("Response payload").isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getPayload())
+                .as("Response payload")
+                .isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
     }
 
     @Test
-    public void testNewSuccessResponseWithMessageAndPayload() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message",
-                "Simple payload".getBytes(Charset.defaultCharset()));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
+    void testNewSuccessResponseWithMessageAndPayload() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newSuccessResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Simple message");
-        assertThat(response.getPayload()).as("Response payload").isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getPayload())
+                .as("Response payload")
+                .isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
     }
 
     @Test
-    public void testNewErrorResponseEmpty() {
+    void testNewErrorResponseEmpty() {
         final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse();
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isNull();
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testNewErrorResponseWithMessage() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message");
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+    void testNewErrorResponseWithMessage() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newErrorResponse("Simple message");
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Simple message");
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testNewErrorResponseWithPayload() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple payload".getBytes(Charset.defaultCharset()));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+    void testNewErrorResponseWithPayload() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newErrorResponse("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isNull();
-        assertThat(response.getPayload()).as("Response payload").isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getPayload())
+                .as("Response payload")
+                .isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
     }
 
     @Test
-    public void testNewErrorResponseWithMessageAndPayload() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message",
-                "Simple payload".getBytes(Charset.defaultCharset()));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+    void testNewErrorResponseWithMessageAndPayload() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newErrorResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Simple message");
-        assertThat(response.getPayload()).as("Response payload").isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
+        assertThat(response.getPayload())
+                .as("Response payload")
+                .isEqualTo("Simple payload".getBytes(Charset.defaultCharset()));
     }
 
     @Test
-    public void testNewErrorResponseWithException() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new Exception("Simple exception"));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+    void testNewErrorResponseWithException() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newErrorResponse(new Exception("Simple exception"));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Unexpected error");
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testNewErrorResponseWithChaincodeException() {
-        final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new ChaincodeException("Chaincode exception"));
-        assertThat(response.getStatus()).as("Response status").isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
+    void testNewErrorResponseWithChaincodeException() {
+        final org.hyperledger.fabric.shim.Chaincode.Response response =
+                ResponseUtils.newErrorResponse(new ChaincodeException("Chaincode exception"));
+        assertThat(response.getStatus())
+                .as("Response status")
+                .isEqualTo(org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR);
         assertThat(response.getMessage()).as("Response message").isEqualTo("Chaincode exception");
         assertThat(response.getPayload()).as("Response payload").isNull();
     }
 
     @Test
-    public void testOptions() throws Exception {
+    void testOptions() throws Exception {
         final ChaincodeBase cb = new EmptyChaincode();
 
         assertThat(cb.getHost()).as("Host incorrect").isEqualTo(ChaincodeBase.DEFAULT_HOST);
@@ -164,7 +197,7 @@ public void testOptions() throws Exception {
     }
 
     @Test
-    public void testUnsetOptionId() {
+    void testUnsetOptionId() {
         final ChaincodeBase cb = new EmptyChaincode();
         assertThatThrownBy(cb::validateOptions)
                 .isInstanceOf(IllegalArgumentException.class)
@@ -172,7 +205,7 @@ public void testUnsetOptionId() {
     }
 
     @Test
-    public void testUnsetOptionClientCertPath() {
+    void testUnsetOptionClientCertPath() {
         final ChaincodeBase cb = new EmptyChaincode();
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
         environmentVariables.set("CORE_PEER_TLS_ENABLED", "true");
@@ -183,7 +216,7 @@ public void testUnsetOptionClientCertPath() {
     }
 
     @Test
-    public void testUnsetOptionClientKeyPath() {
+    void testUnsetOptionClientKeyPath() {
         final ChaincodeBase cb = new EmptyChaincode();
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
         environmentVariables.set("CORE_PEER_TLS_ENABLED", "true");
@@ -196,7 +229,7 @@ public void testUnsetOptionClientKeyPath() {
 
     @Test
     @Disabled
-    public void testNewChannelBuilder() throws Exception {
+    void testNewChannelBuilder() throws Exception {
         final ChaincodeBase cb = new EmptyChaincode();
 
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
@@ -212,7 +245,7 @@ public void testNewChannelBuilder() throws Exception {
     }
 
     @Test
-    public void testInitializeLogging() {
+    void testInitializeLogging() {
         final ChaincodeBase cb = new EmptyChaincode();
 
         cb.processEnvironmentOptions();
@@ -258,7 +291,7 @@ public void testInitializeLogging() {
     }
 
     @Test
-    public void testStartFailsWithoutValidOptions() {
+    void testStartFailsWithoutValidOptions() {
         final String[] args = new String[0];
         final ChaincodeBase cb = new EmptyChaincode();
 
@@ -273,11 +306,15 @@ public void testStartFailsWithoutValidOptions() {
         String msg = lr.getMessage();
 
         assertThat(msg).doesNotContain("java.lang.NullPointerException");
-        assertThat(msg).contains(
-            "The chaincode id must be specified using either the -i or --i command line options or the CORE_CHAINCODE_ID_NAME environment variable.");
+        assertThat(msg)
+                .contains(
+                        "The chaincode id must be specified using either the -i or --i command line options or the CORE_CHAINCODE_ID_NAME environment variable.");
     }
 
-    public static void setLogLevelForChaincode(final EnvironmentVariables environmentVariables, final ChaincodeBase cb, final String shimLevel,
+    private static void setLogLevelForChaincode(
+            final EnvironmentVariables environmentVariables,
+            final ChaincodeBase cb,
+            final String shimLevel,
             final String chaincodeLevel) {
         environmentVariables.set(ChaincodeBase.CORE_CHAINCODE_LOGGING_SHIM, shimLevel);
         environmentVariables.set(ChaincodeBase.CORE_CHAINCODE_LOGGING_LEVEL, chaincodeLevel);
@@ -286,7 +323,7 @@ public static void setLogLevelForChaincode(final EnvironmentVariables environmen
     }
 
     @Test
-    public void connectChaincodeBase() throws IOException {
+    void connectChaincodeBase() throws IOException {
         final ChaincodeBase cb = new EmptyChaincode();
 
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
@@ -300,21 +337,15 @@ public void connectChaincodeBase() throws IOException {
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        cb.connectToPeer(new StreamObserver() {
+        cb.connectToPeer(new StreamObserver<>() {
             @Override
-            public void onNext(final ChaincodeMessage value) {
-
-            }
+            public void onNext(final ChaincodeMessage value) {}
 
             @Override
-            public void onError(final Throwable t) {
-
-            }
+            public void onError(final Throwable t) {}
 
             @Override
-            public void onCompleted() {
-
-            }
+            public void onCompleted() {}
         });
 
         environmentVariables.remove("CORE_CHAINCODE_ID_NAME");
@@ -323,13 +354,10 @@ public void onCompleted() {
     }
 
     @Test
-    public void connectChaincodeBaseNull() {
-        Assertions.assertThrows(
-                IllegalArgumentException.class,
-                () -> {
-                    final ChaincodeBase cb = new EmptyChaincode();
-                    cb.connectToPeer(null);
-                }
-        );
+    void connectChaincodeBaseNull() {
+        Assertions.assertThrows(IllegalArgumentException.class, () -> {
+            final ChaincodeBase cb = new EmptyChaincode();
+            cb.connectToPeer(null);
+        });
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeServerImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeServerImplTest.java
index 8b52bbfdc..3d143458b 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeServerImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeServerImplTest.java
@@ -5,6 +5,8 @@
  */
 package org.hyperledger.fabric.shim;
 
+import java.io.IOException;
+import java.net.URISyntaxException;
 import org.hyperledger.fabric.contract.ContractRouter;
 import org.hyperledger.fabric.shim.chaincode.EmptyChaincode;
 import org.junit.jupiter.api.AfterEach;
@@ -15,11 +17,8 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.net.URISyntaxException;
-
 @ExtendWith(SystemStubsExtension.class)
-class ChaincodeServerImplTest {
+final class ChaincodeServerImplTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -49,7 +48,8 @@ void clearEnv() {
     void init() {
         try {
             final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -60,7 +60,8 @@ void initEnvNotSet() {
         clearEnv();
         try {
             final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -69,16 +70,18 @@ void initEnvNotSet() {
     @Test
     void startAndStop() {
         try {
-            final ChaincodeBase chaincodeBase = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            final ChaincodeBase chaincodeBase =
+                    new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
             new Thread(() -> {
-                try {
-                    chaincodeServer.start();
-                } catch (Exception e) {
-                    e.printStackTrace();
-                }
-            }
-            ).start();
+                        try {
+                            chaincodeServer.start();
+                        } catch (Exception e) {
+                            e.printStackTrace();
+                        }
+                    })
+                    .start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeStubTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeStubTest.java
index 37b8db4d8..0a583dead 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeStubTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeStubTest.java
@@ -9,7 +9,6 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
 import org.hyperledger.fabric.protos.peer.SignedProposal;
 import org.hyperledger.fabric.shim.Chaincode.Response;
@@ -20,9 +19,10 @@
 import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata;
 import org.junit.jupiter.api.Test;
 
-public class ChaincodeStubTest {
+final class ChaincodeStubTest {
 
-    class FakeStub implements ChaincodeStub {
+    @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull")
+    private static final class FakeStub implements ChaincodeStub {
 
         @Override
         public List getArgs() {
@@ -102,8 +102,8 @@ public QueryResultsIterator getStateByRange(final String startKey, fin
         }
 
         @Override
-        public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(final String startKey, final String endKey, final int pageSize,
-                final String bookmark) {
+        public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(
+                final String startKey, final String endKey, final int pageSize, final String bookmark) {
             // TODO Auto-generated method stub
             return null;
         }
@@ -115,7 +115,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final String
         }
 
         @Override
-        public QueryResultsIterator getStateByPartialCompositeKey(final String objectType, final String... attributes) {
+        public QueryResultsIterator getStateByPartialCompositeKey(
+                final String objectType, final String... attributes) {
             // TODO Auto-generated method stub
             return null;
         }
@@ -127,8 +128,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final Compos
         }
 
         @Override
-        public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(final CompositeKey compositeKey, final int pageSize,
-                final String bookmark) {
+        public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(
+                final CompositeKey compositeKey, final int pageSize, final String bookmark) {
             // TODO Auto-generated method stub
             return null;
         }
@@ -152,7 +153,8 @@ public QueryResultsIterator getQueryResult(final String query) {
         }
 
         @Override
-        public QueryResultsIteratorWithMetadata getQueryResultWithPagination(final String query, final int pageSize, final String bookmark) {
+        public QueryResultsIteratorWithMetadata getQueryResultWithPagination(
+                final String query, final int pageSize, final String bookmark) {
             // TODO Auto-generated method stub
             return null;
         }
@@ -205,26 +207,29 @@ public void purgePrivateData(final String collection, final String key) {
         }
 
         @Override
-        public QueryResultsIterator getPrivateDataByRange(final String collection, final String startKey, final String endKey) {
+        public QueryResultsIterator getPrivateDataByRange(
+                final String collection, final String startKey, final String endKey) {
             // TODO Auto-generated method stub
             return null;
         }
 
         @Override
-        public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final String compositeKey) {
+        public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+                final String collection, final String compositeKey) {
             // TODO Auto-generated method stub
             return null;
         }
 
         @Override
-        public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final CompositeKey compositeKey) {
+        public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+                final String collection, final CompositeKey compositeKey) {
             // TODO Auto-generated method stub
             return null;
         }
 
         @Override
-        public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection, final String objectType,
-                final String... attributes) {
+        public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+                final String collection, final String objectType, final String... attributes) {
             // TODO Auto-generated method stub
             return null;
         }
@@ -282,17 +287,16 @@ public String getMspId() {
             // TODO Auto-generated method stub
             return null;
         }
-
     }
 
     @Test
-    public void testDefaultMethods() {
+    void testDefaultMethods() {
         final ChaincodeStub stub = new FakeStub();
         final String chaincodeName = "ACME_SHIPPING";
 
-        stub.invokeChaincode(chaincodeName, new ArrayList());
-        stub.invokeChaincodeWithStringArgs(chaincodeName, new ArrayList(), "channel");
-        stub.invokeChaincodeWithStringArgs(chaincodeName, new ArrayList());
+        stub.invokeChaincode(chaincodeName, new ArrayList<>());
+        stub.invokeChaincodeWithStringArgs(chaincodeName, new ArrayList<>(), "channel");
+        stub.invokeChaincodeWithStringArgs(chaincodeName, new ArrayList<>());
         stub.invokeChaincodeWithStringArgs(chaincodeName, "anvil", "tnt");
 
         stub.getStringState("key");
@@ -300,5 +304,4 @@ public void testDefaultMethods() {
         stub.getPrivateDataUTF8("collection", "key");
         stub.putStringState("key", "value");
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeTest.java
index 800ec670b..2eaa38ca0 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChaincodeTest.java
@@ -5,25 +5,26 @@
  */
 package org.hyperledger.fabric.shim;
 
-import org.junit.jupiter.api.Test;
-
-import java.nio.charset.StandardCharsets;
-
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
-public class ChaincodeTest {
+import java.nio.charset.StandardCharsets;
+import org.junit.jupiter.api.Test;
+
+final class ChaincodeTest {
     @Test
-    public void testResponse() {
-        final Chaincode.Response resp = new Chaincode.Response(Chaincode.Response.Status.SUCCESS, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
+    void testResponse() {
+        final Chaincode.Response resp = new Chaincode.Response(
+                Chaincode.Response.Status.SUCCESS, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
         assertThat(Chaincode.Response.Status.SUCCESS).as("Incorrect status").isEqualTo(resp.getStatus());
         assertThat("No message").as("Incorrect message").isEqualTo(resp.getMessage());
         assertThat("no payload").as("Incorrect payload").isEqualTo(resp.getStringPayload());
     }
 
     @Test
-    public void testResponseWithCode() {
-        Chaincode.Response resp = new Chaincode.Response(200, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
+    void testResponseWithCode() {
+        Chaincode.Response resp =
+                new Chaincode.Response(200, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
         assertThat(Chaincode.Response.Status.SUCCESS).as("Incorrect status").isEqualTo(resp.getStatus());
         assertThat(200).as("Incorrect status").isEqualTo(resp.getStatusCode());
         assertThat("No message").as("Incorrect message").isEqualTo(resp.getMessage());
@@ -34,20 +35,28 @@ public void testResponseWithCode() {
         assertThat("No message").as("Incorrect message").isEqualTo(resp.getMessage());
         assertThat("no payload").as("Incorrect payload").isEqualTo(resp.getStringPayload());
 
-        resp = new Chaincode.Response(Chaincode.Response.Status.ERROR_THRESHOLD, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
-        assertThat(Chaincode.Response.Status.ERROR_THRESHOLD).as("Incorrect status").isEqualTo(resp.getStatus());
+        resp = new Chaincode.Response(
+                Chaincode.Response.Status.ERROR_THRESHOLD, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
+        assertThat(Chaincode.Response.Status.ERROR_THRESHOLD)
+                .as("Incorrect status")
+                .isEqualTo(resp.getStatus());
         assertThat(400).as("Incorrect status").isEqualTo(resp.getStatusCode());
         assertThat("No message").as("Incorrect message").isEqualTo(resp.getMessage());
         assertThat("no payload").as("Incorrect payload").isEqualTo(resp.getStringPayload());
     }
 
     @Test
-    public void testStatus() {
-        assertThat(Chaincode.Response.Status.SUCCESS).as("Wrong status").isEqualTo(Chaincode.Response.Status.forCode(200));
-        assertThat(Chaincode.Response.Status.ERROR_THRESHOLD).as("Wrong status").isEqualTo(Chaincode.Response.Status.forCode(400));
-        assertThat(Chaincode.Response.Status.INTERNAL_SERVER_ERROR).as("Wrong status").isEqualTo(Chaincode.Response.Status.forCode(500));
-
-        assertThatThrownBy(() -> Chaincode.Response.Status.forCode(501))
-                .isInstanceOf(IllegalArgumentException.class);
+    void testStatus() {
+        assertThat(Chaincode.Response.Status.SUCCESS)
+                .as("Wrong status")
+                .isEqualTo(Chaincode.Response.Status.forCode(200));
+        assertThat(Chaincode.Response.Status.ERROR_THRESHOLD)
+                .as("Wrong status")
+                .isEqualTo(Chaincode.Response.Status.forCode(400));
+        assertThat(Chaincode.Response.Status.INTERNAL_SERVER_ERROR)
+                .as("Wrong status")
+                .isEqualTo(Chaincode.Response.Status.forCode(500));
+
+        assertThatThrownBy(() -> Chaincode.Response.Status.forCode(501)).isInstanceOf(IllegalArgumentException.class);
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeerTest.java
index 5e7108f31..d6093a5d5 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeerTest.java
@@ -5,8 +5,24 @@
  */
 package org.hyperledger.fabric.shim;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.stream.Collectors.toList;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INIT;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INVOKE_CHAINCODE;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
 import com.google.protobuf.ByteString;
 import io.grpc.stub.StreamObserver;
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+import java.util.stream.Stream;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeInput;
@@ -24,27 +40,10 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static java.util.stream.Collectors.toList;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INIT;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INVOKE_CHAINCODE;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
 @ExtendWith(SystemStubsExtension.class)
-class ChatChaincodeWithPeerTest {
+final class ChatChaincodeWithPeerTest {
     private static final String TEST_CHANNEL = "testChannel";
+
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -75,8 +74,7 @@ void initNull() throws IOException {
                 () -> {
                     ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(null);
                 },
-                "chaincodeBase can't be null"
-        );
+                "chaincodeBase can't be null");
     }
 
     @Test
@@ -112,21 +110,17 @@ void initEmptyId() throws IOException {
                     Traces.initialize(props);
                     ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
                 },
-                "chaincode id not set, set env 'CORE_CHAINCODE_ID_NAME', for example 'CORE_CHAINCODE_ID_NAME=mycc'"
-        );
+                "chaincode id not set, set env 'CORE_CHAINCODE_ID_NAME', for example 'CORE_CHAINCODE_ID_NAME=mycc'");
     }
 
     @Test
     void connectEnvNotSet() throws IOException {
         clearEnv();
 
-        Assertions.assertThrows(
-                IllegalArgumentException.class,
-                () -> {
-                    ChaincodeBase chaincodeBase = new EmptyChaincode();
-                    ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-                }
-        );
+        Assertions.assertThrows(IllegalArgumentException.class, () -> {
+            ChaincodeBase chaincodeBase = new EmptyChaincode();
+            ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
+        });
     }
 
     @Test
@@ -143,6 +137,7 @@ void connectNull() throws IOException {
     }
 
     @Test
+    @SuppressWarnings("PMD.SystemPrintln")
     void connectAndReceiveRegister() throws IOException {
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
         ChaincodeBase chaincodeBase = new EmptyChaincode();
@@ -154,7 +149,7 @@ void connectAndReceiveRegister() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
+        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver<>() {
             @Override
             public void onNext(final ChaincodeMessage value) {
                 assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
@@ -167,49 +162,61 @@ public void onError(final Throwable t) {
             }
 
             @Override
-            public void onCompleted() {
-            }
+            public void onCompleted() {}
         });
         assertNotNull(connect);
 
-        final ByteString payload = org.hyperledger.fabric.protos.peer.ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("")).build()
+        final ByteString payload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
                 .toByteString();
         final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, TEST_CHANNEL, "0", payload, null);
         connect.onNext(initMsg);
 
-        try {
-            final List args = Stream.of("invoke", "a", "1").map(x -> x.getBytes(UTF_8)).collect(toList());
+        {
+            final List args =
+                    Stream.of("invoke", "a", "1").map(x -> x.getBytes(UTF_8)).collect(toList());
             final ByteString invocationSpecPayload = ChaincodeSpec.newBuilder()
-                    .setChaincodeId(ChaincodeID.newBuilder().setName(chaincodeBase.getId()).build())
-                    .setInput(ChaincodeInput.newBuilder().addAllArgs(args.stream().map(ByteString::copyFrom)
-                            .collect(Collectors.toList())).build()).build()
+                    .setChaincodeId(ChaincodeID.newBuilder()
+                            .setName(chaincodeBase.getId())
+                            .build())
+                    .setInput(ChaincodeInput.newBuilder()
+                            .addAllArgs(args.stream().map(ByteString::copyFrom).collect(toList()))
+                            .build())
+                    .build()
                     .toByteString();
 
             final ChaincodeMessage invokeChaincodeMessage = ChaincodeMessage.newBuilder()
-                    .setType(INVOKE_CHAINCODE).setChannelId(TEST_CHANNEL)
-                    .setTxid("1").setPayload(invocationSpecPayload).build();
+                    .setType(INVOKE_CHAINCODE)
+                    .setChannelId(TEST_CHANNEL)
+                    .setTxid("1")
+                    .setPayload(invocationSpecPayload)
+                    .build();
             connect.onNext(invokeChaincodeMessage);
             System.out.println(invokeChaincodeMessage.getPayload().toStringUtf8());
-        } catch (Exception e) {
-
         }
 
-        try {
-            final List args = Stream.of("invoke", "a", "1").map(x -> x.getBytes(UTF_8)).collect(toList());
+        {
+            final List args =
+                    Stream.of("invoke", "a", "1").map(x -> x.getBytes(UTF_8)).collect(toList());
             final ByteString invocationSpecPayload = ChaincodeSpec.newBuilder()
-                    .setChaincodeId(ChaincodeID.newBuilder().setName(chaincodeBase.getId()).build())
-                    .setInput(ChaincodeInput.newBuilder().addAllArgs(args.stream().map(ByteString::copyFrom)
-                            .collect(Collectors.toList())).build()).build()
+                    .setChaincodeId(ChaincodeID.newBuilder()
+                            .setName(chaincodeBase.getId())
+                            .build())
+                    .setInput(ChaincodeInput.newBuilder()
+                            .addAllArgs(args.stream().map(ByteString::copyFrom).collect(toList()))
+                            .build())
+                    .build()
                     .toByteString();
 
             final ChaincodeMessage invokeChaincodeMessage = ChaincodeMessage.newBuilder()
-                    .setType(INVOKE_CHAINCODE).setChannelId(TEST_CHANNEL)
-                    .setTxid("2").setPayload(invocationSpecPayload).build();
+                    .setType(INVOKE_CHAINCODE)
+                    .setChannelId(TEST_CHANNEL)
+                    .setTxid("2")
+                    .setPayload(invocationSpecPayload)
+                    .build();
             connect.onNext(invokeChaincodeMessage);
             System.out.println(invokeChaincodeMessage.getPayload().toStringUtf8());
-        } catch (Exception e) {
-
         }
     }
 
@@ -225,7 +232,7 @@ void connectAndReceiveRegisterComplete() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
+        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver<>() {
             @Override
             public void onNext(final ChaincodeMessage value) {
                 assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
@@ -238,8 +245,7 @@ public void onError(final Throwable t) {
             }
 
             @Override
-            public void onCompleted() {
-            }
+            public void onCompleted() {}
         });
         connect.onCompleted();
     }
@@ -256,23 +262,21 @@ void connectAndReceiveRegisterException() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
+        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver<>() {
             @Override
-            public void onNext(final ChaincodeMessage value) {
-            }
+            public void onNext(final ChaincodeMessage value) {}
 
             @Override
-            public void onError(final Throwable t) {
-            }
+            public void onError(final Throwable t) {}
 
             @Override
-            public void onCompleted() {
-            }
+            public void onCompleted() {}
         });
         connect.onError(new Exception("some_error"));
     }
 
     @Test
+    @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
     void connectOnCompletedException() throws IOException {
         environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc");
         ChaincodeBase chaincodeBase = new EmptyChaincode();
@@ -287,15 +291,12 @@ void connectOnCompletedException() throws IOException {
 
         Assertions.assertDoesNotThrow(
                 () -> {
-                    final StreamObserver connect = chatChaincodeWithPeer
-                            .connect(new StreamObserver() {
+                    chatChaincodeWithPeer.connect(new StreamObserver<>() {
                         @Override
-                        public void onNext(final ChaincodeMessage value) {
-                        }
+                        public void onNext(final ChaincodeMessage value) {}
 
                         @Override
-                        public void onError(final Throwable t) {
-                        }
+                        public void onError(final Throwable t) {}
 
                         @Override
                         public void onCompleted() {
@@ -303,8 +304,7 @@ public void onCompleted() {
                         }
                     });
                 },
-                "some_error"
-        );
+                "some_error");
     }
 
     @Test
@@ -316,18 +316,15 @@ void testMockChaincodeBase() throws IOException {
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(mockChaincodeBase);
         assertNotNull(chatChaincodeWithPeer);
 
-        assertNull(chatChaincodeWithPeer.connect(new StreamObserver() {
+        assertNull(chatChaincodeWithPeer.connect(new StreamObserver<>() {
             @Override
-            public void onNext(final ChaincodeMessage value) {
-            }
+            public void onNext(final ChaincodeMessage value) {}
 
             @Override
-            public void onError(final Throwable t) {
-            }
+            public void onError(final Throwable t) {}
 
             @Override
-            public void onCompleted() {
-            }
+            public void onCompleted() {}
         }));
     }
 
@@ -342,10 +339,9 @@ void testMockChaincodeBaseThrowIOException() throws IOException {
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(mockChaincodeBase);
         assertNotNull(chatChaincodeWithPeer);
 
-        assertNull(chatChaincodeWithPeer.connect(new StreamObserver() {
+        assertNull(chatChaincodeWithPeer.connect(new StreamObserver<>() {
             @Override
-            public void onNext(final ChaincodeMessage value) {
-            }
+            public void onNext(final ChaincodeMessage value) {}
 
             @Override
             public void onError(final Throwable t) {
@@ -353,8 +349,7 @@ public void onError(final Throwable t) {
             }
 
             @Override
-            public void onCompleted() {
-            }
+            public void onCompleted() {}
         }));
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/NettyGrpcServerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/NettyGrpcServerTest.java
index c14163e77..05bfb3ff8 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/NettyGrpcServerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/NettyGrpcServerTest.java
@@ -5,6 +5,9 @@
  */
 package org.hyperledger.fabric.shim;
 
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.Properties;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.shim.chaincode.EmptyChaincode;
 import org.hyperledger.fabric.traces.Traces;
@@ -17,12 +20,8 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.Properties;
-
 @ExtendWith(SystemStubsExtension.class)
-class NettyGrpcServerTest {
+final class NettyGrpcServerTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -53,7 +52,8 @@ void initNoTls() {
         try {
             final ChaincodeBase chaincodeBase = new EmptyChaincode();
             chaincodeBase.processEnvironmentOptions();
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
         } catch (IOException | URISyntaxException e) {
             e.printStackTrace();
         }
@@ -61,100 +61,138 @@ void initNoTls() {
 
     @Test
     void validationNoChaincodeServerPropertiesg() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, null);
-        }, "ChaincodeServerProperties must be specified");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, null);
+                },
+                "ChaincodeServerProperties must be specified");
     }
 
     @Test
     void validationPortChaincodeServer() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setServerAddress(null);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getServerAddress() must be set");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setServerAddress(null);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getServerAddress() must be set");
     }
 
     @Test
     void validationKeepAliveTimeMinutes() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setKeepAliveTimeMinutes(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setKeepAliveTimeMinutes(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0");
     }
 
     @Test
     void validationKeepAliveTimeoutSeconds() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setKeepAliveTimeoutSeconds(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setKeepAliveTimeoutSeconds(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0");
     }
 
     @Test
     void validationPermitKeepAliveTimeMinutes() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setPermitKeepAliveTimeMinutes(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setPermitKeepAliveTimeMinutes(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0");
     }
 
     @Test
     void validationMaxConnectionAgeSeconds() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setMaxConnectionAgeSeconds(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setMaxConnectionAgeSeconds(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0");
     }
 
     @Test
     void validationMaxInboundMetadataSize() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setMaxInboundMetadataSize(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setMaxInboundMetadataSize(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0");
     }
 
     @Test
     void validationMaxInboundMessageSize() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setMaxInboundMessageSize(-1);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setMaxInboundMessageSize(-1);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
     }
 
     @Test
     void validationTlsEnabledButKeyNotSet() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            final ChaincodeBase chaincodeBase = new EmptyChaincode();
-            final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
-            chaincodeServerProperties.setTlsEnabled(true);
-            chaincodeServerProperties.setKeyFile(null);
-            chaincodeServerProperties.setKeyCertChainFile(null);
-            chaincodeServerProperties.setKeyPassword(null);
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
-        }, "ChaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    final ChaincodeBase chaincodeBase = new EmptyChaincode();
+                    final ChaincodeServerProperties chaincodeServerProperties = new ChaincodeServerProperties();
+                    chaincodeServerProperties.setTlsEnabled(true);
+                    chaincodeServerProperties.setKeyFile(null);
+                    chaincodeServerProperties.setKeyCertChainFile(null);
+                    chaincodeServerProperties.setKeyPassword(null);
+                    ChaincodeServer chaincodeServer =
+                            new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
+                },
+                "ChaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
     }
 
     @Test
     void initNull() {
-        Assertions.assertThrows(IllegalArgumentException.class, () -> {
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(null, new ChaincodeServerProperties());
-        }, "chaincode must be specified");
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> {
+                    ChaincodeServer chaincodeServer = new NettyChaincodeServer(null, new ChaincodeServerProperties());
+                },
+                "chaincode must be specified");
     }
 
     @Test
@@ -163,7 +201,6 @@ void initNullEnvNotSet() {
         Assertions.assertThrows(IllegalArgumentException.class, () -> {
             ChaincodeServer chaincodeServer = new NettyChaincodeServer(null, new ChaincodeServerProperties());
         });
-
     }
 
     @Test
@@ -187,8 +224,8 @@ void initEnvSetPortChaincodeServerAndCoreChaincodeIdName() throws IOException, U
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
-
+        ChaincodeServer chaincodeServer =
+                new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
     }
 
     @Test
@@ -203,14 +240,16 @@ void startAndStopSetCoreChaincodeIdName() {
             Metrics.initialize(props);
             Traces.initialize(props);
 
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
             new Thread(() -> {
-                try {
-                    chaincodeServer.start();
-                } catch (IOException | InterruptedException e) {
-                    e.printStackTrace();
-                }
-            }).start();
+                        try {
+                            chaincodeServer.start();
+                        } catch (IOException | InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    })
+                    .start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
@@ -218,7 +257,7 @@ void startAndStopSetCoreChaincodeIdName() {
             }
 
             chaincodeServer.stop();
-        } catch (IOException | URISyntaxException  e) {
+        } catch (IOException | URISyntaxException e) {
             e.printStackTrace();
         }
     }
@@ -228,14 +267,16 @@ void startAndStop() {
         try {
             final ChaincodeBase chaincodeBase = new EmptyChaincode();
             chaincodeBase.processEnvironmentOptions();
-            ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
+            ChaincodeServer chaincodeServer =
+                    new NettyChaincodeServer(chaincodeBase, chaincodeBase.getChaincodeServerConfig());
             new Thread(() -> {
-                try {
-                    chaincodeServer.start();
-                } catch (IOException | InterruptedException e) {
-                    e.printStackTrace();
-                }
-            }).start();
+                        try {
+                            chaincodeServer.start();
+                        } catch (IOException | InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    })
+                    .start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
@@ -260,12 +301,13 @@ void startAndStopTlsPassword() {
             chaincodeServerProperties.setKeyPassword("test");
             ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
             new Thread(() -> {
-                try {
-                    chaincodeServer.start();
-                } catch (IOException | InterruptedException e) {
-                    e.printStackTrace();
-                }
-            }).start();
+                        try {
+                            chaincodeServer.start();
+                        } catch (IOException | InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    })
+                    .start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
@@ -289,12 +331,13 @@ void startAndStopTlsWithoutPassword() {
             chaincodeServerProperties.setKeyCertChainFile("src/test/resources/client.crt");
             ChaincodeServer chaincodeServer = new NettyChaincodeServer(chaincodeBase, chaincodeServerProperties);
             new Thread(() -> {
-                try {
-                    chaincodeServer.start();
-                } catch (IOException | InterruptedException e) {
-                    e.printStackTrace();
-                }
-            }).start();
+                        try {
+                            chaincodeServer.start();
+                        } catch (IOException | InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    })
+                    .start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsementTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsementTest.java
index d1d23adb7..3ab30011c 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsementTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsementTest.java
@@ -5,19 +5,20 @@
  */
 package org.hyperledger.fabric.shim.ext.sbe;
 
-import org.junit.jupiter.api.Test;
-
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
-public class StateBasedEndorsementTest {
+import org.junit.jupiter.api.Test;
+
+final class StateBasedEndorsementTest {
     @Test
-    public void testRoleType() {
-        assertThat(StateBasedEndorsement.RoleType.forVal("MEMBER")).isEqualTo(StateBasedEndorsement.RoleType.RoleTypeMember);
-        assertThat(StateBasedEndorsement.RoleType.forVal("PEER")).isEqualTo(StateBasedEndorsement.RoleType.RoleTypePeer);
+    void testRoleType() {
+        assertThat(StateBasedEndorsement.RoleType.forVal("MEMBER"))
+                .isEqualTo(StateBasedEndorsement.RoleType.RoleTypeMember);
+        assertThat(StateBasedEndorsement.RoleType.forVal("PEER"))
+                .isEqualTo(StateBasedEndorsement.RoleType.RoleTypePeer);
 
         assertThatThrownBy(() -> StateBasedEndorsement.RoleType.forVal("NONEXIST"))
                 .isInstanceOf(IllegalArgumentException.class);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactoryTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactoryTest.java
index 08896e603..c980b5a26 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactoryTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactoryTest.java
@@ -5,22 +5,21 @@
  */
 package org.hyperledger.fabric.shim.ext.sbe.impl;
 
-import org.junit.jupiter.api.Test;
-
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 
+import org.junit.jupiter.api.Test;
 
-public class StateBasedEndorsementFactoryTest {
+final class StateBasedEndorsementFactoryTest {
     @Test
-    public void getInstance() {
+    void getInstance() {
         assertNotNull(StateBasedEndorsementFactory.getInstance());
         assertInstanceOf(StateBasedEndorsementFactory.class, StateBasedEndorsementFactory.getInstance());
     }
 
     @Test
-    public void newStateBasedEndorsement() {
+    void newStateBasedEndorsement() {
         assertNotNull(StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {}));
         assertThatThrownBy(() -> StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {0}))
                 .isInstanceOf(IllegalArgumentException.class);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImplTest.java
index 332fa3477..fe6482fbf 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImplTest.java
@@ -5,13 +5,6 @@
  */
 package org.hyperledger.fabric.shim.ext.sbe.impl;
 
-import org.hyperledger.fabric.protos.common.MSPRole.MSPRoleType;
-import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
-import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement.RoleType;
-import org.junit.jupiter.api.Test;
-
-import java.util.List;
-
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.hasSize;
@@ -21,26 +14,38 @@
 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
-public class StateBasedEndorsementImplTest {
+import java.util.List;
+import org.hyperledger.fabric.protos.common.MSPRole.MSPRoleType;
+import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
+import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement.RoleType;
+import org.junit.jupiter.api.Test;
+
+final class StateBasedEndorsementImplTest {
 
     @Test
-    public void addOrgs() {
+    void addOrgs() {
         // add an org
-        final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null);
+        final StateBasedEndorsement ep =
+                StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null);
         ep.addOrgs(RoleType.RoleTypePeer, "Org1");
 
         final byte[] epBytes = ep.policy();
         assertThat(epBytes, is(not(nullValue())));
         assertTrue(epBytes.length > 0);
-        final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray();
+        final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER)
+                .toByteString()
+                .toByteArray();
         assertArrayEquals(expectedEPBytes, epBytes);
     }
 
     @Test
-    public void delOrgs() {
+    void delOrgs() {
 
-        final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray();
-        final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes);
+        final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER)
+                .toByteString()
+                .toByteArray();
+        final StateBasedEndorsement ep =
+                StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes);
         final List listOrgs = ep.listOrgs();
 
         assertThat(listOrgs, is(not(nullValue())));
@@ -54,14 +59,19 @@ public void delOrgs() {
 
         assertThat(epBytes, is(not(nullValue())));
         assertTrue(epBytes.length > 0);
-        final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org2", MSPRoleType.MEMBER).toByteString().toByteArray();
+        final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org2", MSPRoleType.MEMBER)
+                .toByteString()
+                .toByteArray();
         assertArrayEquals(expectedEPBytes, epBytes);
     }
 
     @Test
-    public void listOrgs() {
-        final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray();
-        final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes);
+    void listOrgs() {
+        final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER)
+                .toByteString()
+                .toByteArray();
+        final StateBasedEndorsement ep =
+                StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes);
         final List listOrgs = ep.listOrgs();
 
         assertThat(listOrgs, is(not(nullValue())));
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/fvt/ChaincodeFVTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/fvt/ChaincodeFVTest.java
index 0ebd3c6b7..0148486a3 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/fvt/ChaincodeFVTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/fvt/ChaincodeFVTest.java
@@ -5,7 +5,25 @@
  */
 package org.hyperledger.fabric.shim.fvt;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.COMPLETED;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INIT;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.RESPONSE;
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.TRANSACTION;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
 import com.google.protobuf.ByteString;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 import org.hyperledger.fabric.protos.peer.ChaincodeInput;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.Response;
@@ -42,27 +60,8 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.COMPLETED;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.INIT;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.READY;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.RESPONSE;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.TRANSACTION;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
-
 @ExtendWith(SystemStubsExtension.class)
-public final class ChaincodeFVTest {
+final class ChaincodeFVTest {
 
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
@@ -70,7 +69,7 @@ public final class ChaincodeFVTest {
     private ChaincodeMockPeer server;
 
     @AfterEach
-    public void afterTest() throws Exception {
+    void afterTest() throws Exception {
         if (server != null) {
             server.stop();
             server = null;
@@ -78,7 +77,7 @@ public void afterTest() throws Exception {
     }
 
     @Test
-    public void testRegister() throws Exception {
+    void testRegister() throws Exception {
         final ChaincodeBase cb = new EmptyChaincode();
 
         final List scenario = new ArrayList<>();
@@ -86,7 +85,7 @@ public void testRegister() throws Exception {
 
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
@@ -95,7 +94,7 @@ public void testRegister() throws Exception {
     }
 
     @Test
-    public void testRegisterAndEmptyInit() throws Exception {
+    void testRegisterAndEmptyInit() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -108,10 +107,11 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString payload = org.hyperledger.fabric.protos.peer.ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("")).build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload,
-                null);
+        final ByteString payload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -119,7 +119,7 @@ public Response invoke(final ChaincodeStub stub) {
 
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -130,7 +130,7 @@ public Response invoke(final ChaincodeStub stub) {
     }
 
     @Test
-    public void testInitAndInvoke() throws Exception {
+    void testInitAndInvoke() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -153,10 +153,13 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8("init"))
-                .addArgs(ByteString.copyFromUtf8("a")).addArgs(ByteString.copyFromUtf8("100")).build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8("init"))
+                .addArgs(ByteString.copyFromUtf8("a"))
+                .addArgs(ByteString.copyFromUtf8("100"))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -170,7 +173,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -178,14 +181,16 @@ public Response invoke(final ChaincodeStub stub) {
 
         assertThat(server.getLastMessageSend().getType(), is(INIT));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response1"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response1"));
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).addArgs(ByteString.copyFromUtf8("a"))
-                .addArgs(ByteString.copyFromUtf8("10")).build().toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .addArgs(ByteString.copyFromUtf8("a"))
+                .addArgs(ByteString.copyFromUtf8("10"))
+                .build()
+                .toByteString();
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         server.send(invokeMsg);
 
@@ -199,7 +204,7 @@ public Response invoke(final ChaincodeStub stub) {
     }
 
     @Test
-    public void testStateValidationParameter() throws Exception {
+    void testStateValidationParameter() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -210,20 +215,22 @@ public Response init(final ChaincodeStub stub) {
             public Response invoke(final ChaincodeStub stub) {
                 final String aKey = stub.getStringArgs().get(1);
                 final byte[] epBytes = stub.getStateValidationParameter(aKey);
-                final StateBasedEndorsement stateBasedEndorsement = StateBasedEndorsementFactory.getInstance()
-                        .newStateBasedEndorsement(epBytes);
+                final StateBasedEndorsement stateBasedEndorsement =
+                        StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(epBytes);
                 assertThat(stateBasedEndorsement.listOrgs().size(), is(2));
                 stub.setStateValidationParameter(aKey, stateBasedEndorsement.policy());
                 return ResponseUtils.newSuccessResponse("OK response2");
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8("init"))
-                .build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8("init"))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
-        final StateBasedEndorsement sbe = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null);
+        final StateBasedEndorsement sbe =
+                StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null);
         sbe.addOrgs(StateBasedEndorsement.RoleType.RoleTypePeer, "Org1");
         sbe.addOrgs(StateBasedEndorsement.RoleType.RoleTypeMember, "Org2");
 
@@ -238,7 +245,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -246,26 +253,26 @@ public Response invoke(final ChaincodeStub stub) {
 
         assertThat(server.getLastMessageSend().getType(), is(INIT));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response1"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response1"));
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).addArgs(ByteString.copyFromUtf8("a")).build()
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .addArgs(ByteString.copyFromUtf8("a"))
+                .build()
                 .toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         server.send(invokeMsg);
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 5, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
     }
 
     @Test
-    public void testInvokeRangeQ() throws Exception {
+    void testInvokeRangeQ() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -293,16 +300,20 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8(""))
-                .build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).addArgs(ByteString.copyFromUtf8("a"))
-                .addArgs(ByteString.copyFromUtf8("b")).build().toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .addArgs(ByteString.copyFromUtf8("a"))
+                .addArgs(ByteString.copyFromUtf8("b"))
+                .build()
+                .toByteString();
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -318,7 +329,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -329,20 +340,18 @@ public Response invoke(final ChaincodeStub stub) {
         ChaincodeMockPeer.checkScenarioStepEnded(server, 5, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
 
         server.send(invokeMsg);
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 9, 30000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
     }
 
     @Test
-    public void testGetQueryResult() throws Exception {
+    void testGetQueryResult() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -367,16 +376,19 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8(""))
-                .build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).addArgs(ByteString.copyFromUtf8("query")).build()
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .addArgs(ByteString.copyFromUtf8("query"))
+                .build()
                 .toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -392,7 +404,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -403,20 +415,18 @@ public Response invoke(final ChaincodeStub stub) {
         ChaincodeMockPeer.checkScenarioStepEnded(server, 5, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
 
         server.send(invokeMsg);
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 9, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
     }
 
     @Test
-    public void testGetHistoryForKey() throws Exception {
+    void testGetHistoryForKey() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -441,16 +451,19 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8(""))
-                .build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).addArgs(ByteString.copyFromUtf8("key1")).build()
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .addArgs(ByteString.copyFromUtf8("key1"))
+                .build()
                 .toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -462,7 +475,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -473,13 +486,11 @@ public Response invoke(final ChaincodeStub stub) {
         ChaincodeMockPeer.checkScenarioStepEnded(server, 5, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(RESPONSE));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(),
-                is("OK response2"));
-
+        assertThat(Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage(), is("OK response2"));
     }
 
     @Test
-    public void testInvokeChaincode() throws Exception {
+    void testInvokeChaincode() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -493,15 +504,18 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString initPayload = ChaincodeInput.newBuilder().addArgs(ByteString.copyFromUtf8(""))
-                .build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0",
-                initPayload, null);
+        final ByteString initPayload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", initPayload, null);
 
         final ByteString invokePayload = ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("invoke")).build().toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+                .addArgs(ByteString.copyFromUtf8("invoke"))
+                .build()
+                .toByteString();
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -512,7 +526,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -526,7 +540,7 @@ public Response invoke(final ChaincodeStub stub) {
     }
 
     @Test
-    public void testErrorInitInvoke() throws Exception {
+    void testErrorInitInvoke() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
@@ -539,10 +553,11 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString payload = org.hyperledger.fabric.protos.peer.ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("")).build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload,
-                null);
+        final ByteString payload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -552,7 +567,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
 
         server.send(initMsg);
@@ -560,30 +575,34 @@ public Response invoke(final ChaincodeStub stub) {
 
         assertThat(server.getLastMessageSend().getType(), is(INIT));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        String resp1 = (Response.parseFrom(server.getLastMessageRcvd().getPayload()).getPayload().toStringUtf8());
+        String resp1 = Response.parseFrom(server.getLastMessageRcvd().getPayload())
+                .getPayload()
+                .toStringUtf8();
         assertThat(resp1, is("Wrong response1"));
 
         final ByteString invokePayload = ChaincodeInput.newBuilder().build().toByteString();
-        final ChaincodeMessage invokeMsg = MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0",
-                invokePayload, null);
+        final ChaincodeMessage invokeMsg =
+                MessageUtil.newEventMessage(TRANSACTION, "testChannel", "0", invokePayload, null);
 
         server.send(invokeMsg);
 
         ChaincodeMockPeer.checkScenarioStepEnded(server, 3, 5000, TimeUnit.MILLISECONDS);
         assertThat(server.getLastMessageSend().getType(), is(TRANSACTION));
         assertThat(server.getLastMessageRcvd().getType(), is(COMPLETED));
-        String resp2 = Response.parseFrom(server.getLastMessageRcvd().getPayload()).getMessage().toString();
+        String resp2 = Response.parseFrom(server.getLastMessageRcvd().getPayload())
+                .getMessage()
+                .toString();
         assertThat(resp2, is("Wrong response2"));
     }
 
     @Test
-    public void testStreamShutdown() throws Exception {
+    void testStreamShutdown() throws Exception {
         final ChaincodeBase cb = new ChaincodeBase() {
             @Override
             public Response init(final ChaincodeStub stub) {
                 try {
                     Thread.sleep(10);
-                } catch (final InterruptedException e) {
+                } catch (final InterruptedException ignored) {
                 }
                 return ResponseUtils.newSuccessResponse();
             }
@@ -594,10 +613,11 @@ public Response invoke(final ChaincodeStub stub) {
             }
         };
 
-        final ByteString payload = org.hyperledger.fabric.protos.peer.ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("")).build().toByteString();
-        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload,
-                null);
+        final ByteString payload = ChaincodeInput.newBuilder()
+                .addArgs(ByteString.copyFromUtf8(""))
+                .build()
+                .toByteString();
+        final ChaincodeMessage initMsg = MessageUtil.newEventMessage(INIT, "testChannel", "0", payload, null);
 
         final List scenario = new ArrayList<>();
         scenario.add(new RegisterStep());
@@ -606,7 +626,7 @@ public Response invoke(final ChaincodeStub stub) {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         ChaincodeMockPeer.checkScenarioStepEnded(server, 1, 5000, TimeUnit.MILLISECONDS);
         server.send(initMsg);
         server.stop();
@@ -614,7 +634,7 @@ public Response invoke(final ChaincodeStub stub) {
     }
 
     @Test
-    public void testChaincodeLogLevel() throws Exception {
+    void testChaincodeLogLevel() throws Exception {
         final ChaincodeBase cb = new EmptyChaincode();
 
         final List scenario = new ArrayList<>();
@@ -624,14 +644,15 @@ public void testChaincodeLogLevel() throws Exception {
         setLogLevel("DEBUG");
         server = ChaincodeMockPeer.startServer(scenario);
 
-        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId" });
+        cb.start(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
 
-        assertEquals(Level.FINEST,
+        assertEquals(
+                Level.FINEST,
                 Logger.getLogger(cb.getClass().getPackage().getName()).getLevel(),
                 "Wrong debug level for " + cb.getClass().getPackage().getName());
     }
 
-    public void setLogLevel(final String logLevel) {
+    private void setLogLevel(final String logLevel) {
         environmentVariables.set("CORE_CHAINCODE_LOGGING_SHIM", logLevel);
         environmentVariables.set("CORE_CHAINCODE_LOGGING_LEVEL", logLevel);
     }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactoryTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactoryTest.java
index 97da696b9..ca152f9ad 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactoryTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactoryTest.java
@@ -6,17 +6,16 @@
 
 package org.hyperledger.fabric.shim.impl;
 
-import org.hyperledger.fabric.protos.peer.ChaincodeID;
+import com.google.protobuf.ByteString;
 import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
+import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type;
 import org.hyperledger.fabric.shim.Chaincode.Response;
 import org.hyperledger.fabric.shim.ResponseUtils;
 import org.junit.jupiter.api.Test;
 
-import com.google.protobuf.ByteString;
-
-class ChaincodeMessageFactoryTest {
+final class ChaincodeMessageFactoryTest {
 
     private final String txId = "txid";
     private final String key = "key";
@@ -29,7 +28,8 @@ class ChaincodeMessageFactoryTest {
     private ChaincodeEvent event;
     private final Response response = ResponseUtils.newSuccessResponse();
     private final ByteString payload = ByteString.copyFromUtf8("Hello");
-    private final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("test").build();
+    private final ChaincodeID chaincodeId =
+            ChaincodeID.newBuilder().setName("test").build();
     private final Type type = ChaincodeMessage.Type.COMPLETED;
 
     @Test
@@ -90,5 +90,4 @@ void testNewEventMessageTypeStringStringByteString() {
         ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload);
         ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload, event);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClientTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClientTest.java
index c3cf24d8d..369f22cc4 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClientTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClientTest.java
@@ -5,8 +5,12 @@
  */
 package org.hyperledger.fabric.shim.impl;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
 import io.grpc.ManagedChannelBuilder;
 import io.grpc.stub.StreamObserver;
+import java.io.IOException;
+import java.util.Properties;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
@@ -19,13 +23,8 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.util.Properties;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
 @ExtendWith(SystemStubsExtension.class)
-class ChaincodeSupportClientTest {
+final class ChaincodeSupportClientTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -44,15 +43,18 @@ void testStartInvocationTaskManagerAndRequestObserverNull() throws IOException {
         ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(managedChannelBuilder);
 
         assertThatThrownBy(
-                () -> {
-                    final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
-                    final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
-
-                    final StreamObserver requestObserver = null;
-                    chaincodeSupportClient.start(itm, requestObserver);
-                },
-                "StreamObserver 'requestObserver' for chat with peer can't be null"
-        ).isInstanceOf(IOException.class);
+                        () -> {
+                            final ChaincodeID chaincodeId = ChaincodeID.newBuilder()
+                                    .setName("chaincodeIdNumber12345")
+                                    .build();
+                            final InvocationTaskManager itm =
+                                    InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
+
+                            final StreamObserver requestObserver = null;
+                            chaincodeSupportClient.start(itm, requestObserver);
+                        },
+                        "StreamObserver 'requestObserver' for chat with peer can't be null")
+                .isInstanceOf(IOException.class);
         environmentVariables.remove("CORE_CHAINCODE_ID_NAME");
     }
 
@@ -71,26 +73,20 @@ void testStartInvocationTaskManagerNullAndRequestObserver() throws IOException {
         ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(managedChannelBuilder);
 
         assertThatThrownBy(
-                () -> {
-                    chaincodeSupportClient.start(null, new StreamObserver() {
-                        @Override
-                        public void onNext(final ChaincodeMessage value) {
-
-                        }
-
-                        @Override
-                        public void onError(final Throwable t) {
-
-                        }
-
-                        @Override
-                        public void onCompleted() {
-
-                        }
-                    });
-                },
-                "InvocationTaskManager 'itm' can't be null"
-        ).isInstanceOf(IOException.class);
+                        () -> {
+                            chaincodeSupportClient.start(null, new StreamObserver<>() {
+                                @Override
+                                public void onNext(final ChaincodeMessage value) {}
+
+                                @Override
+                                public void onError(final Throwable t) {}
+
+                                @Override
+                                public void onCompleted() {}
+                            });
+                        },
+                        "InvocationTaskManager 'itm' can't be null")
+                .isInstanceOf(IOException.class);
         environmentVariables.remove("CORE_CHAINCODE_ID_NAME");
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InnvocationTaskManagerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InnvocationTaskManagerTest.java
index 6ef01199e..a7f1348af 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InnvocationTaskManagerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InnvocationTaskManagerTest.java
@@ -5,8 +5,13 @@
  */
 package org.hyperledger.fabric.shim.impl;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
 import com.google.protobuf.ByteString;
 import io.grpc.ManagedChannelBuilder;
+import java.io.IOException;
+import java.util.Properties;
+import java.util.function.Consumer;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
@@ -22,14 +27,8 @@
 import uk.org.webcompere.systemstubs.jupiter.SystemStub;
 import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
 
-import java.io.IOException;
-import java.util.Properties;
-import java.util.function.Consumer;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
 @ExtendWith(SystemStubsExtension.class)
-class InnvocationTaskManagerTest {
+final class InnvocationTaskManagerTest {
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -64,7 +63,8 @@ void getManager() throws IOException {
         Traces.initialize(props);
         Metrics.initialize(props);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
     }
 
@@ -80,24 +80,25 @@ void getManagerChaincodeIDNull() throws IOException {
         Traces.initialize(props);
 
         Assertions.assertThrows(
-                IllegalArgumentException.class, () -> {
+                IllegalArgumentException.class,
+                () -> {
                     final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, null);
                 },
-                "chaincodeId can't be null"
-        );
+                "chaincodeId can't be null");
     }
 
     @Test
     void getManagerChaincodeBaseNull() throws IOException {
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
 
         Assertions.assertThrows(
-                IllegalArgumentException.class, () -> {
+                IllegalArgumentException.class,
+                () -> {
                     final InvocationTaskManager itm = InvocationTaskManager.getManager(null, chaincodeId);
                 },
-                "chaincode is null"
-        );
+                "chaincode is null");
     }
 
     @Test
@@ -111,13 +112,12 @@ void onChaincodeMessage() throws IOException {
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
 
         Assertions.assertThrows(
-                IllegalArgumentException.class, () -> itm.onChaincodeMessage(null),
-            "chaincodeMessage is null"
-        );
+                IllegalArgumentException.class, () -> itm.onChaincodeMessage(null), "chaincodeMessage is null");
     }
 
     @Test
@@ -131,7 +131,8 @@ void setResponseConsumer() throws IOException {
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
         itm.setResponseConsumer(null);
     }
@@ -147,14 +148,11 @@ void registerException() {
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
 
-        Assertions.assertThrows(
-                IllegalArgumentException.class, itm::register,
-                "outgoingMessage is null"
-        );
-
+        Assertions.assertThrows(IllegalArgumentException.class, itm::register, "outgoingMessage is null");
     }
 
     @Test
@@ -168,7 +166,8 @@ void onChaincodeMessageREGISTER() {
         Metrics.initialize(props);
         Traces.initialize(props);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
         final Consumer consumer = t -> {
             assertEquals(ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId), t);
@@ -191,15 +190,16 @@ void onChaincodeMessageInvokeChaincode() {
         Traces.initialize(props);
 
         final String chaincodeIdNumber = "chaincodeIdNumber12345";
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(chaincodeIdNumber).build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName(chaincodeIdNumber).build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
         final Consumer consumer = t -> {
             assertEquals(ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId), t);
         };
 
         itm.setResponseConsumer(consumer);
-        final ChaincodeMessage chaincodeMessage = ChaincodeMessageFactory
-                .newInvokeChaincodeMessage(chaincodeIdNumber, "txid", ByteString.copyFromUtf8(""));
+        final ChaincodeMessage chaincodeMessage = ChaincodeMessageFactory.newInvokeChaincodeMessage(
+                chaincodeIdNumber, "txid", ByteString.copyFromUtf8(""));
         itm.onChaincodeMessage(chaincodeMessage);
     }
 
@@ -215,15 +215,16 @@ void onChaincodeMessagePutState() {
         Traces.initialize(props);
 
         final String chaincodeIdNumber = "chaincodeIdNumber12345";
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(chaincodeIdNumber).build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName(chaincodeIdNumber).build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
         final Consumer consumer = t -> {
             assertEquals(ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId), t);
         };
 
         itm.setResponseConsumer(consumer);
-        final ChaincodeMessage chaincodeMessage = ChaincodeMessageFactory
-                .newPutStateEventMessage(chaincodeIdNumber, "txid", "collection", "key", ByteString.copyFromUtf8("value"));
+        final ChaincodeMessage chaincodeMessage = ChaincodeMessageFactory.newPutStateEventMessage(
+                chaincodeIdNumber, "txid", "collection", "key", ByteString.copyFromUtf8("value"));
         itm.onChaincodeMessage(chaincodeMessage);
     }
 
@@ -241,7 +242,8 @@ void shutdown() throws IOException {
         final ManagedChannelBuilder managedChannelBuilder = chaincodeBase.newChannelBuilder();
         ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(managedChannelBuilder);
 
-        final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
+        final ChaincodeID chaincodeId =
+                ChaincodeID.newBuilder().setName("chaincodeIdNumber12345").build();
         final InvocationTaskManager itm = InvocationTaskManager.getManager(chaincodeBase, chaincodeId);
         itm.shutdown();
     }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationStubImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationStubImplTest.java
index 8d2b4720f..63aa35f01 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationStubImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationStubImplTest.java
@@ -15,7 +15,6 @@
 
 import com.google.protobuf.ByteString;
 import com.google.protobuf.InvalidProtocolBufferException;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.GetStateByRange;
 import org.hyperledger.fabric.protos.peer.QueryResponse;
@@ -26,23 +25,23 @@
 import org.junit.jupiter.api.Test;
 import org.mockito.ArgumentCaptor;
 
-public class InvocationStubImplTest {
+final class InvocationStubImplTest {
 
     private final String channelId = "mychannel";
     private final String txId = "0xCAFEBABE";
     private final String simpleKeyStartNamespace = new String(Character.toChars(0x000001));
 
     @Nested
-    class GetStateByRangeTests {
+    final class GetStateByRangeTests {
 
         private InvocationStubImpl stubImpl;
         private ArgumentCaptor chaincodeMessageCaptor;
         private ChaincodeInvocationTask mockHandler;
 
         @BeforeEach
-        public void beforeEach() throws Exception {
-            final ChaincodeMessage mockMessage = ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "",
-                    "key");
+        void beforeEach() throws Exception {
+            final ChaincodeMessage mockMessage =
+                    ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", "key");
             mockHandler = mock(ChaincodeInvocationTask.class);
             final ByteString mockString = QueryResponse.newBuilder().build().toByteString();
 
@@ -53,7 +52,7 @@ public void beforeEach() throws Exception {
         }
 
         @Test
-        public void regular() throws InvalidProtocolBufferException {
+        void regular() throws InvalidProtocolBufferException {
             final QueryResultsIterator qri = stubImpl.getStateByRange("Aardvark", "Zebra");
 
             verify(mockHandler).invoke(chaincodeMessageCaptor.capture());
@@ -69,7 +68,7 @@ public void regular() throws InvalidProtocolBufferException {
         }
 
         @Test
-        public void nullvalues() throws InvalidProtocolBufferException {
+        void nullvalues() throws InvalidProtocolBufferException {
             final QueryResultsIterator qri = stubImpl.getStateByRange(null, null);
 
             verify(mockHandler).invoke(chaincodeMessageCaptor.capture());
@@ -86,7 +85,7 @@ public void nullvalues() throws InvalidProtocolBufferException {
         }
 
         @Test
-        public void unbounded() throws InvalidProtocolBufferException {
+        void unbounded() throws InvalidProtocolBufferException {
             final QueryResultsIterator qri = stubImpl.getStateByRange("", "");
 
             verify(mockHandler).invoke(chaincodeMessageCaptor.capture());
@@ -103,14 +102,12 @@ public void unbounded() throws InvalidProtocolBufferException {
         }
 
         @Test
-        public void simplekeys() {
+        void simplekeys() {
             assertThatThrownBy(() -> {
-                final QueryResultsIterator qri = stubImpl
-                        .getStateByRange(new String(Character.toChars(Character.MIN_CODE_POINT)), "");
-            }).hasMessageContaining("not allowed");
-
+                        final QueryResultsIterator qri =
+                                stubImpl.getStateByRange(new String(Character.toChars(Character.MIN_CODE_POINT)), "");
+                    })
+                    .hasMessageContaining("not allowed");
         }
-
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationTaskManagerTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationTaskManagerTest.java
index ae4ee29ab..a7299c535 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationTaskManagerTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/InvocationTaskManagerTest.java
@@ -5,7 +5,14 @@
  */
 package org.hyperledger.fabric.shim.impl;
 
+import static org.mockito.Mockito.when;
+
 import com.google.protobuf.ByteString;
+import java.io.UnsupportedEncodingException;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.Logger;
 import org.hyperledger.fabric.metrics.Metrics;
 import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
@@ -16,22 +23,14 @@
 import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 
-import java.io.UnsupportedEncodingException;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.LogManager;
-import java.util.logging.Logger;
-
-import static org.mockito.Mockito.when;
-
-public final class InvocationTaskManagerTest {
+final class InvocationTaskManagerTest {
 
     private InvocationTaskManager itm;
     private ChaincodeBase chaincode;
     private Logger perfLogger;
 
     @BeforeEach
-    public void setup() {
+    void setup() {
         Metrics.initialize(new Properties());
         Traces.initialize(new Properties());
 
@@ -42,70 +41,65 @@ public void setup() {
 
         perfLogger = LogManager.getLogManager().getLogger("org.hyperledger.Performance");
         perfLogger.setLevel(Level.ALL);
-        this.itm.setResponseConsumer((value) -> {
-        });
+        this.itm.setResponseConsumer((value) -> {});
     }
 
     @AfterEach
-    public void teardown() {
+    void teardown() {
 
         itm.shutdown();
         perfLogger.setLevel(Level.INFO);
     }
 
     @Test
-    public void register() throws UnsupportedEncodingException {
+    void register() throws UnsupportedEncodingException {
         itm.register();
     }
 
     @Test
-    public void onMessageTestTx() throws UnsupportedEncodingException {
+    void onMessageTestTx() throws UnsupportedEncodingException {
 
-        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION,
-                "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
+        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(
+                ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
 
         when(chaincode.getState()).thenReturn(ChaincodeBase.CCState.READY);
 
         itm.onChaincodeMessage(msg);
-
     }
 
     @Test
-    public void onWrongCreatedState() throws UnsupportedEncodingException {
+    void onWrongCreatedState() throws UnsupportedEncodingException {
 
         perfLogger.setLevel(Level.ALL);
-        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION,
-                "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
+        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(
+                ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
 
         when(chaincode.getState()).thenReturn(ChaincodeBase.CCState.CREATED);
 
         itm.onChaincodeMessage(msg);
-
     }
 
     @Test
-    public void onWrongEstablishedState() throws UnsupportedEncodingException {
+    void onWrongEstablishedState() throws UnsupportedEncodingException {
 
-        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION,
-                "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
+        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(
+                ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
 
         when(chaincode.getState()).thenReturn(ChaincodeBase.CCState.ESTABLISHED);
 
         // final InvocationTaskManager itm =
         // InvocationTaskManager.getManager(chaincode, id);
         itm.onChaincodeMessage(msg);
-
     }
 
     @Test
-    public void onErrorResponse() throws UnsupportedEncodingException {
+    void onErrorResponse() throws UnsupportedEncodingException {
 
-        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.ERROR, "mychannel",
-                "txid", ByteString.copyFrom("Hello", "UTF-8"));
+        final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(
+                ChaincodeMessage.Type.ERROR, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8"));
 
         when(chaincode.getState()).thenReturn(ChaincodeBase.CCState.READY);
 
         itm.onChaincodeMessage(msg);
-
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyModificationImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyModificationImplTest.java
index 51fc01930..28527224d 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyModificationImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyModificationImplTest.java
@@ -6,114 +6,107 @@
 
 package org.hyperledger.fabric.shim.impl;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+
 import com.google.protobuf.ByteString;
 import com.google.protobuf.Timestamp;
+import java.util.stream.Stream;
 import org.hyperledger.fabric.shim.ledger.KeyModification;
 import org.junit.jupiter.api.Test;
 
-import java.time.Instant;
-import java.util.stream.Stream;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-public class KeyModificationImplTest {
+final class KeyModificationImplTest {
 
     @Test
-    public void testKeyModificationImpl() {
+    void testKeyModificationImpl() {
         new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
                 .setTxId("txid")
                 .setValue(ByteString.copyFromUtf8("value"))
-                .setTimestamp(Timestamp.newBuilder()
-                        .setSeconds(1234567890)
-                        .setNanos(123456789))
+                .setTimestamp(Timestamp.newBuilder().setSeconds(1234567890).setNanos(123456789))
                 .setIsDelete(true)
                 .build());
     }
 
     @Test
-    public void testGetTxId() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setTxId("txid")
-                .build());
-        assertThat(km.getTxId(), is(equalTo("txid")));
+    void testGetTxId() {
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setTxId("txid")
+                        .build());
+        assertThat(km.getTxId()).isEqualTo("txid");
     }
 
     @Test
-    public void testGetValue() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setValue(ByteString.copyFromUtf8("value"))
-                .build());
-        assertThat(km.getValue(), is(equalTo("value".getBytes(UTF_8))));
+    void testGetValue() {
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setValue(ByteString.copyFromUtf8("value"))
+                        .build());
+        assertThat(km.getValue()).isEqualTo("value".getBytes(UTF_8));
     }
 
     @Test
-    public void testGetStringValue() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setValue(ByteString.copyFromUtf8("value"))
-                .build());
-        assertThat(km.getStringValue(), is(equalTo("value")));
+    void testGetStringValue() {
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setValue(ByteString.copyFromUtf8("value"))
+                        .build());
+        assertThat(km.getStringValue()).isEqualTo("value");
     }
 
     @Test
-    public void testGetTimestamp() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setTimestamp(Timestamp.newBuilder()
-                        .setSeconds(1234567890L)
-                        .setNanos(123456789))
-                .build());
-        assertThat(km.getTimestamp(), hasProperty("epochSecond", equalTo(1234567890L)));
-        assertThat(km.getTimestamp(), hasProperty("nano", equalTo(123456789)));
+    void testGetTimestamp() {
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setTimestamp(
+                                Timestamp.newBuilder().setSeconds(1234567890L).setNanos(123456789))
+                        .build());
+        assertThat(km.getTimestamp().getEpochSecond()).isEqualTo(1234567890L);
+        assertThat(km.getTimestamp().getNano()).isEqualTo(123456789);
     }
 
     @Test
-    public void testIsDeleted() {
-        Stream.of(true, false)
-                .forEach(b -> {
-                    final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+    void testIsDeleted() {
+        Stream.of(true, false).forEach(b -> {
+            final KeyModification km = new KeyModificationImpl(
+                    org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
                             .setIsDelete(b)
                             .build());
-                    assertThat(km.isDeleted(), is(b));
-                });
+            assertThat(km.isDeleted()).isEqualTo(b);
+        });
     }
 
     @Test
-    public void testHashCode() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setIsDelete(false)
-                .build());
-
-        int expectedHashCode = 31;
-        expectedHashCode = expectedHashCode + 1237;
-        expectedHashCode = expectedHashCode * 31 + Instant.EPOCH.hashCode();
-        expectedHashCode = expectedHashCode * 31 + "".hashCode();
-        expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode();
-
-        assertEquals(expectedHashCode, km.hashCode(), "Wrong hash code");
-
+    void testHashCode() {
+        final KeyModification km1 =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(false)
+                        .build());
+        final KeyModification km2 =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(false)
+                        .build());
+
+        assertThat(km1.hashCode()).isEqualTo(km2.hashCode());
     }
 
     @Test
-    public void testEquals() {
-        final KeyModification km1 = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setIsDelete(false)
-                .build());
-        final KeyModification km2 = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setIsDelete(true)
-                .build());
-
-        final KeyModification km3 = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setIsDelete(false)
-                .build());
-
-        assertFalse(km1.equals(km2));
-        assertTrue(km1.equals(km3));
+    void testEquals() {
+        final KeyModification km1 =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(false)
+                        .build());
+        final KeyModification km2 =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(true)
+                        .build());
+
+        final KeyModification km3 =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(false)
+                        .build());
+
+        assertThat(km1).isNotEqualTo(km2);
+        assertThat(km1).isEqualTo(km3);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyValueImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyValueImplTest.java
index 216398d63..219aaf461 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyValueImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/KeyValueImplTest.java
@@ -6,22 +6,17 @@
 
 package org.hyperledger.fabric.shim.impl;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+
 import com.google.protobuf.ByteString;
 import org.hyperledger.fabric.protos.ledger.queryresult.KV;
 import org.junit.jupiter.api.Test;
 
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-public class KeyValueImplTest {
+final class KeyValueImplTest {
 
     @Test
-    public void testKeyValueImpl() {
+    void testKeyValueImpl() {
         new KeyValueImpl(KV.newBuilder()
                 .setKey("key")
                 .setValue(ByteString.copyFromUtf8("value"))
@@ -29,46 +24,42 @@ public void testKeyValueImpl() {
     }
 
     @Test
-    public void testGetKey() {
+    void testGetKey() {
         final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder()
                 .setKey("key")
                 .setValue(ByteString.copyFromUtf8("value"))
                 .build());
-        assertThat(kv.getKey(), is(equalTo("key")));
+        assertThat(kv.getKey()).isEqualTo("key");
     }
 
     @Test
-    public void testGetValue() {
+    void testGetValue() {
         final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder()
                 .setKey("key")
                 .setValue(ByteString.copyFromUtf8("value"))
                 .build());
-        assertThat(kv.getValue(), is(equalTo("value".getBytes(UTF_8))));
+        assertThat(kv.getValue()).isEqualTo("value".getBytes(UTF_8));
     }
 
     @Test
-    public void testGetStringValue() {
+    void testGetStringValue() {
         final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder()
                 .setKey("key")
                 .setValue(ByteString.copyFromUtf8("value"))
                 .build());
-        assertThat(kv.getStringValue(), is(equalTo("value")));
+        assertThat(kv.getStringValue()).isEqualTo("value");
     }
 
     @Test
-    public void testHashCode() {
-        final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder()
-                .build());
-
-        int expectedHashCode = 31;
-        expectedHashCode = expectedHashCode + "".hashCode();
-        expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode();
+    void testHashCode() {
+        final KeyValueImpl kv1 = new KeyValueImpl(KV.newBuilder().build());
+        final KeyValueImpl kv2 = new KeyValueImpl(KV.newBuilder().build());
 
-        assertEquals(expectedHashCode, kv.hashCode(), "Wrong hashcode");
+        assertThat(kv1.hashCode()).isEqualTo(kv2.hashCode());
     }
 
     @Test
-    public void testEquals() {
+    void testEquals() {
         final KeyValueImpl kv1 = new KeyValueImpl(KV.newBuilder()
                 .setKey("a")
                 .setValue(ByteString.copyFromUtf8("valueA"))
@@ -89,10 +80,8 @@ public void testEquals() {
                 .setValue(ByteString.copyFromUtf8("valueA"))
                 .build());
 
-        assertFalse(kv1.equals(kv2));
-        assertFalse(kv1.equals(kv3));
-        assertTrue(kv1.equals(kv4));
-
+        assertThat(kv1).isNotEqualTo(kv2);
+        assertThat(kv1).isNotEqualTo(kv3);
+        assertThat(kv1).isEqualTo(kv4);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImplTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImplTest.java
index 9f312564b..73cc0079b 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImplTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/impl/QueryResultsIteratorWithMetadataImplTest.java
@@ -6,45 +6,34 @@
 
 package org.hyperledger.fabric.shim.impl;
 
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+import com.google.protobuf.ByteString;
 import java.util.function.Function;
-
 import org.hyperledger.fabric.protos.peer.QueryResponse;
-import org.hyperledger.fabric.protos.peer.QueryResultBytes;
 import org.hyperledger.fabric.protos.peer.QueryResponseMetadata;
+import org.hyperledger.fabric.protos.peer.QueryResultBytes;
 import org.junit.jupiter.api.Test;
 
-import com.google.protobuf.ByteString;
-
-public class QueryResultsIteratorWithMetadataImplTest {
+final class QueryResultsIteratorWithMetadataImplTest {
+    private static final Function QUERY_RESULT_BYTES_TO_KV = queryResultBytes -> 0;
 
     @Test
-    public void getMetadata() {
-        final QueryResultsIteratorWithMetadataImpl testIter = new QueryResultsIteratorWithMetadataImpl<>(null, "", "",
-                prepareQueryResponse().toByteString(), queryResultBytesToKv);
-        assertThat(testIter.getMetadata().getBookmark(), is("asdf"));
-        assertThat(testIter.getMetadata().getFetchedRecordsCount(), is(2));
+    void getMetadata() {
+        final QueryResultsIteratorWithMetadataImpl testIter = new QueryResultsIteratorWithMetadataImpl<>(
+                null, "", "", prepareQueryResponse().toByteString(), QUERY_RESULT_BYTES_TO_KV);
+        assertThat(testIter.getMetadata().getBookmark()).isEqualTo("asdf");
+        assertThat(testIter.getMetadata().getFetchedRecordsCount()).isEqualTo(2);
     }
 
     @Test
-    public void getInvalidMetadata() {
-        try {
-            new QueryResultsIteratorWithMetadataImpl<>(null, "", "", prepareQueryResponseWrongMeta().toByteString(), queryResultBytesToKv);
-            fail();
-        } catch (final RuntimeException e) {
-        }
+    void getInvalidMetadata() {
+        assertThatThrownBy(() -> new QueryResultsIteratorWithMetadataImpl<>(
+                        null, "", "", prepareQueryResponseWrongMeta().toByteString(), QUERY_RESULT_BYTES_TO_KV))
+                .isInstanceOf(RuntimeException.class);
     }
 
-    private final Function queryResultBytesToKv = new Function() {
-        @Override
-        public Integer apply(final QueryResultBytes queryResultBytes) {
-            return 0;
-        }
-    };
-
     private QueryResponse prepareQueryResponse() {
         final QueryResponseMetadata qrm = QueryResponseMetadata.newBuilder()
                 .setBookmark("asdf")
@@ -55,16 +44,11 @@ private QueryResponse prepareQueryResponse() {
                 .setHasMore(false)
                 .setMetadata(qrm.toByteString())
                 .build();
-
     }
 
     private QueryResponse prepareQueryResponseWrongMeta() {
         final ByteString bs = ByteString.copyFrom(new byte[] {0, 0});
 
-        return QueryResponse.newBuilder()
-                .setHasMore(false)
-                .setMetadata(bs)
-                .build();
-
+        return QueryResponse.newBuilder().setHasMore(false).setMetadata(bs).build();
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ledger/CompositeKeyTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ledger/CompositeKeyTest.java
index 2fce7d4f7..21293a01a 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ledger/CompositeKeyTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/ledger/CompositeKeyTest.java
@@ -6,10 +6,6 @@
 
 package org.hyperledger.fabric.shim.ledger;
 
-import org.junit.jupiter.api.Test;
-
-import java.util.Arrays;
-
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.contains;
@@ -17,20 +13,23 @@
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.is;
 
-public class CompositeKeyTest {
+import java.util.Arrays;
+import org.junit.jupiter.api.Test;
+
+final class CompositeKeyTest {
     @Test
-    public void testValidateSimpleKeys() {
+    void testValidateSimpleKeys() {
         CompositeKey.validateSimpleKeys("abc", "def", "ghi");
     }
 
     @Test
-    public void testValidateSimpleKeysException() {
+    void testValidateSimpleKeysException() {
         assertThatThrownBy(() -> CompositeKey.validateSimpleKeys("\u0000abc"))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testCompositeKeyStringStringArray() {
+    void testCompositeKeyStringStringArray() {
         final CompositeKey key = new CompositeKey("abc", "def", "ghi", "jkl", "mno");
         assertThat(key.getObjectType(), is(equalTo("abc")));
         assertThat(key.getAttributes(), hasSize(4));
@@ -38,7 +37,7 @@ public void testCompositeKeyStringStringArray() {
     }
 
     @Test
-    public void testCompositeKeyStringListOfString() {
+    void testCompositeKeyStringListOfString() {
         final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno"));
         assertThat(key.getObjectType(), is(equalTo("abc")));
         assertThat(key.getAttributes(), hasSize(4));
@@ -46,7 +45,7 @@ public void testCompositeKeyStringListOfString() {
     }
 
     @Test
-    public void testEmptyAttributes() {
+    void testEmptyAttributes() {
         final CompositeKey key = new CompositeKey("abc");
         assertThat(key.getObjectType(), is(equalTo("abc")));
         assertThat(key.getAttributes(), hasSize(0));
@@ -54,37 +53,37 @@ public void testEmptyAttributes() {
     }
 
     @Test
-    public void testCompositeKeyWithInvalidObjectTypeDelimiter() {
+    void testCompositeKeyWithInvalidObjectTypeDelimiter() {
         assertThatThrownBy(() -> new CompositeKey("ab\u0000c", Arrays.asList("def", "ghi", "jkl", "mno")))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testCompositeKeyWithInvalidAttributeDelimiter() {
+    void testCompositeKeyWithInvalidAttributeDelimiter() {
         assertThatThrownBy(() -> new CompositeKey("abc", Arrays.asList("def", "ghi", "j\u0000kl", "mno")))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testCompositeKeyWithInvalidObjectTypeMaxCodePoint() {
+    void testCompositeKeyWithInvalidObjectTypeMaxCodePoint() {
         assertThatThrownBy(() -> new CompositeKey("ab\udbff\udfffc", Arrays.asList("def", "ghi", "jkl", "mno")))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testCompositeKeyWithInvalidAttributeMaxCodePoint() {
+    void testCompositeKeyWithInvalidAttributeMaxCodePoint() {
         assertThatThrownBy(() -> new CompositeKey("abc", Arrays.asList("def", "ghi", "jk\udbff\udfffl", "mno")))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testGetObjectType() {
+    void testGetObjectType() {
         final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno"));
         assertThat(key.getObjectType(), is(equalTo("abc")));
     }
 
     @Test
-    public void testGetAttributes() {
+    void testGetAttributes() {
         final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno"));
         assertThat(key.getObjectType(), is(equalTo("abc")));
         assertThat(key.getAttributes(), hasSize(4));
@@ -92,13 +91,13 @@ public void testGetAttributes() {
     }
 
     @Test
-    public void testToString() {
+    void testToString() {
         final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno"));
         assertThat(key.toString(), is(equalTo("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000")));
     }
 
     @Test
-    public void testParseCompositeKey() {
+    void testParseCompositeKey() {
         final CompositeKey key = CompositeKey.parseCompositeKey("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000");
         assertThat(key.getObjectType(), is(equalTo("abc")));
         assertThat(key.getAttributes(), hasSize(4));
@@ -107,15 +106,16 @@ public void testParseCompositeKey() {
     }
 
     @Test
-    public void testParseCompositeKeyInvalidObjectType() {
-        assertThatThrownBy(() -> CompositeKey.parseCompositeKey("ab\udbff\udfffc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))
+    void testParseCompositeKeyInvalidObjectType() {
+        assertThatThrownBy(() ->
+                        CompositeKey.parseCompositeKey("ab\udbff\udfffc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
 
     @Test
-    public void testParseCompositeKeyInvalidAttribute() {
-        assertThatThrownBy(() -> CompositeKey.parseCompositeKey("abc\u0000def\u0000ghi\u0000jk\udbff\udfffl\u0000mno\u0000"))
+    void testParseCompositeKeyInvalidAttribute() {
+        assertThatThrownBy(() ->
+                        CompositeKey.parseCompositeKey("abc\u0000def\u0000ghi\u0000jk\udbff\udfffl\u0000mno\u0000"))
                 .isInstanceOf(CompositeKeyFormatException.class);
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ChaincodeMockPeer.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ChaincodeMockPeer.java
index badf8ca62..cf89c8886 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ChaincodeMockPeer.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ChaincodeMockPeer.java
@@ -6,27 +6,23 @@
 
 package org.hyperledger.fabric.shim.mock.peer;
 
+import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.PUT_STATE;
+
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+import io.grpc.stub.StreamObserver;
 import java.io.IOException;
-import java.util.List;
 import java.util.ArrayList;
+import java.util.List;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.ReentrantLock;
 import java.util.logging.Logger;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc;
 import org.hyperledger.fabric.shim.utils.TimeoutUtil;
 
-import io.grpc.Server;
-import io.grpc.ServerBuilder;
-import io.grpc.stub.StreamObserver;
-import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.PUT_STATE;
-
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * Mock peer implementation
- */
+/** Mock peer implementation */
 public final class ChaincodeMockPeer {
     private static final Logger LOGGER = Logger.getLogger(ChaincodeMockPeer.class.getName());
 
@@ -38,7 +34,7 @@ public final class ChaincodeMockPeer {
      * Constructor
      *
      * @param scenario list of scenario steps
-     * @param port     mock peer communication port
+     * @param port mock peer communication port
      * @throws IOException
      */
     public ChaincodeMockPeer(final List scenario, final int port) {
@@ -48,16 +44,15 @@ public ChaincodeMockPeer(final List scenario, final int port) {
         this.server = sb.addService(this.service).build();
     }
 
-    /**
-     * Start serving requests.
-     */
+    /** Start serving requests. */
+    @SuppressWarnings("PMD.SystemPrintln")
     public void start() throws IOException {
         server.start();
-        LOGGER.info("Server started, listening on " + port);
+        LOGGER.info(() -> "Server started, listening on " + port);
         Runtime.getRuntime().addShutdownHook(new Thread() {
             @Override
             public void run() {
-                // Use stderr here since the logger may has been reset by its JVM shutdown hook.
+                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                 System.err.println("*** shutting down gRPC server since JVM is shutting down");
                 ChaincodeMockPeer.this.stop();
                 System.err.println("*** server shut down");
@@ -65,15 +60,13 @@ public void run() {
         });
     }
 
-    /**
-     * Stop serving requests and shutdown resources.
-     */
+    /** Stop serving requests and shutdown resources. */
     public void stop() {
         if (server != null) {
             server.shutdownNow();
             try {
                 server.awaitTermination();
-            } catch (final InterruptedException e) {
+            } catch (final InterruptedException ignored) {
             }
         }
     }
@@ -86,7 +79,7 @@ public void stop() {
     public void send(final ChaincodeMessage msg) {
         this.service.lastMessageSend = msg;
 
-        LOGGER.info("Mock peer => Sending message: " + msg);
+        LOGGER.info(() -> "Mock peer => Sending message: " + msg);
         this.service.send(msg);
     }
 
@@ -99,21 +92,16 @@ public int getLastExecutedStep() {
         return this.service.lastExecutedStepNumber;
     }
 
-    /**
-     * @return last received message from chaincode
-     */
+    /** @return last received message from chaincode */
     public ChaincodeMessage getLastMessageRcvd() {
         return this.service.lastMessageRcvd;
-
     }
 
-    public ArrayList getAllReceivedMessages() {
+    public List getAllReceivedMessages() {
         return this.service.allMessages;
     }
 
-    /**
-     * @return last message sent by peer to chaincode
-     */
+    /** @return last message sent by peer to chaincode */
     public ChaincodeMessage getLastMessageSend() {
         return this.service.lastMessageSend;
     }
@@ -136,7 +124,7 @@ private static class ChaincodeMockPeerService extends ChaincodeSupportGrpc.Chain
         private int lastExecutedStepNumber;
         private ChaincodeMessage lastMessageRcvd;
         private ChaincodeMessage lastMessageSend;
-        private final ArrayList allMessages = new ArrayList<>();
+        private final List allMessages = new ArrayList<>();
         private StreamObserver observer;
 
         // create a lock, with fair property
@@ -161,10 +149,9 @@ public void send(final ChaincodeMessage msg) {
          * @return
          */
         @Override
-        public StreamObserver register(
-                final StreamObserver responseObserver) {
+        public StreamObserver register(final StreamObserver responseObserver) {
             observer = responseObserver;
-            return new StreamObserver() {
+            return new StreamObserver<>() {
 
                 /**
                  * Handling incoming messages
@@ -172,15 +159,17 @@ public StreamObserver register(
                  * @param chaincodeMessage
                  */
                 @Override
+                @SuppressWarnings("PMD.AvoidCatchingThrowable")
                 public void onNext(final ChaincodeMessage chaincodeMessage) {
                     try {
-                        LOGGER.info("Mock peer => Got message: " + chaincodeMessage);
+                        LOGGER.info(() -> "Mock peer => Got message: " + chaincodeMessage);
                         ChaincodeMockPeerService.this.lastMessageRcvd = chaincodeMessage;
                         ChaincodeMockPeerService.this.allMessages.add(chaincodeMessage);
                         if (chaincodeMessage.getType().equals(PUT_STATE)) {
                             final ChaincodeMessage m = ChaincodeMessage.newBuilder()
                                     .setType(ChaincodeMessage.Type.RESPONSE)
-                                    .setChannelId(chaincodeMessage.getChannelId()).setTxid(chaincodeMessage.getTxid())
+                                    .setChannelId(chaincodeMessage.getChannelId())
+                                    .setTxid(chaincodeMessage.getTxid())
                                     .build();
                             Thread.sleep(500);
                             ChaincodeMockPeerService.this.send(m);
@@ -191,11 +180,12 @@ public void onNext(final ChaincodeMessage chaincodeMessage) {
                                 final List nextSteps = step.next();
                                 for (final ChaincodeMessage m : nextSteps) {
                                     ChaincodeMockPeerService.this.lastMessageSend = m;
-                                    LOGGER.info("Mock peer => Sending response message: " + m);
+                                    LOGGER.info(() -> "Mock peer => Sending response message: " + m);
                                     ChaincodeMockPeerService.this.send(m);
                                 }
                             } else {
-                                LOGGER.warning("Non expected message rcvd in step " + step.getClass().getSimpleName());
+                                LOGGER.warning(() -> "Non expected message rcvd in step "
+                                        + step.getClass().getSimpleName());
                             }
                             ChaincodeMockPeerService.this.lastExecutedStepNumber++;
                         }
@@ -206,34 +196,35 @@ public void onNext(final ChaincodeMessage chaincodeMessage) {
 
                 @Override
                 public void onError(final Throwable throwable) {
-                    System.out.println(throwable);
+                    throwable.printStackTrace();
                 }
 
                 @Override
-                public void onCompleted() {
-
-                }
+                public void onCompleted() {}
             };
         }
     }
 
-    public static void checkScenarioStepEnded(final ChaincodeMockPeer s, final int step, final int timeout,
-            final TimeUnit units) throws Exception {
+    @SuppressWarnings("PMD.SystemPrintln")
+    public static void checkScenarioStepEnded(
+            final ChaincodeMockPeer s, final int step, final int timeout, final TimeUnit units) throws Exception {
         try {
-            TimeoutUtil.runWithTimeout(new Thread(() -> {
-                while (true) {
-                    if (s.getLastExecutedStep() == step) {
-                        return;
-                    }
-                    try {
-                        Thread.sleep(500);
-                    } catch (final InterruptedException e) {
-                    }
-                }
-            }), timeout, units);
+            TimeoutUtil.runWithTimeout(
+                    new Thread(() -> {
+                        while (true) {
+                            if (s.getLastExecutedStep() == step) {
+                                return;
+                            }
+                            try {
+                                Thread.sleep(500);
+                            } catch (final InterruptedException ignored) {
+                            }
+                        }
+                    }),
+                    timeout,
+                    units);
         } catch (final TimeoutException e) {
             System.out.println("Got timeout, step " + step + " not finished");
         }
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/CompleteStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/CompleteStep.java
index 625de5873..34ea010b9 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/CompleteStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/CompleteStep.java
@@ -8,12 +8,9 @@
 
 import java.util.Collections;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
-/**
- * Waits for COMPLETED message, sends nothing back
- */
+/** Waits for COMPLETED message, sends nothing back */
 public final class CompleteStep implements ScenarioStep {
     @Override
     public boolean expected(final ChaincodeMessage msg) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/DelValueStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/DelValueStep.java
index 95b31012e..37ef42b05 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/DelValueStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/DelValueStep.java
@@ -7,12 +7,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates delState() invocation in chaincode Waits for DEL_STATE message from
- * chaincode and sends back response with empty payload
+ * Simulates delState() invocation in chaincode Waits for DEL_STATE message from chaincode and sends back response with
+ * empty payload
  */
 public final class DelValueStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ErrorResponseStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ErrorResponseStep.java
index fae2dd601..96e63c7a5 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ErrorResponseStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ErrorResponseStep.java
@@ -7,12 +7,9 @@
 
 import java.util.Collections;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
-/**
- * Error message from chaincode side, no response sent
- */
+/** Error message from chaincode side, no response sent */
 public final class ErrorResponseStep implements ScenarioStep {
     @Override
     public boolean expected(final ChaincodeMessage msg) {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetHistoryForKeyStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetHistoryForKeyStep.java
index 813732ee6..c307d6ae8 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetHistoryForKeyStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetHistoryForKeyStep.java
@@ -7,16 +7,14 @@
 
 import static java.util.stream.Collectors.toList;
 
+import com.google.protobuf.ByteString;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.ledger.queryresult.KeyModification;
+import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.QueryResponse;
 import org.hyperledger.fabric.protos.peer.QueryResultBytes;
-import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
-
-import com.google.protobuf.ByteString;
 
 public final class GetHistoryForKeyStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
@@ -27,10 +25,10 @@ public final class GetHistoryForKeyStep implements ScenarioStep {
      * Initiate step
      *
      * @param hasNext is response message QueryResponse hasMore field set
-     * @param vals    list of keys to generate ("key" => "key Value") pairs
+     * @param vals list of keys to generate ("key" => "key Value") pairs
      */
     public GetHistoryForKeyStep(final boolean hasNext, final String... vals) {
-        this.values = vals;
+        this.values = Arrays.copyOf(vals, vals.length);
         this.hasNext = hasNext;
     }
 
@@ -42,14 +40,17 @@ public boolean expected(final ChaincodeMessage msg) {
 
     @Override
     public List next() {
-        final List keyModifications = Arrays.asList(values).stream().map(x -> KeyModification.newBuilder()
-                .setTxId(x)
-                .setValue(ByteString.copyFromUtf8(x + " Value"))
-                .build()).collect(toList());
+        final List keyModifications = Arrays.asList(values).stream()
+                .map(x -> KeyModification.newBuilder()
+                        .setTxId(x)
+                        .setValue(ByteString.copyFromUtf8(x + " Value"))
+                        .build())
+                .collect(toList());
 
         final QueryResponse.Builder builder = QueryResponse.newBuilder();
         builder.setHasMore(hasNext);
-        keyModifications.stream().forEach(kv -> builder.addResults(QueryResultBytes.newBuilder().setResultBytes(kv.toByteString())));
+        keyModifications.stream()
+                .forEach(kv -> builder.addResults(QueryResultBytes.newBuilder().setResultBytes(kv.toByteString())));
         final ByteString historyPayload = builder.build().toByteString();
 
         final List list = new ArrayList<>();
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetQueryResultStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetQueryResultStep.java
index 00207270a..2c137d932 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetQueryResultStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetQueryResultStep.java
@@ -8,8 +8,8 @@
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates query invocation. Waits for GET_QUERY_RESULT Returns message that
- * contains list of results in form ("key" => "key Value")*
+ * Simulates query invocation. Waits for GET_QUERY_RESULT Returns message that contains list of results in form ("key"
+ * => "key Value")*
  */
 public final class GetQueryResultStep extends QueryResultStep {
 
@@ -17,7 +17,7 @@ public final class GetQueryResultStep extends QueryResultStep {
      * Initiate step
      *
      * @param hasNext is response message QueryResponse hasMore field set
-     * @param vals    list of keys to generate ("key" => "key Value") pairs
+     * @param vals list of keys to generate ("key" => "key Value") pairs
      */
     public GetQueryResultStep(final boolean hasNext, final String... vals) {
         super(hasNext, vals);
@@ -28,5 +28,4 @@ public boolean expected(final ChaincodeMessage msg) {
         super.orgMsg = msg;
         return msg.getType() == ChaincodeMessage.Type.GET_QUERY_RESULT;
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateByRangeStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateByRangeStep.java
index fc87811df..0acebac6a 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateByRangeStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateByRangeStep.java
@@ -8,8 +8,8 @@
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates getStateByRange Waits for GET_STATE_BY_RANGE message Returns
- * message that contains list of results in form ("key" => "key Value")*
+ * Simulates getStateByRange Waits for GET_STATE_BY_RANGE message Returns message that contains list of results in form
+ * ("key" => "key Value")*
  */
 public final class GetStateByRangeStep extends QueryResultStep {
 
@@ -17,7 +17,7 @@ public final class GetStateByRangeStep extends QueryResultStep {
      * Initiate step
      *
      * @param hasNext is response message QueryResponse hasMore field set
-     * @param vals    list of keys to generate ("key" => "key Value") pairs
+     * @param vals list of keys to generate ("key" => "key Value") pairs
      */
     public GetStateByRangeStep(final boolean hasNext, final String... vals) {
         super(hasNext, vals);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateMetadata.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateMetadata.java
index 6d085fe5e..8419ee2db 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateMetadata.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetStateMetadata.java
@@ -5,28 +5,23 @@
  */
 package org.hyperledger.fabric.shim.mock.peer;
 
+import com.google.protobuf.ByteString;
 import java.util.ArrayList;
 import java.util.List;
-
-import org.hyperledger.fabric.protos.peer.StateMetadata;
-import org.hyperledger.fabric.protos.peer.StateMetadataResult;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.MetaDataKeys;
+import org.hyperledger.fabric.protos.peer.StateMetadata;
+import org.hyperledger.fabric.protos.peer.StateMetadataResult;
 import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
 
-import com.google.protobuf.ByteString;
-
 /**
- * simulates Handler.getStateMetadata Waits for GET_STATE_METADATA message
- * Returns response message with stored metadata
+ * simulates Handler.getStateMetadata Waits for GET_STATE_METADATA message Returns response message with stored metadata
  */
 public final class GetStateMetadata implements ScenarioStep {
     private ChaincodeMessage orgMsg;
     private final byte[] val;
 
-    /**
-     * @param sbe StateBasedEndorsement to return as one and only one metadata entry
-     */
+    /** @param sbe StateBasedEndorsement to return as one and only one metadata entry */
     public GetStateMetadata(final StateBasedEndorsement sbe) {
         val = sbe.policy();
     }
@@ -45,9 +40,8 @@ public List next() {
                 .setValue(ByteString.copyFrom(val))
                 .build();
         entriesList.add(validationValue);
-        final StateMetadataResult stateMetadataResult = StateMetadataResult.newBuilder()
-                .addAllEntries(entriesList)
-                .build();
+        final StateMetadataResult stateMetadataResult =
+                StateMetadataResult.newBuilder().addAllEntries(entriesList).build();
         final List list = new ArrayList<>();
         list.add(ChaincodeMessage.newBuilder()
                 .setType(ChaincodeMessage.Type.RESPONSE)
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetValueStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetValueStep.java
index 670701967..6bac3ac3b 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetValueStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/GetValueStep.java
@@ -5,25 +5,17 @@
  */
 package org.hyperledger.fabric.shim.mock.peer;
 
+import com.google.protobuf.ByteString;
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
-import com.google.protobuf.ByteString;
-
-/**
- * Simulates getState Waits for GET_STATE message Returns response message with
- * value as payload
- */
+/** Simulates getState Waits for GET_STATE message Returns response message with value as payload */
 public final class GetValueStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
     private final String val;
 
-    /**
-     *
-     * @param val value to return
-     */
+    /** @param val value to return */
     public GetValueStep(final String val) {
         this.val = val;
     }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/InvokeChaincodeStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/InvokeChaincodeStep.java
index 9ca3b5472..dceae3b39 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/InvokeChaincodeStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/InvokeChaincodeStep.java
@@ -5,18 +5,16 @@
  */
 package org.hyperledger.fabric.shim.mock.peer;
 
+import com.google.protobuf.ByteString;
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.Response;
 import org.hyperledger.fabric.shim.Chaincode;
 
-import com.google.protobuf.ByteString;
-
 /**
- * Simulates another chaincode invocation Waits for INVOKE_CHAINCODE Sends back
- * RESPONSE message with chaincode response inside
+ * Simulates another chaincode invocation Waits for INVOKE_CHAINCODE Sends back RESPONSE message with chaincode response
+ * inside
  */
 public final class InvokeChaincodeStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
@@ -28,22 +26,22 @@ public boolean expected(final ChaincodeMessage msg) {
     }
 
     /**
-     *
-     * @return Chaincode response packed as payload inside COMPLETE message packed
-     *         as payload inside RESPONSE message
+     * @return Chaincode response packed as payload inside COMPLETE message packed as payload inside RESPONSE message
      */
     @Override
     public List next() {
         final ByteString chaincodeResponse = Response.newBuilder()
                 .setStatus(Chaincode.Response.Status.SUCCESS.getCode())
                 .setMessage("OK")
-                .build().toByteString();
+                .build()
+                .toByteString();
         final ByteString completePayload = ChaincodeMessage.newBuilder()
                 .setType(ChaincodeMessage.Type.COMPLETED)
                 .setChannelId(orgMsg.getChannelId())
                 .setTxid(orgMsg.getTxid())
                 .setPayload(chaincodeResponse)
-                .build().toByteString();
+                .build()
+                .toByteString();
         final List list = new ArrayList<>();
         list.add(ChaincodeMessage.newBuilder()
                 .setType(ChaincodeMessage.Type.RESPONSE)
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PurgeValueStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PurgeValueStep.java
index b048295d0..e6eed0420 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PurgeValueStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PurgeValueStep.java
@@ -7,12 +7,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates purgePrivateData() invocation in chaincode Waits for PURGE_PRIVATE_DATA message from
- * chaincode and sends back response with empty payload
+ * Simulates purgePrivateData() invocation in chaincode Waits for PURGE_PRIVATE_DATA message from chaincode and sends
+ * back response with empty payload
  */
 public final class PurgeValueStep implements ScenarioStep {
 
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutStateMetadata.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutStateMetadata.java
index 156f73532..95d80e03a 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutStateMetadata.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutStateMetadata.java
@@ -5,20 +5,17 @@
  */
 package org.hyperledger.fabric.shim.mock.peer;
 
+import com.google.protobuf.InvalidProtocolBufferException;
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.MetaDataKeys;
 import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
 import org.hyperledger.fabric.shim.ext.sbe.impl.StateBasedEndorsementFactory;
 
-import com.google.protobuf.InvalidProtocolBufferException;
-
 /**
- * * Simulates Handler.putStateMetadata() invocation from chaincode side * Waits
- * for PUT_STATE_METADATA message from chaincode, including metadata entry with
- * validation metadata and sends back response with empty payload
+ * * Simulates Handler.putStateMetadata() invocation from chaincode side * Waits for PUT_STATE_METADATA message from
+ * chaincode, including metadata entry with validation metadata and sends back response with empty payload
  */
 public final class PutStateMetadata implements ScenarioStep {
     private ChaincodeMessage orgMsg;
@@ -29,8 +26,7 @@ public PutStateMetadata(final StateBasedEndorsement sbe) {
     }
 
     /**
-     * Check incoming message If message type is PUT_STATE_METADATA and payload
-     * match to passed in constructor
+     * Check incoming message If message type is PUT_STATE_METADATA and payload match to passed in constructor
      *
      * @param msg message from chaincode
      * @return
@@ -44,9 +40,12 @@ public boolean expected(final ChaincodeMessage msg) {
         } catch (final InvalidProtocolBufferException e) {
             return false;
         }
-        final StateBasedEndorsement msgSbe = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(psm.getMetadata().getValue().toByteArray());
+        final StateBasedEndorsement msgSbe = StateBasedEndorsementFactory.getInstance()
+                .newStateBasedEndorsement(psm.getMetadata().getValue().toByteArray());
         return msg.getType() == ChaincodeMessage.Type.PUT_STATE_METADATA
-                && MetaDataKeys.VALIDATION_PARAMETER.toString().equals(psm.getMetadata().getMetakey())
+                && MetaDataKeys.VALIDATION_PARAMETER
+                        .toString()
+                        .equals(psm.getMetadata().getMetakey())
                 && (msgSbe.listOrgs().size() == val.listOrgs().size());
     }
 
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutValueStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutValueStep.java
index 6dc16d47f..b96e7425e 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutValueStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/PutValueStep.java
@@ -6,18 +6,16 @@
 
 package org.hyperledger.fabric.shim.mock.peer;
 
+import com.google.protobuf.InvalidProtocolBufferException;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.List;
-
-import org.hyperledger.fabric.protos.peer.PutState;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
-
-import com.google.protobuf.InvalidProtocolBufferException;
+import org.hyperledger.fabric.protos.peer.PutState;
 
 /**
- * Simulates putState() invocation in chaincode Waits for PUT_STATE message from
- * chaincode, including value and sends back response with empty payload
+ * Simulates putState() invocation in chaincode Waits for PUT_STATE message from chaincode, including value and sends
+ * back response with empty payload
  */
 public final class PutValueStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
@@ -33,8 +31,7 @@ public PutValueStep(final String val) {
     }
 
     /**
-     * Check incoming message If message type is PUT_STATE and payload equal to
-     * passed in constructor
+     * Check incoming message If message type is PUT_STATE and payload equal to passed in constructor
      *
      * @param msg message from chaincode
      * @return
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryCloseStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryCloseStep.java
index e282b23d0..501ed1ce9 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryCloseStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryCloseStep.java
@@ -7,12 +7,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulate last query (close) step. Happens after passing over all query result
- * Waits for QUERY_STATE_CLOSE Sends back response with empty payload
+ * Simulate last query (close) step. Happens after passing over all query result Waits for QUERY_STATE_CLOSE Sends back
+ * response with empty payload
  */
 public final class QueryCloseStep implements ScenarioStep {
     private ChaincodeMessage orgMsg;
@@ -23,10 +22,7 @@ public boolean expected(final ChaincodeMessage msg) {
         return msg.getType() == ChaincodeMessage.Type.QUERY_STATE_CLOSE;
     }
 
-    /**
-     *
-     * @return RESPONSE message with empty payload
-     */
+    /** @return RESPONSE message with empty payload */
     @Override
     public List next() {
         final List list = new ArrayList<>();
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryNextStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryNextStep.java
index fced5b3eb..331b15e3c 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryNextStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryNextStep.java
@@ -8,9 +8,8 @@
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates requesting/receiving next set of results for query Waits for
- * QUERY_STATE_NEXT Returns message that contains list of results in form ("key"
- * => "key Value")*
+ * Simulates requesting/receiving next set of results for query Waits for QUERY_STATE_NEXT Returns message that contains
+ * list of results in form ("key" => "key Value")*
  */
 public final class QueryNextStep extends QueryResultStep {
 
@@ -18,7 +17,7 @@ public final class QueryNextStep extends QueryResultStep {
      * Initiate step
      *
      * @param hasNext is response message QueryResponse hasMore field set
-     * @param vals    list of keys to generate ("key" => "key Value") pairs
+     * @param vals list of keys to generate ("key" => "key Value") pairs
      */
     public QueryNextStep(final boolean hasNext, final String... vals) {
         super(hasNext, vals);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryResultStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryResultStep.java
index cab82313c..697127199 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryResultStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/QueryResultStep.java
@@ -7,20 +7,16 @@
 
 import static java.util.stream.Collectors.toList;
 
+import com.google.protobuf.ByteString;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.ledger.queryresult.KV;
-import org.hyperledger.fabric.protos.peer.QueryResultBytes;
-import org.hyperledger.fabric.protos.peer.QueryResponse;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
+import org.hyperledger.fabric.protos.peer.QueryResponse;
+import org.hyperledger.fabric.protos.peer.QueryResultBytes;
 
-import com.google.protobuf.ByteString;
-
-/**
- * Base class for multi result query steps/messages
- */
+/** Base class for multi result query steps/messages */
 public abstract class QueryResultStep implements ScenarioStep {
     protected ChaincodeMessage orgMsg;
     protected final String[] values;
@@ -30,10 +26,10 @@ public abstract class QueryResultStep implements ScenarioStep {
      * Initiate step
      *
      * @param hasNext is response message QueryResponse hasMore field set
-     * @param vals    list of keys to generate ("key" => "key Value") pairs
+     * @param vals list of keys to generate ("key" => "key Value") pairs
      */
     QueryResultStep(final boolean hasNext, final String... vals) {
-        this.values = vals;
+        this.values = Arrays.copyOf(vals, vals.length);
         this.hasNext = hasNext;
     }
 
@@ -44,14 +40,17 @@ public abstract class QueryResultStep implements ScenarioStep {
      */
     @Override
     public List next() {
-        final List keyValues = Arrays.asList(values).stream().map(x -> KV.newBuilder()
-                .setKey(x)
-                .setValue(ByteString.copyFromUtf8(x + " Value"))
-                .build()).collect(toList());
+        final List keyValues = Arrays.asList(values).stream()
+                .map(x -> KV.newBuilder()
+                        .setKey(x)
+                        .setValue(ByteString.copyFromUtf8(x + " Value"))
+                        .build())
+                .collect(toList());
 
         final QueryResponse.Builder builder = QueryResponse.newBuilder();
         builder.setHasMore(hasNext);
-        keyValues.stream().forEach(kv -> builder.addResults(QueryResultBytes.newBuilder().setResultBytes(kv.toByteString())));
+        keyValues.stream()
+                .forEach(kv -> builder.addResults(QueryResultBytes.newBuilder().setResultBytes(kv.toByteString())));
         final ByteString rangePayload = builder.build().toByteString();
 
         final List list = new ArrayList<>();
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/RegisterStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/RegisterStep.java
index 81f823bd0..25c66c424 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/RegisterStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/RegisterStep.java
@@ -8,12 +8,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 /**
- * Simulates chaincode registration after start Waits for REGISTER message from
- * chaincode Sends back pair of messages: REGISTERED and READY
+ * Simulates chaincode registration after start Waits for REGISTER message from chaincode Sends back pair of messages:
+ * REGISTERED and READY
  */
 public final class RegisterStep implements ScenarioStep {
 
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ScenarioStep.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ScenarioStep.java
index f913ea6c0..d219b4058 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ScenarioStep.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/mock/peer/ScenarioStep.java
@@ -7,7 +7,6 @@
 package org.hyperledger.fabric.shim.mock.peer;
 
 import java.util.List;
-
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
 public interface ScenarioStep {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/MessageUtil.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/MessageUtil.java
index dc0f4fa09..b6ab6a5cb 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/MessageUtil.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/MessageUtil.java
@@ -6,16 +6,13 @@
 
 package org.hyperledger.fabric.shim.utils;
 
+import com.google.protobuf.ByteString;
 import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 
-import com.google.protobuf.ByteString;
-
 public final class MessageUtil {
 
-    private MessageUtil() {
-
-    }
+    private MessageUtil() {}
 
     /**
      * Generate chaincode messages
@@ -27,8 +24,12 @@ private MessageUtil() {
      * @param event
      * @return
      */
-    public static ChaincodeMessage newEventMessage(final ChaincodeMessage.Type type, final String channelId, final String txId,
-            final ByteString payload, final ChaincodeEvent event) {
+    public static ChaincodeMessage newEventMessage(
+            final ChaincodeMessage.Type type,
+            final String channelId,
+            final String txId,
+            final ByteString payload,
+            final ChaincodeEvent event) {
         final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder()
                 .setType(type)
                 .setChannelId(channelId)
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/TimeoutUtil.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/TimeoutUtil.java
index 6216363dd..128364833 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/TimeoutUtil.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/shim/utils/TimeoutUtil.java
@@ -11,16 +11,13 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 
-/**
- * Give possibility to stop runnable execution after specific time, if not ended
- */
+/** Give possibility to stop runnable execution after specific time, if not ended */
 public final class TimeoutUtil {
 
-    private TimeoutUtil() {
-
-    }
+    private TimeoutUtil() {}
 
-    public static void runWithTimeout(final Runnable callable, final long timeout, final TimeUnit timeUnit) throws Exception {
+    public static void runWithTimeout(final Runnable callable, final long timeout, final TimeUnit timeUnit)
+            throws Exception {
         final ExecutorService executor = Executors.newSingleThreadExecutor();
         final CountDownLatch latch = new CountDownLatch(1);
         final Thread t = new Thread(() -> {
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/TracesTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/TracesTest.java
index 38bf768aa..f175484cd 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/TracesTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/TracesTest.java
@@ -5,33 +5,28 @@
  */
 package org.hyperledger.fabric.traces;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import io.opentelemetry.api.trace.Span;
-import org.hyperledger.fabric.traces.impl.DefaultTracesProvider;
+import java.util.Properties;
 import org.hyperledger.fabric.shim.ChaincodeStub;
+import org.hyperledger.fabric.traces.impl.DefaultTracesProvider;
 import org.hyperledger.fabric.traces.impl.NullProvider;
 import org.hyperledger.fabric.traces.impl.OpenTelemetryTracesProvider;
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Nested;
 import org.junit.jupiter.api.Test;
 
-import java.util.Properties;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-public class TracesTest {
+final class TracesTest {
 
-    public static final class TestProvider implements TracesProvider {
+    private static final class TestProvider implements TracesProvider {
 
-        public TestProvider() {
-
-        }
+        public TestProvider() {}
 
         @Override
-        public void initialize(final Properties props) {
-        }
+        public void initialize(final Properties props) {}
 
         @Override
         public Span createSpan(final ChaincodeStub stub) {
@@ -41,48 +36,49 @@ public Span createSpan(final ChaincodeStub stub) {
 
     @Nested
     @DisplayName("Traces initialize")
-    class Initialize {
+    final class Initialize {
 
         @Test
-        public void tracesDisabled() {
+        void tracesDisabled() {
             final TracesProvider provider = Traces.initialize(new Properties());
             assertThat(provider).isExactlyInstanceOf(NullProvider.class);
         }
 
         @Test
-        public void tracesEnabledUnknownProvider() {
+        void tracesEnabledUnknownProvider() {
             final Properties props = new Properties();
             props.put("CHAINCODE_TRACES_PROVIDER", "org.example.traces.provider");
             props.put("CHAINCODE_TRACES_ENABLED", "true");
 
-            assertThrows(RuntimeException.class, () -> {
-                final TracesProvider provider = Traces.initialize(props);
-            }, "Unable to start traces");
+            assertThrows(
+                    RuntimeException.class,
+                    () -> {
+                        final TracesProvider provider = Traces.initialize(props);
+                    },
+                    "Unable to start traces");
         }
 
         @Test
-        public void tracesNoProvider() {
+        void tracesNoProvider() {
             final Properties props = new Properties();
             props.put("CHAINCODE_TRACES_ENABLED", "true");
 
             final TracesProvider provider = Traces.initialize(props);
             assertTrue(provider instanceof DefaultTracesProvider);
-
         }
 
         @Test
-        public void tracesOpenTelemetryProvider() {
+        void tracesOpenTelemetryProvider() {
             final Properties props = new Properties();
             props.put("CHAINCODE_TRACES_PROVIDER", "org.hyperledger.fabric.traces.impl.OpenTelemetryTracesProvider");
             props.put("CHAINCODE_TRACES_ENABLED", "true");
 
             final TracesProvider provider = Traces.initialize(props);
             assertTrue(provider instanceof OpenTelemetryTracesProvider);
-
         }
 
         @Test
-        public void tracesValid() {
+        void tracesValid() {
             final Properties props = new Properties();
             props.put("CHAINCODE_TRACES_PROVIDER", TracesTest.TestProvider.class.getName());
             props.put("CHAINCODE_TRACES_ENABLED", "true");
@@ -90,6 +86,5 @@ public void tracesValid() {
 
             assertThat(provider).isExactlyInstanceOf(TracesTest.TestProvider.class);
         }
-
     }
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/DefaultProviderTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/DefaultProviderTest.java
index 7740b3418..2c07a3d44 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/DefaultProviderTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/DefaultProviderTest.java
@@ -5,17 +5,17 @@
  */
 package org.hyperledger.fabric.traces.impl;
 
+import static org.assertj.core.api.Assertions.assertThat;
+
 import io.opentelemetry.api.trace.Span;
 import org.hyperledger.fabric.contract.ChaincodeStubNaiveImpl;
 import org.hyperledger.fabric.shim.ChaincodeStub;
 import org.junit.jupiter.api.Test;
 
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class DefaultProviderTest {
+final class DefaultProviderTest {
 
     @Test
-    public void testDefaultProvider() {
+    void testDefaultProvider() {
         DefaultTracesProvider provider = new DefaultTracesProvider();
         ChaincodeStub stub = new ChaincodeStubNaiveImpl();
         Span span = provider.createSpan(stub);
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryPropertiesTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryPropertiesTest.java
index fca985db1..96d895374 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryPropertiesTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryPropertiesTest.java
@@ -5,15 +5,6 @@
  */
 package org.hyperledger.fabric.traces.impl;
 
-import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException;
-import org.junit.jupiter.api.Test;
-
-import java.time.Duration;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
 import static java.time.temporal.ChronoUnit.DAYS;
 import static java.time.temporal.ChronoUnit.HOURS;
 import static java.time.temporal.ChronoUnit.MILLIS;
@@ -22,96 +13,104 @@
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
-public class OpenTelemetryPropertiesTest {
+import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+
+final class OpenTelemetryPropertiesTest {
 
     @Test
-    public void testOverrideValue() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "bar"), Collections.singletonMap("foo", "foobar"));
+    void testOverrideValue() {
+        OpenTelemetryProperties props = new OpenTelemetryProperties(
+                Collections.singletonMap("foo", "bar"), Collections.singletonMap("foo", "foobar"));
         assertThat(props.getString("foo")).isEqualTo("foobar");
     }
 
     @Test
-    public void testCanGetDurationDays() {
+    void testCanGetDurationDays() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5d"));
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, DAYS));
     }
 
     @Test
-    public void testCanGetDurationHours() {
+    void testCanGetDurationHours() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5h"));
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, HOURS));
     }
 
-
     @Test
-    public void testCanGetDurationMinutes() {
+    void testCanGetDurationMinutes() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5m"));
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, MINUTES));
     }
 
     @Test
-    public void testCanGetDurationSeconds() {
+    void testCanGetDurationSeconds() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5s"));
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, SECONDS));
     }
 
     @Test
-    public void testCanGetDurationMilliSeconds() {
+    void testCanGetDurationMilliSeconds() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5ms"));
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, MILLIS));
     }
 
     @Test
-    public void testCanGetDurationInvalid() {
+    void testCanGetDurationInvalid() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5foo"));
         assertThatThrownBy(() -> props.getDuration("foo")).isInstanceOf(ConfigurationException.class);
     }
 
     @Test
-    public void testGetDouble() {
+    void testGetDouble() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5.23"));
         assertThat(props.getDouble("foo")).isEqualTo(5.23d);
         assertThat(props.getDouble("bar")).isNull();
     }
 
     @Test
-    public void testGetDoubleInvalid() {
+    void testGetDoubleInvalid() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5foo"));
         assertThatThrownBy(() -> props.getDouble("foo")).isInstanceOf(ConfigurationException.class);
     }
 
     @Test
-    public void testGetLong() {
+    void testGetLong() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "500003"));
         assertThat(props.getLong("foo")).isEqualTo(500003L);
         assertThat(props.getLong("bar")).isNull();
     }
 
-
     @Test
-    public void testGetInt() {
+    void testGetInt() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "500003"));
         assertThat(props.getInt("foo")).isEqualTo(500003);
         assertThat(props.getInt("bar")).isNull();
     }
 
     @Test
-    public void testGetBoolean() {
+    void testGetBoolean() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "true"));
         assertThat(props.getBoolean("foo")).isTrue();
         assertThat(props.getBoolean("bar")).isNull();
     }
 
     @Test
-    public void testGetList() {
+    void testGetList() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "foo,bar,foobar"));
         assertThat(props.getList("foo")).isEqualTo(Arrays.asList("foo", "bar", "foobar"));
         assertThat(props.getList("bar")).isEqualTo(Collections.emptyList());
     }
 
     @Test
-    public void testGetMap() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "foo=bar,foobar=noes"));
+    void testGetMap() {
+        OpenTelemetryProperties props =
+                new OpenTelemetryProperties(Collections.singletonMap("foo", "foo=bar,foobar=noes"));
         Map expected = new HashMap<>();
         expected.put("foo", "bar");
         expected.put("foobar", "noes");
@@ -119,8 +118,9 @@ public void testGetMap() {
     }
 
     @Test
-    public void testGetMapInvalid() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "foo/bar,foobar/noes"));
+    void testGetMapInvalid() {
+        OpenTelemetryProperties props =
+                new OpenTelemetryProperties(Collections.singletonMap("foo", "foo/bar,foobar/noes"));
         Map expected = new HashMap<>();
         assertThatThrownBy(() -> props.getMap("foo")).isInstanceOf(ConfigurationException.class);
     }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProviderTest.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProviderTest.java
index 7b03a3f2d..af8689ef6 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProviderTest.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/OpenTelemetryTracesProviderTest.java
@@ -5,6 +5,8 @@
  */
 package org.hyperledger.fabric.traces.impl;
 
+import static org.assertj.core.api.Assertions.assertThat;
+
 import io.grpc.ManagedChannelBuilder;
 import io.grpc.Server;
 import io.grpc.ServerCall;
@@ -17,10 +19,14 @@
 import io.grpc.stub.StreamObserver;
 import io.opentelemetry.api.trace.Span;
 import io.opentelemetry.sdk.trace.data.SpanData;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
 import org.hyperledger.fabric.contract.ChaincodeStubNaiveImpl;
 import org.hyperledger.fabric.metrics.Metrics;
-import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeGrpc;
+import org.hyperledger.fabric.protos.peer.ChaincodeID;
 import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
 import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc;
 import org.hyperledger.fabric.shim.ChaincodeBase;
@@ -31,14 +37,7 @@
 import org.hyperledger.fabric.traces.Traces;
 import org.junit.jupiter.api.Test;
 
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public final class OpenTelemetryTracesProviderTest {
+final class OpenTelemetryTracesProviderTest {
 
     private final class ContextGetterChaincode extends ChaincodeBase {
 
@@ -58,9 +57,8 @@ public Properties getChaincodeConfig() {
         }
     }
 
-
     @Test
-    public void testProvider() {
+    void testProvider() {
         OpenTelemetryTracesProvider provider = new OpenTelemetryTracesProvider();
         provider.initialize(new Properties());
         ChaincodeStub stub = new ChaincodeStubNaiveImpl();
@@ -70,7 +68,7 @@ public void testProvider() {
     }
 
     @Test
-    public void testTracing() throws Exception {
+    void testTracing() throws Exception {
 
         Properties props = new Properties();
         props.put("CHAINCODE_TRACES_ENABLED", "true");
@@ -84,33 +82,35 @@ public void testTracing() throws Exception {
         // set up a grpc server in process
         ServerCallHandler handler = (call, headers) -> {
             call.close(Status.OK, headers);
-            return new ServerCall.Listener() {
-            };
+            return new ServerCall.Listener<>() {};
         };
 
-        ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(ChaincodeGrpc.getServiceDescriptor()).
-                addMethod(ServerMethodDefinition.create(ChaincodeGrpc.getConnectMethod(), handler));
-        ServerServiceDefinition.Builder supportBuilder = ServerServiceDefinition.builder(ChaincodeSupportGrpc.getServiceDescriptor()).
-                addMethod(ServerMethodDefinition.create(ChaincodeSupportGrpc.getRegisterMethod(), handler));
+        ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(ChaincodeGrpc.getServiceDescriptor())
+                .addMethod(ServerMethodDefinition.create(ChaincodeGrpc.getConnectMethod(), handler));
+        ServerServiceDefinition.Builder supportBuilder = ServerServiceDefinition.builder(
+                        ChaincodeSupportGrpc.getServiceDescriptor())
+                .addMethod(ServerMethodDefinition.create(ChaincodeSupportGrpc.getRegisterMethod(), handler));
 
         String uniqueName = InProcessServerBuilder.generateName();
         Server server = InProcessServerBuilder.forName(uniqueName)
                 .directExecutor()
                 .addService(builder.build())
                 .addService(supportBuilder.build())
-                .build().start();
+                .build()
+                .start();
 
         // create our client
         ManagedChannelBuilder channelBuilder = InProcessChannelBuilder.forName(uniqueName);
         ContextGetterChaincode chaincode = new ContextGetterChaincode();
         ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder);
 
-        InvocationTaskManager itm = InvocationTaskManager.getManager(chaincode, ChaincodeID.newBuilder().setName("foo").build());
+        InvocationTaskManager itm = InvocationTaskManager.getManager(
+                chaincode, ChaincodeID.newBuilder().setName("foo").build());
 
         CompletableFuture wait = new CompletableFuture<>();
-        StreamObserver requestObserver = chaincodeSupportClient.getStub().register(
-
-                new StreamObserver() {
+        StreamObserver requestObserver = chaincodeSupportClient
+                .getStub()
+                .register(new StreamObserver<>() {
                     @Override
                     public void onNext(final ChaincodeMessage chaincodeMessage) {
                         // message off to the ITM...
@@ -128,9 +128,7 @@ public void onCompleted() {
                         chaincodeSupportClient.shutdown(itm);
                         wait.complete(null);
                     }
-                }
-
-        );
+                });
 
         chaincodeSupportClient.start(itm, requestObserver);
         wait.get(5, TimeUnit.SECONDS);
@@ -141,5 +139,4 @@ public void onCompleted() {
         chaincodeSupportClient.shutdown(itm);
         server.shutdown();
     }
-
 }
diff --git a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/TestSpanExporterProvider.java b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/TestSpanExporterProvider.java
index 2bfa9bd6e..95891c675 100644
--- a/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/TestSpanExporterProvider.java
+++ b/fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/traces/impl/TestSpanExporterProvider.java
@@ -10,7 +10,6 @@
 import io.opentelemetry.sdk.common.CompletableResultCode;
 import io.opentelemetry.sdk.trace.data.SpanData;
 import io.opentelemetry.sdk.trace.export.SpanExporter;
-
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -22,7 +21,7 @@ public final class TestSpanExporterProvider implements ConfigurableSpanExporterP
 
         @Override
         public CompletableResultCode export(final Collection spans) {
-            TestSpanExporterProvider.SPANS.addAll(spans);
+            SPANS.addAll(spans);
             return CompletableResultCode.ofSuccess();
         }
 
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index d64cd4917..a4b76b953 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 0aaefbcaf..e2847c820 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
 distributionBase=GRADLE_USER_HOME
 distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
 networkTimeout=10000
 validateDistributionUrl=true
 zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
index 1aa94a426..f5feea6d6 100755
--- a/gradlew
+++ b/gradlew
@@ -15,6 +15,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+# SPDX-License-Identifier: Apache-2.0
+#
 
 ##############################################################################
 #
@@ -55,7 +57,7 @@
 #       Darwin, MinGW, and NonStop.
 #
 #   (3) This script is generated from the Groovy template
-#       https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+#       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/.
@@ -84,7 +86,8 @@ done
 # shellcheck disable=SC2034
 APP_BASE_NAME=${0##*/}
 # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
-APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
 
 # Use the maximum available, or set MAX_FD != -1 to use that value.
 MAX_FD=maximum
diff --git a/gradlew.bat b/gradlew.bat
index 7101f8e46..9b42019c7 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -13,6 +13,8 @@
 @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
 @rem ##########################################################################
diff --git a/pmd-ruleset.xml b/pmd-ruleset.xml
new file mode 100644
index 000000000..3c886141a
--- /dev/null
+++ b/pmd-ruleset.xml
@@ -0,0 +1,54 @@
+
+
+    Custom PMD ruleset
+    
+        
+    
+    
+        
+            
+        
+    
+    
+        
+        
+        
+        
+        
+        
+        
+    
+    
+        
+            
+            
+        
+    
+    
+        
+        
+        
+        
+        
+    
+    
+        
+            
+        
+    
+    
+    
+    
+        
+        
+    
+    
+        
+        
+    
+    
+    
+
diff --git a/settings.gradle b/settings.gradle
index c384cfad7..3837c43e9 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -7,4 +7,4 @@ rootProject.name = 'fabric-chaincode-java'
 
 include 'fabric-chaincode-shim'
 include 'fabric-chaincode-docker'
-include 'fabric-chaincode-integration-test'
\ No newline at end of file
+include 'fabric-chaincode-integration-test'