diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d64500d8..5914179d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Push to registry ${{ matrix.publish_target }} run: | @@ -65,7 +65,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Build the dependencies needed for the image run: ./gradlew :fabric-chaincode-docker:copyAllDeps diff --git a/.github/workflows/scan.yml b/.github/workflows/scan.yml index e87983eb..6147f760 100644 --- a/.github/workflows/scan.yml +++ b/.github/workflows/scan.yml @@ -22,7 +22,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Set up Go uses: actions/setup-go@v5 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7ae6e959..791e657a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Build and Unit test run: ./gradlew :fabric-chaincode-shim:build @@ -36,7 +36,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Populate chaincode with latest java-version run: | @@ -69,7 +69,7 @@ jobs: - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 - uses: gradle/actions/setup-gradle@v4 - name: Build Docker image run: ./gradlew :fabric-chaincode-docker:buildImage diff --git a/.gitignore b/.gitignore index 1e849943..78211b3e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ **/bin/ /build/ build/* +settings-gradle.lockfile _cfg repository diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8f624836..d872b5bc 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/build.gradle b/build.gradle index 094a38f0..0b11212f 100644 --- a/build.gradle +++ b/build.gradle @@ -6,12 +6,13 @@ plugins { id "com.github.ben-manes.versions" version "0.51.0" + alias libs.plugins.spotless } 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,16 +24,27 @@ if (properties.containsKey('NIGHTLY')) { } allprojects { + apply plugin: libs.plugins.spotless.get().pluginId + 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 @@ -64,6 +76,13 @@ subprojects { 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 index 14ee8c15..92b99a49 100644 --- a/ci/checkstyle/checkstyle.xml +++ b/ci/checkstyle/checkstyle.xml @@ -41,20 +41,8 @@ - - - - - - - - - - - - @@ -108,11 +96,6 @@ - - - - - diff --git a/fabric-chaincode-docker/build.gradle b/fabric-chaincode-docker/build.gradle index f65f9468..e5ba5d6c 100644 --- a/fabric-chaincode-docker/build.gradle +++ b/fabric-chaincode-docker/build.gradle @@ -67,4 +67,3 @@ task buildImage(type: DockerBuildImage) { inputDir = project.file('Dockerfile').parentFile 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/build.gradle b/fabric-chaincode-integration-test/build.gradle index 08d1524e..9d2b1fc7 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 67b9b238..fce50a3e 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/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 881ac8cd..b05dbf81 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 20a1825e..ad856978 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 50b27c45..94ebb378 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 418cdbf7..32e8ec56 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,8 +19,6 @@ public class SBECCIntegrationTest { @BeforeAll public static void setUp() throws Exception { FabricState.getState().start(); - - } @Test @@ -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,10 +82,9 @@ public void RunSBE_pub_setget() { assertThat(text, containsString("success")); text = helper.invoke("org1", "EndorsementCC:recordExists", mode); assertThat(text, containsString("false")); - } - @Test + @Test public void RunSBE_priv() { final String mode = "priv"; @@ -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 b135a48b..2440e224 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 a18a282e..a4a759e8 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 f500d333..e24bed82 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 3beaac55..50a2e8eb 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 59909a2a..8483446e 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 @@ -10,7 +10,6 @@ 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 { @@ -49,15 +48,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 971cb252..6d4915f8 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 99c19111..65f045b3 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,43 +106,43 @@ 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"); } @@ -155,12 +151,11 @@ public Peer build(Map additionalEnv){ 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-shim/build.gradle b/fabric-chaincode-shim/build.gradle index ded8f870..24c0e79f 100644 --- a/fabric-chaincode-shim/build.gradle +++ b/fabric-chaincode-shim/build.gradle @@ -47,7 +47,7 @@ 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.opentelemetry:opentelemetry-bom:1.42.1') + implementation platform('io.opentelemetry:opentelemetry-bom:1.43.0') implementation 'org.hyperledger.fabric:fabric-protos:0.3.3' implementation 'org.bouncycastle:bcpkix-jdk18on:1.78.1' @@ -56,7 +56,7 @@ dependencies { 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' @@ -64,14 +64,15 @@ dependencies { // Required if using Java 11+ as no longer bundled in the core libraries testImplementation 'javax.xml.bind:jaxb-api:2.3.1' - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry.proto:opentelemetry-proto:1.3.2-alpha' + compileOnly 'io.opentelemetry:opentelemetry-api' implementation 'io.opentelemetry:opentelemetry-sdk' implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' implementation 'io.opentelemetry:opentelemetry-sdk-trace' implementation 'io.opentelemetry:opentelemetry-exporter-otlp' implementation 'io.opentelemetry:opentelemetry-extension-trace-propagators' - implementation 'io.opentelemetry.instrumentation:opentelemetry-grpc-1.6:2.8.0-alpha' + implementation 'io.opentelemetry.semconv:opentelemetry-semconv' + implementation 'io.opentelemetry.proto:opentelemetry-proto:1.3.2-alpha' + implementation 'io.opentelemetry.instrumentation:opentelemetry-grpc-1.6:2.9.0-alpha' } sourceSets { @@ -226,7 +227,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 +298,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 c8b0f9d6..e1a55c90 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,10 +11,7 @@ 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) { @@ -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); } @@ -57,16 +50,12 @@ public static Logger getLogger(final Class class1) { return l; } - /** - * @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 b6369056..1d26eaf4 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 @@ -15,31 +15,22 @@ /** * 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. @@ -63,7 +54,6 @@ public static String formatError(final Throwable throwable) { } return buffer.toString(); - } /** @@ -79,30 +69,33 @@ public static void setLogLevel(final String newLevel) { // so find those that have the correct stem. final ArrayList 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(name -> logManager.getLogger(name)) + .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; + 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 078e0657..4c10f704 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,12 +25,9 @@ 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()); @@ -60,7 +56,8 @@ 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(); @@ -71,12 +68,12 @@ public ClientIdentity(final ChaincodeStub stub) throws CertificateException, JSO } // 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,10 +93,9 @@ 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 { @@ -107,7 +103,8 @@ private Map parseAttributes(final byte[] extensionValue) throws 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(); @@ -136,16 +133,13 @@ private Map parseAttributes(final byte[] extensionValue) throws } /** - * 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)) { @@ -156,16 +150,14 @@ public String getAttributeValue(final String attrName) { } /** - * 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)) { @@ -176,9 +168,8 @@ public boolean assertAttributeValue(final String attrName, final String attrValu } /** - * 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 c11f17f9..ea0b4d36 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 b282dc2d..64e12a1b 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,17 +8,11 @@ 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; - /** - * - * @return ContextFactory - */ + /** @return ContextFactory */ public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); @@ -27,7 +21,6 @@ public static synchronized ContextFactory getInstance() { } /** - * * @param stub * @return Context */ @@ -35,5 +28,4 @@ public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } - } 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 9ef0352e..c9bea5fc 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,21 @@ 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) { - } + default void beforeTransaction(final Context ctx) {} /** * 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) { - } + default void afterTransaction(final Context ctx, final Object result) {} } 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 510f1498..0219f71d 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,13 +28,9 @@ 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 */ @@ -47,10 +46,9 @@ 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 */ @@ -81,9 +79,7 @@ public ContractRouter(final String[] args) { executor = ExecutionFactory.getInstance().createExecutionService(serializers); } - /** - * Locate all the contracts that are available on the classpath. - */ + /** Locate all the contracts that are available on the classpath. */ protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } @@ -91,7 +87,7 @@ protected void findAllContracts() { /** * 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 */ @@ -169,8 +165,7 @@ public static void main(final String[] args) throws Exception { // 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()); + ChaincodeServer chaincodeServer = new NettyChaincodeServer(cfc, cfc.getChaincodeServerConfig()); chaincodeServer.start(); } else { logger.info("Starting chaincode as client"); @@ -201,5 +196,4 @@ public void startRouterWithChaincodeServer(final ChaincodeServer chaincodeServer 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 0fca449f..b51c218f 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,19 @@ 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 { - /** - * - * @param string - */ + /** @param string */ public ContractRuntimeException(final String string) { super(string); } /** - * * @param string * @param cause */ @@ -34,17 +28,11 @@ 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. - */ + /** 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 c344b37b..fb3e2fc9 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 d28987b2..8114170e 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 8799198d..a671fcf0 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 683ba668..f289e56a 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 8b1d05fd..17d02e16 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 88989f02..a585f634 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 1b75fffb..5a94e8dc 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 10ff45d6..37d91fc9 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 c9180ca4..3f41e3fb 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 0d437c5e..fee47eb1 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 @@ -14,9 +14,7 @@ public class ExecutionFactory { private static ExecutionFactory rf; - /** - * @return ExecutionFactory - */ + /** @return ExecutionFactory */ public static ExecutionFactory getInstance() { if (rf == null) { rf = new ExecutionFactory(); 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 ef0b9719..8c859680 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 6978e037..92c478c1 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 c7633e53..c1c99591 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 @@ -15,7 +15,6 @@ 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,19 +26,14 @@ import org.json.JSONException; import org.json.JSONObject; -/** - * Used as a the default serialisation for transmission from SDK to Contract. - */ +/** Used as a the default serialisation for transmission from SDK to Contract. */ @Serializer() public class JSONTransactionSerializer implements SerializerInterface { private static Logger logger = Logger.getLogger(JSONTransactionSerializer.class.getName()); private final TypeRegistry typeRegistry = TypeRegistry.getRegistry(); - /** - * Create a new serialiser. - */ - public JSONTransactionSerializer() { - } + /** Create a new serialiser. */ + public JSONTransactionSerializer() {} /** * Convert the value supplied to a byte array, according to the TypeSchema. @@ -56,23 +50,23 @@ public byte[] toBuffer(final Object value, final TypeSchema ts) { 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 (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); } } else { // at this point we can assert that the value is @@ -102,14 +96,13 @@ 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 */ private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) { @@ -143,7 +136,6 @@ private JSONArray normalizeArray(final JSONArray jsonArray, final TypeSchema ts) final JSONObject obj = new JSONObject(jsonArray.getJSONObject(i), propNames); normalizedArray.put(i, obj); } - } return normalizedArray; } @@ -152,8 +144,7 @@ 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 @@ -172,11 +163,10 @@ public Object fromBuffer(final byte[] buffer, final TypeSchema ts) { } /** - * 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 @@ -191,31 +181,32 @@ private Class mapPrimitive(final Class 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; + 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; } } /* * Internal method to do the conversion */ - private Object convert(final String stringData, final TypeSchema ts) throws IllegalArgumentException, IllegalAccessException, InstantiationException { + private Object convert(final String stringData, final TypeSchema ts) + throws IllegalArgumentException, IllegalAccessException, InstantiationException { logger.debug(() -> "Schema to convert is " + ts); String type = ts.getType(); String format = null; @@ -236,20 +227,20 @@ private Object convert(final String stringData, final TypeSchema ts) throws Ille } else if (type.contentEquals("integer")) { final String intFormat = ts.getFormat(); switch (intFormat) { - case "int32": - value = Integer.parseInt(stringData); - break; - case "int8": - value = Byte.parseByte(stringData); - break; - case "int16": - value = Short.parseShort(stringData); - break; - case "int64": - value = Long.parseLong(stringData); - break; - default: - throw new RuntimeException("Unknown format for integer " + intFormat); + case "int32": + value = Integer.parseInt(stringData); + break; + case "int8": + value = Byte.parseByte(stringData); + break; + case "int16": + value = Short.parseShort(stringData); + break; + case "int64": + value = Long.parseLong(stringData); + break; + default: + throw new RuntimeException("Unknown format for integer " + intFormat); } } else if (type.contentEquals("number")) { @@ -268,13 +259,13 @@ private Object convert(final String stringData, final TypeSchema ts) throws Ille 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()); + 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; - } return value; } @@ -282,9 +273,9 @@ private Object convert(final String stringData, final TypeSchema ts) throws Ille /** * 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 */ Object createComponentInstance(final String format, final String jsonString, final TypeSchema ts) { @@ -293,7 +284,10 @@ Object createComponentInstance(final String format, final String jsonString, fin 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,7 +296,7 @@ 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();) { + for (final Iterator iterator = fields.values().iterator(); iterator.hasNext(); ) { final PropertyDefinition prop = iterator.next(); final Field f = prop.getField(); @@ -310,12 +304,14 @@ Object createComponentInstance(final String format, final String jsonString, fin 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 ed5cc584..f52d87d0 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 e9611107..b8803269 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,29 +26,21 @@ 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 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) { + 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 a2b9d9e9..a63d2ffc 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 @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.contract.execution.InvocationRequest; @@ -22,11 +21,10 @@ public class ContractInvocationRequest implements InvocationRequest { private static Log logger = LogFactory.getLog(ContractInvocationRequest.class); - /** - * @param context - */ + /** @param context */ public ContractInvocationRequest(final ChaincodeStub context) { - final String func = context.getStringArgs().size() > 0 ? context.getStringArgs().get(0) : null; + final String func = + context.getStringArgs().size() > 0 ? context.getStringArgs().get(0) : null; final String[] funcParts = func.split(":"); logger.debug(func); if (funcParts.length == 2) { @@ -41,44 +39,33 @@ public ContractInvocationRequest(final ChaincodeStub context) { 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 dd93d90a..b708841f 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 2c9651ad..4fa00279 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 6b1830db..c7b5d0c0 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 @@ -17,7 +17,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,17 +36,14 @@ /** * 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 */ public final class MetadataBuilder { private static Logger logger = Logger.getLogger(MetadataBuilder.class); - private MetadataBuilder() { - - } + private MetadataBuilder() {} @SuppressWarnings("serial") static class MetadataMap extends HashMap { @@ -83,8 +79,11 @@ public static void validate() { 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()); @@ -92,17 +91,18 @@ public static void validate() { throw new RuntimeException(e); } catch (final ValidationException e) { logger.error(e.getMessage()); - e.getCausingExceptions().stream().map(ValidationException::getMessage).forEach(logger::info); + e.getCausingExceptions().stream() + .map(ValidationException::getMessage) + .forEach(logger::info); logger.error(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) { @@ -117,7 +117,6 @@ public static void initialize(final RoutingRegistry registry, final TypeRegistry // check logger.info("Validating schema created"); MetadataBuilder.validate(); - } /** @@ -195,7 +194,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) { @@ -270,10 +269,7 @@ private static JSONObject metadata() { return joMetadata; } - /** - * - * @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 213fb83d..79453428 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,6 @@ import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; - import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; @@ -19,24 +18,18 @@ 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") public final class TypeSchema extends HashMap { private static Logger logger = Logger.getLogger(TypeSchema.class.getName()); - /** - * - */ - public TypeSchema() { - - } + /** */ + public TypeSchema() {} private Object putInternal(final String key, final Object value) { if (value != null && !value.toString().isEmpty()) { @@ -62,10 +55,7 @@ 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"); @@ -74,10 +64,7 @@ public String getType() { return (String) this.get("type"); } - /** - * - * @return TypeSchema items - */ + /** @return TypeSchema items */ public TypeSchema getItems() { if (this.containsKey("schema")) { final Map intermediateMap = (Map) this.get("schema"); @@ -86,23 +73,16 @@ public TypeSchema getItems() { return (TypeSchema) this.get("items"); } - /** - * - * @return Reference - */ + /** @return Reference */ public String getRef() { if (this.containsKey("schema")) { final Map intermediateMap = (Map) this.get("schema"); 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"); @@ -112,7 +92,6 @@ public String getFormat() { } /** - * * @param typeRegistry * @return Class object */ @@ -135,33 +114,33 @@ public Class getTypeClass(final TypeRegistry typeRegistry) { // need to check the format final String format = getFormat(); switch (format) { - case "int8": - clz = byte.class; - break; - case "int16": - clz = short.class; - break; - case "int32": - clz = int.class; - break; - case "int64": - clz = long.class; - break; - default: - throw new RuntimeException("Unknown format for integer of " + format); + case "int8": + clz = byte.class; + break; + case "int16": + clz = short.class; + break; + case "int32": + clz = int.class; + break; + case "int64": + clz = long.class; + break; + 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); + 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; @@ -183,7 +162,6 @@ public Class getTypeClass(final TypeRegistry typeRegistry) { * * @param clz * @return TypeSchema - * */ public static TypeSchema typeConvert(final Class clz) { final TypeSchema returnschema = new TypeSchema(); @@ -213,61 +191,60 @@ public static TypeSchema typeConvert(final Class clz) { } 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)); + 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)); } return returnschema; } - - /** - * 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 @@ -289,11 +266,11 @@ 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); + e.getCausingExceptions().stream() + .map(ValidationException::getMessage) + .forEach(sb::append); logger.info(sb.toString()); throw new ContractRuntimeException(sb.toString(), 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 743c7b04..d02326ec 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 5185aedb..24dbf8be 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 ba8072cb..4bca0f44 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 3267a718..84d2e3fb 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 bc81c234..2411e6aa 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 dd4e7e37..4c53cdc7 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 3c4e9825..264ff9b2 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 80472df5..37e307b7 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 860e2278..392419fa 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 73271956..4b61e2d4 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 09a293fc..056b3abc 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,9 +21,7 @@ /** * 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); @@ -36,10 +33,7 @@ public final class ContractDefinitionImpl implements ContractDefinition { private final Contract contractAnnotation; private TxFunction unknownTx; - /** - * - * @param cl - */ + /** @param cl */ public ContractDefinitionImpl(final Class cl) { final Contract annotation = cl.getAnnotation(Contract.class); @@ -62,7 +56,8 @@ public ContractDefinitionImpl(final Class cl) { unknownTx = new TxFunctionImpl(m, this); unknownTx.setUnknownTx(true); } catch (NoSuchMethodException | SecurityException e) { - final ContractRuntimeException cre = new ContractRuntimeException("Failure to find unknownTransaction method", e); + final ContractRuntimeException cre = + new ContractRuntimeException("Failure to find unknownTransaction method", e); logger.severe(() -> logger.formatError(cre)); throw cre; } 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 78c2b9a1..5165bfbf 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 @@ -9,7 +9,6 @@ import java.util.HashMap; 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 +21,7 @@ public final class DataTypeDefinitionImpl implements DataTypeDefinition { private final String simpleName; private final Class clazz; - /** - * - * @param componentClass - */ + /** @param componentClass */ public DataTypeDefinitionImpl(final Class componentClass) { this.clazz = componentClass; this.name = componentClass.getName(); @@ -44,20 +40,22 @@ public DataTypeDefinitionImpl(final Class componentClass) { 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; + 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 +64,6 @@ public DataTypeDefinitionImpl(final Class componentClass) { this.properties.put(f.getName(), propDef); } } - } @Override @@ -115,5 +112,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 a99765ca..7fa8f6e6 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 5ea83705..f7772d04 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 084b3280..5996137c 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); @@ -131,7 +127,6 @@ public ContractDefinition getContract(final String namespace) { @Override public Collection getAllDefinitions() { return contracts.values(); - } /* @@ -145,9 +140,7 @@ 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()) { @@ -198,7 +191,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) { @@ -217,7 +209,6 @@ private void addContracts(final List> contractClasses) logger.debug("Found annotated method " + m.getName()); contract.addTxFunction(m); - } } @@ -225,5 +216,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 74b9a0b8..3e7c1f74 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,35 +5,29 @@ */ 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 final Class annotationClass = Serializer.class; - /** - * - */ - public SerializerRegistryImpl() { - } + /** */ + public SerializerRegistryImpl() {} // Could index these by name and or type. private final Map contents = new HashMap<>(); @@ -41,7 +35,7 @@ public SerializerRegistryImpl() { /** * 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,7 +44,8 @@ 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) { + 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; @@ -78,7 +73,8 @@ 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())) { + 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(); @@ -94,9 +90,6 @@ public void findAndSetContents() throws InstantiationException, IllegalAccessExc logger.debug("Failed to load class: " + e); } } - } - } - } 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 b12726d2..3f61350a 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 @@ -10,7 +10,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.hyperledger.fabric.Logger; import org.hyperledger.fabric.contract.Context; import org.hyperledger.fabric.contract.ContractInterface; @@ -42,7 +41,6 @@ public final class RoutingImpl implements Routing { 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,13 +76,12 @@ 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) { @@ -114,15 +113,15 @@ 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())); + final List params = + new ArrayList(Arrays.asList(method.getParameters())); // validate the first one is a context object if (params.size() == 0) { throw new ContractRuntimeException("First argument should be of type Context"); } else if (!Context.class.isAssignableFrom(params.get(0).getType())) { - throw new ContractRuntimeException( - "First argument should be of type Context " + method.getName() + " " + params.get(0).getType()); + throw new ContractRuntimeException("First argument should be of type Context " + method.getName() + " " + + params.get(0).getType()); } else { params.remove(0); @@ -137,7 +136,8 @@ public TxFunctionImpl(final Method m, final ContractDefinition contract) { final TypeSchema paramMap = new TypeSchema(); final TypeSchema schema = TypeSchema.typeConvert(parameter.getType()); - final Property annotation = parameter.getAnnotation(org.hyperledger.fabric.contract.annotation.Property.class); + 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) { @@ -147,8 +147,8 @@ public TxFunctionImpl(final Method m, final ContractDefinition contract) { paramMap.put("name", parameter.getName()); paramMap.put("schema", schema); - final ParameterDefinition pd = new ParameterDefinitionImpl(parameter.getName(), parameter.getClass(), paramMap, - parameter); + final ParameterDefinition pd = + new ParameterDefinitionImpl(parameter.getName(), parameter.getClass(), paramMap, parameter); paramsList.add(pd); } } @@ -193,10 +193,7 @@ public List getParamsList() { return paramsList; } - /** - * - * @param paramsList - */ + /** @param paramsList */ public void setParamsList(final ArrayList paramsList) { this.paramsList = paramsList; } @@ -209,7 +206,6 @@ public TypeSchema getReturnSchema() { @Override public void setParameterDefinitions(final List list) { this.paramsList = list; - } @Override @@ -221,5 +217,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 dc50d3dc..07377c77 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,15 +8,11 @@ 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 TypeRegistryImpl singletonInstance; @@ -75,5 +71,4 @@ public DataTypeDefinition getDataType(final TypeSchema schema) { 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 108f8132..e3d4b1ea 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 32533b45..4ab5847b 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 f2427e22..74fd07ab 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,22 +12,19 @@ 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() { - - } + /** */ + public SystemContract() {} /** - * * @param ctx * @return Metadata */ @@ -36,5 +33,4 @@ public String getMetadata(final Context ctx) { final String jsonmetadata = MetadataBuilder.getMetadata(); return jsonmetadata; } - } 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 5dcfe058..cde12bb0 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 195eb5f8..1f109da8 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 ce347971..3f9c11cc 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,36 @@ /** * 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 +50,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 +59,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 index faea7f49..c313ef77 100644 --- 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 @@ -7,16 +7,12 @@ import org.hyperledger.fabric.ledger.Collection; -/** - * Placeholder. - */ +/** Placeholder. */ public class CollectionImpl implements Collection { private final String name; /** - * - * * @param name * @param ledgerImpl */ @@ -29,5 +25,4 @@ 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 1087cd24..9f8ed761 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 @@ -39,5 +39,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 96b288ea..025bb854 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 ca6cfec7..129a4271 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 56bcdab6..74cd6247 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 @@ -8,16 +8,14 @@ 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,13 +26,9 @@ public final class Metrics { private static MetricsProvider provider; - - private Metrics() { - - } + private Metrics() {} /** - * * @param props * @return The metrics provide */ @@ -46,37 +40,36 @@ 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) { + } catch (ClassNotFoundException + | InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException + | NoSuchMethodException + | SecurityException e) { throw new RuntimeException("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 482fbbdf..9609ea87 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 { @@ -32,17 +28,15 @@ public interface MetricsProvider { * * @param props */ - default void initialize(final Properties props) { - }; + default void initialize(final Properties props) {} + ; /** - * 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) { - }; - + default void setTaskMetricsCollector(final TaskMetricsCollector taskService) {} + ; } 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 bb2c6065..ef59d6a4 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 a2dc8a78..841e4164 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,24 +9,17 @@ 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 TaskMetricsCollector taskService; - /** - * - */ + /** */ public DefaultProvider() { perflogger.info("Default Metrics Provider started"); } @@ -41,13 +34,15 @@ public void setTaskMetricsCollector(final TaskMetricsCollector taskService) { @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() { @@ -58,14 +53,18 @@ protected void logMetrics() { } 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())); + 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(); }); - } - } 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 f977ac67..19639009 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,9 @@ import org.hyperledger.fabric.metrics.MetricsProvider; -/** - * Very simple provider that does absolutely nothing. Used when metrics are - * disabled. - * - */ +/** Very simple provider that does absolutely nothing. Used when metrics are disabled. */ public class NullProvider implements MetricsProvider { - /** - * - */ - public NullProvider() { - } - + /** */ + public NullProvider() {} } 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 30152965..59afe468 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 ec9d196a..f9cf1f7b 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 cb5d58f6..dfeb5e02 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 046595df..b8882487 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,6 +41,7 @@ class Response {
 
         /**
          * Constructor.
+         *
          * @param status a status object.
          * @param message a response message.
          * @param payload a response payload.
@@ -57,6 +54,7 @@ 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.
@@ -69,6 +67,7 @@ public Response(final int statusCode, final String message, final byte[] payload
 
         /**
          * Get the response status.
+         *
          * @return status.
          */
         public Status getStatus() {
@@ -81,6 +80,7 @@ public Status getStatus() {
 
         /**
          * Get the response status code.
+         *
          * @return status code.
          */
         public int getStatusCode() {
@@ -89,6 +89,7 @@ public int getStatusCode() {
 
         /**
          * Get the response message.
+         *
          * @return a message.
          */
         public String getMessage() {
@@ -97,6 +98,7 @@ public String getMessage() {
 
         /**
          * Get the response payload.
+         *
          * @return payload bytes.
          */
         public byte[] getPayload() {
@@ -105,27 +107,20 @@ public byte[] getPayload() {
 
         /**
          * 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 +132,7 @@ public enum Status {
 
             /**
              * Get the status code associated with this status object.
+             *
              * @return a status code.
              */
             public int getCode() {
@@ -145,6 +141,7 @@ public int getCode() {
 
             /**
              * Get a status object for a given status code.
+             *
              * @param code a status code.
              * @return a status object.
              */
@@ -158,6 +155,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.
              */
@@ -170,8 +168,6 @@ public static boolean hasStatusForCode(final int code) {
                     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 da8da55e..0ce76bc4 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
@@ -9,6 +9,14 @@
 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;
@@ -26,10 +34,6 @@
 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,35 +47,21 @@
 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 */ 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 @@ -82,19 +72,13 @@ public abstract class ChaincodeBase implements Chaincode { private static final Logger LOGGER = Logger.getLogger(ChaincodeBase.class.getName()); - /** - * - */ + /** */ 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; @@ -132,10 +116,10 @@ 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 +129,6 @@ private int getMaxInboundMessageSize() { * * @param args command line arguments */ - public void start(final String[] args) { try { initializeLogging(); @@ -173,7 +156,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 +186,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 +209,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 +236,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); @@ -288,8 +269,8 @@ 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(""); for (final java.util.logging.Handler handler : rootLogger.getHandlers()) { @@ -300,7 +281,6 @@ protected final void initializeLogging() { public synchronized String format(final LogRecord record) { return Thread.currentThread() + " " + super.format(record); } - }); } @@ -322,33 +302,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; + 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. @@ -357,8 +335,7 @@ private SocketAddress parseHostPort(final String hostAddrStr) throws URISyntaxEx int port = uri.getPort(); if (uri.getHost() == null || uri.getPort() == -1) { - throw new URISyntaxException(uri.toString(), - "URI must have host and port parts"); + throw new URISyntaxException(uri.toString(), "URI must have host and port parts"); } // validation succeeded @@ -374,9 +351,7 @@ public boolean isServer() { return !chaincodeServerAddress.isEmpty(); } - /** - * Validate init parameters from env chaincode base. - */ + /** Validate init parameters from env chaincode base. */ public void validateOptions() { if (this.id == null || this.id.isEmpty()) { throw new IllegalArgumentException(format( @@ -435,12 +410,9 @@ protected final void processCommandLineOptions(final String[] args) { LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>"); LOGGER.info("CORE_CHAINCODE_ID_NAME: " + this.id); LOGGER.info("CORE_PEER_ADDRESS: " + this.host + ":" + this.port); - } - /** - * set fields from env. - */ + /** set fields from env. */ public final void processEnvironmentOptions() { if (System.getenv().containsKey(CORE_CHAINCODE_ID_NAME)) { @@ -492,9 +464,8 @@ public final void processEnvironmentOptions() { } /** - * 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 */ @@ -579,8 +550,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 +636,9 @@ String getId() { return id; } - /** - * Chaincode State. - */ + /** Chaincode State. */ public enum CCState { - /** - * */ + /** */ CREATED, /** */ ESTABLISHED, @@ -678,18 +648,12 @@ public enum CCState { 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 fe73b570..7a4b5312 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,19 +47,17 @@ 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. @@ -79,12 +69,11 @@ 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. */ public ChaincodeException(final String message, final byte[] payload, final Throwable cause) { super(message, cause); @@ -93,8 +82,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 +94,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,12 +109,9 @@ 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. */ 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 8c8ff2b3..81c7ce29 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 27c84257..af81bfb7 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 @@ -22,28 +22,33 @@ public final class ChaincodeServerProperties { private String trustCertCollectionFile; private boolean tlsEnabled = false; - /** - * Constructor using default configuration. - */ - public ChaincodeServerProperties() { - } + /** Constructor using default configuration. */ + public ChaincodeServerProperties() {} /** * 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 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 +62,7 @@ public ChaincodeServerProperties( /** * The maximum size of metadata allowed to be received. + * * @return The maximum metadata size allowed. */ public int getMaxInboundMetadataSize() { @@ -65,6 +71,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 +80,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 +89,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 +98,7 @@ public void setMaxInboundMessageSize(final int maxInboundMessageSize) { /** * The maximum connection age. + * * @return The maximum connection age in seconds. */ public int getMaxConnectionAgeSeconds() { @@ -97,6 +107,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 +116,7 @@ public void setMaxConnectionAgeSeconds(final int maxConnectionAgeSeconds) { /** * The timeout for a keep-alive ping requests. + * * @return timeout in seconds. */ public int getKeepAliveTimeoutSeconds() { @@ -113,6 +125,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 +134,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 +143,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 +152,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 +161,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,7 +169,9 @@ 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. */ public boolean getPermitKeepAliveWithoutCalls() { @@ -161,6 +180,7 @@ public boolean getPermitKeepAliveWithoutCalls() { /** * Get the server socket address. + * * @return a socket address. */ public SocketAddress getServerAddress() { @@ -169,6 +189,7 @@ public SocketAddress getServerAddress() { /** * Set the server socket address. + * * @param address a socket address. */ public void setServerAddress(final SocketAddress address) { @@ -176,7 +197,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 +207,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 +218,7 @@ public void setPermitKeepAliveWithoutCalls(final boolean permitKeepAliveWithoutC /** * Password used to access the server key. + * * @return a password. */ public String getKeyPassword() { @@ -201,6 +227,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 +236,7 @@ public void setKeyPassword(final String keyPassword) { /** * Server keychain file name. + * * @return a file name. */ public String getKeyCertChainFile() { @@ -217,6 +245,7 @@ public String getKeyCertChainFile() { /** * Set the server keychain file name. + * * @param keyCertChainFile a file name. */ public void setKeyCertChainFile(final String keyCertChainFile) { @@ -225,6 +254,7 @@ public void setKeyCertChainFile(final String keyCertChainFile) { /** * Server key file name. + * * @return a file name. */ public String getKeyFile() { @@ -233,6 +263,7 @@ public String getKeyFile() { /** * Set the server key file name. + * * @param keyFile a file name. */ public void setKeyFile(final String keyFile) { @@ -241,6 +272,7 @@ public void setKeyFile(final String keyFile) { /** * Server trust certificate collection file name. + * * @return a file name. */ public String getTrustCertCollectionFile() { @@ -249,6 +281,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 +290,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 +299,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,6 +308,7 @@ public void setTlsEnabled(final boolean tlsEnabled) { /** * Check that all the server property values are valid. + * * @throws IllegalArgumentException if any properties are not valid. */ public void validate() { @@ -280,30 +316,37 @@ public void validate() { 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 7c77f5da..8c223fc4 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,21 @@ 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. */ 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 +45,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 +65,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 +74,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 +120,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 +129,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 +144,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 +211,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 +228,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 +238,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 +281,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 +329,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 +528,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 +559,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 +572,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 +584,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 +609,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 +617,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 +627,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 88bf0361..f53d0ad1 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,13 +6,12 @@ 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()); @@ -28,8 +27,8 @@ 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 @@ -43,7 +42,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 aa10efc3..9460dd22 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 a7073d78..df594ed2 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,7 +30,7 @@ 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 */ public void start() throws IOException, InterruptedException { @@ -38,9 +38,7 @@ public void start() throws IOException, InterruptedException { grpcServer.blockUntilShutdown(); } - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ 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 4d6e9c33..bb142337 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,19 @@ 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.Logger; -/** - * 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 +28,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 +42,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,14 +54,18 @@ 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(); + 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()) { + if (chaincodeServerProperties.getKeyPassword() == null + || chaincodeServerProperties.getKeyPassword().isEmpty()) { sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile); } else { - sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword()); + sslContextBuilder = SslContextBuilder.forServer( + keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword()); } ApplicationProtocolConfig apn = new ApplicationProtocolConfig( @@ -74,7 +76,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP sslContextBuilder.applicationProtocolConfig(apn); if (chaincodeServerProperties.getTrustCertCollectionFile() != null) { - final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile()).toFile(); + final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile()) + .toFile(); sslContextBuilder.clientAuth(ClientAuth.REQUIRE); sslContextBuilder.trustManager(trustCertCollectionFile); } @@ -83,7 +86,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP } LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>:\n"); - LOGGER.info("ServerAddress:" + chaincodeServerProperties.getServerAddress().toString()); + LOGGER.info( + "ServerAddress:" + chaincodeServerProperties.getServerAddress().toString()); LOGGER.info("MaxInboundMetadataSize:" + chaincodeServerProperties.getMaxInboundMetadataSize()); LOGGER.info("MaxInboundMessageSize:" + chaincodeServerProperties.getMaxInboundMessageSize()); LOGGER.info("MaxConnectionAgeSeconds:" + chaincodeServerProperties.getMaxConnectionAgeSeconds()); @@ -107,14 +111,12 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP */ 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"); + NettyGrpcServer.this.stop(); + System.err.println("*** server shut down"); + })); server.start(); } @@ -128,9 +130,7 @@ public void blockUntilShutdown() throws InterruptedException { server.awaitTermination(); } - /** - * shutdown now grpc server. - */ + /** shutdown now grpc server. */ 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 c46e1a78..bd6ee06e 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); } @@ -100,7 +95,5 @@ public static Chaincode.Response newErrorResponse(final Throwable throwable) { message = "Unexpected error"; return ResponseUtils.newErrorResponse(message, payload); } - - } } 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 a7b25020..c390ef90 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,17 +47,11 @@ public interface StateBasedEndorsement { */ List listOrgs(); - /** - * RoleType of an endorsement policy's identity. - */ + /** RoleType of an endorsement policy's identity. */ 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 final String val; @@ -69,10 +60,7 @@ enum RoleType { this.val = val; } - /** - * - * @return String value - */ + /** @return String value */ public String getVal() { return val; } @@ -86,7 +74,6 @@ public String getVal() { } /** - * * @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 da1db8ca..f93fc6ce 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,16 +7,11 @@ 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; - /** - * - * @return Endorsement Factory - */ + /** @return Endorsement Factory */ public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); @@ -25,8 +20,8 @@ public static synchronized StateBasedEndorsementFactory getInstance() { } /** - * 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 6dbdbd26..68a67369 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,11 +21,7 @@ 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); @@ -44,7 +40,6 @@ public final class StateBasedEndorsementImpl implements StateBasedEndorsement { } catch (final InvalidProtocolBufferException e) { throw new IllegalArgumentException("error unmarshalling endorsement policy bytes", e); } - } @Override @@ -81,7 +76,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) { @@ -102,15 +99,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 4234a70c..845056bc 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 f4f3bb51..329c3a35 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 50735e07..15c86c68 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 8cafebdb..b2c3c916 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,27 +9,22 @@ 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.util.concurrent.ArrayBlockingQueue; 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.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. */ public class ChaincodeInvocationTask implements Callable { private static Logger logger = Logger.getLogger(ChaincodeInvocationTask.class.getName()); @@ -51,17 +46,16 @@ public class ChaincodeInvocationTask implements Callable { 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,9 +65,7 @@ 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 public ChaincodeMessage call() { ChaincodeMessage finalResponseMessage; @@ -95,7 +87,6 @@ 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); // Call chaincode's invoke @@ -110,24 +101,27 @@ public ChaincodeMessage call() { 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); + 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()); } @@ -165,11 +159,11 @@ public boolean equals(final ChaincodeInvocationTask task) { } /** - * 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,17 +176,16 @@ 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) { @@ -220,12 +213,12 @@ protected ByteString invoke(final ChaincodeMessage message) { logger.severe(() -> String.format("[%-8.8s] Unsuccessful response received.", txId)); throw new RuntimeException(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 RuntimeException(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 831e2277..651bc81a 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,170 @@ 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() {} + + 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, 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()); + } + + 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 newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } - protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message) { + protected 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) { + protected 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); + 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; } - protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { + protected 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(); + 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) { + protected 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, + protected 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 7216ad30..d3a6190d 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,21 +5,19 @@ */ 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 { @@ -29,9 +27,7 @@ public class ChaincodeSupportClient { 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 +37,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 +52,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"); } @@ -110,6 +102,7 @@ public void accept(final ChaincodeMessage t) { /** * 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 08783272..809b36a5 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,9 @@ 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.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; @@ -25,28 +28,27 @@ 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 +57,6 @@ 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; - class InvocationStubImpl implements ChaincodeStub { private static final String UNSPECIFIED_START_KEY = new String(Character.toChars(0x000001)); @@ -79,7 +77,6 @@ class InvocationStubImpl implements ChaincodeStub { private ChaincodeEvent event; /** - * * @param message * @param handler * @throws InvalidProtocolBufferException @@ -93,7 +90,8 @@ 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 == null + || this.signedProposal.getProposalBytes().isEmpty()) { this.creator = null; this.txTimestamp = null; this.transientMap = Collections.emptyMap(); @@ -105,8 +103,8 @@ class InvocationStubImpl implements ChaincodeStub { final ChannelHeader channelHeader = ChannelHeader.parseFrom(header.getChannelHeader()); validateProposalType(channelHeader); final SignatureHeader signatureHeader = SignatureHeader.parseFrom(header.getSignatureHeader()); - final ChaincodeProposalPayload chaincodeProposalPayload = ChaincodeProposalPayload - .parseFrom(proposal.getPayload()); + final ChaincodeProposalPayload chaincodeProposalPayload = + ChaincodeProposalPayload.parseFrom(proposal.getPayload()); final Timestamp timestamp = channelHeader.getTimestamp(); this.txTimestamp = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); @@ -124,8 +122,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,12 +131,12 @@ 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 RuntimeException(String.format( + "Unexpected transaction type: %s", HeaderType.forNumber(channelHeader.getType()))); } } @@ -168,7 +166,9 @@ public void setEvent(final String name, final byte[] payload) { 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,23 +192,26 @@ 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 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) { @@ -217,7 +220,6 @@ public byte[] getStateValidationParameter(final String key) { } return null; - } @Override @@ -230,8 +232,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,19 +259,22 @@ 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, queryResultBytesToKv.andThen(KeyValueImpl::new)); } private final Function queryResultBytesToKv = new Function() { @@ -281,12 +286,11 @@ public KV apply(final QueryResultBytes queryResultBytes) { 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 +304,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, queryResultBytesToKv.andThen(KeyValueImpl::new)); } @Override @@ -337,8 +347,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 +378,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 +400,82 @@ 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, queryResultBytesToKv.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, queryResultBytesToKv.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, + return new QueryResultsIteratorImpl( + this.handler, + channelId, + txId, + response, queryResultBytesToKeyModification.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); - } - } - }; + 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,10 +484,13 @@ 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(); } @@ -465,16 +499,18 @@ public byte[] getPrivateDataHash(final String collection, final String key) { 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) { @@ -489,16 +525,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 +546,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 +578,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 +595,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,26 +608,30 @@ 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, queryResultBytesToKv.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()) { @@ -600,11 +644,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(Collectors.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,14 +659,15 @@ 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(), + 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()); } else { // error @@ -630,7 +677,6 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List } catch (final InvalidProtocolBufferException e) { throw new RuntimeException(e); } - } @Override 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 97d68fbd..c2402e48 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,13 @@ 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()); /** - * * @param corePoolSize * @param maximumPoolSize * @param keepAliveTime @@ -33,8 +27,14 @@ 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"); @@ -46,7 +46,6 @@ public InvocationTaskExecutor(final int corePoolSize, final int maximumPoolSize, 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 424f3a84..2de85597 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 @@ -22,7 +22,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,13 +30,10 @@ 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. */ public final class InvocationTaskManager { @@ -47,7 +43,7 @@ public final class InvocationTaskManager { /** * Get an instance of the Invocation Task Manager. * - * @param chaincode Chaincode Instance + * @param chaincode Chaincode Instance * @param chaincodeId ID of the chaincode * @return InvocationTaskManager */ @@ -84,7 +80,6 @@ public Thread newThread(final Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName("fabric-txinvoke:" + next.incrementAndGet()); return thread; - } }; @@ -102,7 +97,7 @@ public Thread newThread(final Runnable r) { /** * New InvocationTaskManager. * - * @param chaincode Chaincode Instance + * @param chaincode Chaincode Instance * @param chaincodeId ID of the chaincode */ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId) { @@ -128,11 +123,10 @@ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID ch logger.info(() -> "Keep Alive Time [TP_KEEP_ALIVE_MS]" + keepAliveTime); workQueue = new LinkedBlockingQueue(queueSize); - taskService = new InvocationTaskExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, - threadFactory, handler); + taskService = new InvocationTaskExecutor( + corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); Metrics.getProvider().setTaskMetricsCollector(taskService); - } /** @@ -145,35 +139,38 @@ public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws I if (chaincodeMessage == null) { 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", + 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)); + 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())); + 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)); + 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", + logger.warning(() -> String.format( + "[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } @@ -187,8 +184,7 @@ public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws I } /** - * 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 @@ -205,15 +201,14 @@ 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("[%-8.8s] Received %s: cannot handle", 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 */ @@ -233,8 +228,8 @@ private void sendToTask(final ChaincodeMessage message) { 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"); + final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage( + message.getChannelId(), message.getTxid(), "Failed to send response to task"); this.outgoingMessage.accept(m); } } @@ -243,14 +238,13 @@ private void sendToTask(final ChaincodeMessage message) { * 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); @@ -260,9 +254,11 @@ private void newTask(final ChaincodeMessage message, final Type type) { // 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 @@ -281,11 +277,10 @@ private void newTask(final ChaincodeMessage message, final Type type) { // 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); } - } /** @@ -320,9 +315,7 @@ public InvocationTaskManager register() throws IllegalArgumentException { private static final int SHUTDOWN_TIMEOUT = 60; - /** - * - */ + /** */ public void shutdown() { // Recommended shutdown process from // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html @@ -345,5 +338,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 42f77f73..2cecbf97 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,12 +5,10 @@ */ 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; @@ -21,7 +19,8 @@ public final class KeyModificationImpl implements KeyModification { 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(); } @@ -87,5 +86,4 @@ public boolean equals(final Object obj) { } return true; } - } 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 df9903cb..dbf1089f 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; @@ -64,5 +63,4 @@ public boolean equals(final Object obj) { } return true; } - } 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 a319d84b..874ae4f7 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,12 @@ 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.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 +22,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 */ @@ -44,7 +41,11 @@ class QueryResultsIteratorImpl implements QueryResultsIterator { private QueryResponse currentQueryResponse; private 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 { @@ -83,8 +84,12 @@ 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 { @@ -96,22 +101,23 @@ public T next() { // 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 93b349db..26d24f55 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,41 +6,42 @@ package org.hyperledger.fabric.shim.impl; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; 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 { +public final class QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl + implements QueryResultsIteratorWithMetadata { private static Logger logger = Logger.getLogger(QueryResultsIteratorWithMetadataImpl.class.getName()); private 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); 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 ee6912ed..1147f629 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 8b47b39e..32335315 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 @@ -21,9 +21,7 @@ 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; @@ -31,7 +29,6 @@ public class CompositeKey { private final String compositeKey; /** - * * @param objectType * @param attributes */ @@ -40,7 +37,6 @@ public CompositeKey(final String objectType, final String... attributes) { } /** - * * @param objectType * @param attributes */ @@ -53,32 +49,23 @@ public CompositeKey(final String objectType, final List attributes) { this.compositeKey = 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; } /** - * * @param compositeKey * @return Composite Key */ @@ -95,9 +82,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 +110,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 80081c91..b5c45cfa 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 ed1ee601..e47b1e4a 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 8ea4e804..2fd3f337 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 2986f169..28ba7b28 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,18 @@ */ 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,13 +27,9 @@ public final class Traces { private static TracesProvider provider; - - private Traces() { - - } + private Traces() {} /** - * * @param props the configuration of the chaincode * @return The traces provider */ @@ -46,32 +41,32 @@ 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) { + } catch (ClassNotFoundException + | InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException + | NoSuchMethodException + | SecurityException e) { throw new RuntimeException("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 16712059..2083b4e9 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 { @@ -36,22 +31,23 @@ public interface TracesProvider { * * @param props */ - default void initialize(final Properties props) { - }; + default void initialize(final Properties props) {} + ; /** * 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 1ea5b982..0153cc9c 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 15818d5e..fa851edd 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 38c0fb72..7afa5c48 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; @@ -20,6 +18,7 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import javax.annotation.Nullable; final class OpenTelemetryProperties implements ConfigProperties { private final Map config; @@ -34,14 +33,12 @@ final class OpenTelemetryProperties implements ConfigProperties { } @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; @@ -50,8 +47,7 @@ public Boolean getBoolean(final String name) { } @Override - @Nullable - @SuppressWarnings("UnusedException") + @Nullable @SuppressWarnings("UnusedException") public Integer getInt(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { @@ -65,8 +61,7 @@ public Integer getInt(final String name) { } @Override - @Nullable - @SuppressWarnings("UnusedException") + @Nullable @SuppressWarnings("UnusedException") public Long getLong(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { @@ -80,8 +75,7 @@ public Long getLong(final String name) { } @Override - @Nullable - @SuppressWarnings("UnusedException") + @Nullable @SuppressWarnings("UnusedException") public Double getDouble(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { @@ -95,8 +89,7 @@ public Double getDouble(final String name) { } @Override - @Nullable - @SuppressWarnings("UnusedException") + @Nullable @SuppressWarnings("UnusedException") public Duration getDuration(final String name) { String value = config.get(name); if (value == null || value.isEmpty()) { @@ -110,12 +103,7 @@ public Duration getDuration(final String name) { return Duration.ofMillis(TimeUnit.MILLISECONDS.convert(rawNumber, unit)); } catch (NumberFormatException ex) { throw new ConfigurationException( - "Invalid duration property " - + name - + "=" - + value - + ". Expected number, found: " - + numberString); + "Invalid duration property " + name + "=" + value + ". Expected number, found: " + numberString); } catch (ConfigurationException ex) { throw new ConfigurationException( "Invalid duration property " + name + "=" + value + ". " + ex.getMessage()); @@ -135,20 +123,16 @@ public List getList(final String name) { 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( @@ -158,14 +142,12 @@ private static ConfigurationException newInvalidPropertyException( } 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 */ @@ -191,6 +173,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 696aecec..4801ebe3 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 @@ -13,14 +13,12 @@ import io.opentelemetry.context.Context; 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 io.opentelemetry.semconv.ServiceAttributes; 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 { @@ -34,7 +32,7 @@ public final class OpenTelemetryTracesProvider implements TracesProvider { @Override public void initialize(final Properties props) { String serviceName = props.getProperty(CORE_CHAINCODE_ID_NAME, "unknown"); - props.setProperty(ResourceAttributes.SERVICE_NAME.getKey(), serviceName); + props.setProperty(ServiceAttributes.SERVICE_NAME.getKey(), serviceName); OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.builder() .addPropertiesSupplier(() -> getOpenTelemetryProperties(props)) 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 b8aef10b..dd29ef78 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 07ffd3ee..147b5795 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 f62b044c..a97b3071 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,14 +18,6 @@
 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 {
     private ChaincodeMockPeer server;
 
@@ -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 b2c3bc7f..7f2a16f5 100644
--- a/fabric-chaincode-shim/src/test/java/contract/Greeting.java
+++ b/fabric-chaincode-shim/src/test/java/contract/Greeting.java
@@ -60,11 +60,9 @@ public static void validate(final Greeting greeting) {
         if (text.split(" ").length != greeting.wordCount) {
             throw new Error("Word count incorrectly set");
         }
-
     }
 
     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 c10b4154..a28a2924 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,12 @@
 
 @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"))
 @Default()
 public class SampleContract implements ContractInterface {
     public static int getBeforeInvoked() {
@@ -127,9 +124,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 +145,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 cd99c74c..62751cef 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
@@ -29,7 +29,6 @@ public void testContractException() {
 
         logger.error("all gone wrong");
         logger.error(() -> "all gone wrong");
-
     }
 
     @Test
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 6c69de43..c4b22d47 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,16 +5,15 @@
  */
 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 static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.hamcrest.CoreMatchers;
+import org.junit.jupiter.api.Test;
 
 public final class LoggingTest {
     @Test
@@ -37,11 +36,13 @@ public Object proxyMapLevel(final Object... args) {
             final Method m = Logging.class.getDeclaredMethod("mapLevel", String.class);
             m.setAccessible(true);
             return m.invoke(null, args);
-        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
+        } catch (NoSuchMethodException
+                | SecurityException
+                | IllegalAccessException
+                | IllegalArgumentException
                 | InvocationTargetException e) {
             throw new RuntimeException(e);
         }
-
     }
 
     @Test
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 ee448f66..8c48b8b5 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 {
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 6852d616..86cee5cf 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;
@@ -122,8 +123,14 @@ public void setTheCustomObject(final MyType 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());
+        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
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 dcd7c2ff..0054c1d6 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;
@@ -93,7 +91,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 +109,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 +125,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 +136,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 +147,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 +168,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 +194,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 +235,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() {
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 f9dae17a..9f85095d 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,39 +6,38 @@
 
 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;
 
+import java.math.BigInteger;
+import org.hyperledger.fabric.TestUtil;
+import org.hyperledger.fabric.shim.ChaincodeStub;
+import org.junit.jupiter.api.Test;
+
 public class ClientIdentityTest {
-    /**
-     * Test client identity can be created using certificate without attributes
-     */
+    /** Test client identity can be created using certificate without attributes */
     @Test
     public 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 {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
@@ -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 {
         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,30 +74,31 @@ 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 {
         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() {
         final ChaincodeStub stub = mock(ChaincodeStub.class);
@@ -106,18 +107,15 @@ public void catchInvalidProtocolBufferException() {
         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 {
         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 a10ef5de..d0c6c393 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,15 +5,14 @@
  */
 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;
+
+import java.util.Collections;
+import org.hyperledger.fabric.shim.ChaincodeStub;
+import org.junit.jupiter.api.Test;
 
 public class ContextFactoryTest {
 
@@ -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 2d3bf088..405e68ff 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,17 +5,15 @@
  */
 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 {
 
-    /**
-     * Test creating a new context returns what we expect
-     */
+    /** Test creating a new context returns what we expect */
     @Test
     public void getInstance() {
         final ChaincodeStub stub = new ChaincodeStubNaiveImpl();
@@ -24,14 +22,11 @@ public void getInstance() {
         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() {
         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 a3b468fe..e3fcdd6a 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,25 @@
  */
 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;
+
+import org.hyperledger.fabric.shim.ChaincodeException;
+import org.junit.jupiter.api.Test;
 
 public class ContractInterfaceTest {
     @Test
     public void createContext() {
-        assertThat((new ContractInterface() {
-        }).createContext(new ChaincodeStubNaiveImpl()), is(instanceOf(Context.class)));
+        assertThat(
+                (new ContractInterface() {}).createContext(new ChaincodeStubNaiveImpl()),
+                is(instanceOf(Context.class)));
     }
 
     @Test
     public void unknownTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+        final ContractInterface c = new ContractInterface() {};
 
         assertThatThrownBy(() -> c.unknownTransaction(c.createContext(new ChaincodeStubNaiveImpl())))
                 .isInstanceOf(ChaincodeException.class)
@@ -32,16 +32,14 @@ public void unknownTransaction() {
 
     @Test
     public void beforeTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+        final ContractInterface c = new ContractInterface() {};
 
         c.beforeTransaction(c.createContext(new ChaincodeStubNaiveImpl()));
     }
 
     @Test
     public void afterTransaction() {
-        final ContractInterface c = new ContractInterface() {
-        };
+        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 987922f5..b5692cc2 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,23 +28,10 @@
 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 {
     @Test
     public void testCreateFailsWithoutValidOptions() {
-        assertThatThrownBy(() -> new ContractRouter(new String[]{}))
+        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.");
@@ -40,7 +39,7 @@ public void testCreateFailsWithoutValidOptions() {
 
     @Test
     public void testCreateAndScan() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -50,7 +49,9 @@ 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))));
@@ -58,7 +59,7 @@ public void testCreateAndScan() {
 
     @Test
     public void testInit() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        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"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -136,7 +134,7 @@ public void testInvokeTwoTxnsThatExist() {
 
     @Test
     public void testInvokeTxnWithDefinedName() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        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"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -213,7 +209,7 @@ public void testInvokeTwoTxnsWithDefaultNamespace() {
 
     @Test
     public void testInvokeTxnWithDefinedNameUsingMethodName() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -240,7 +236,7 @@ public void testInvokeTxnWithDefinedNameUsingMethodName() {
 
     @Test
     public void testInvokeContractThatDoesNotExist() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -267,7 +263,7 @@ public void testInvokeContractThatDoesNotExist() {
 
     @Test
     public void testInvokeTxnThatDoesNotExist() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -294,7 +290,7 @@ public void testInvokeTxnThatDoesNotExist() {
 
     @Test
     public void testInvokeTxnThatReturnsNullString() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"});
         r.findAllContracts();
         final ChaincodeStub s = new ChaincodeStubNaiveImpl();
 
@@ -321,7 +317,7 @@ public void testInvokeTxnThatReturnsNullString() {
 
     @Test
     public void testInvokeTxnThatThrowsAnException() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        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));
@@ -348,7 +343,7 @@ public void testInvokeTxnThatThrowsAnException() {
 
     @Test
     public void testInvokeTxnThatThrowsAChaincodeException() {
-        final ContractRouter r = new ContractRouter(new String[]{"-a", "127.0.0.1:7052", "-i", "testId"});
+        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,9 +367,7 @@ public void testInvokeTxnThatThrowsAChaincodeException() {
         assertThat(SampleContract.getDoWorkInvoked(), is(0));
     }
 
-    /**
-     * Test confirming ContractRuntimeExceptions can be created.
-     */
+    /** Test confirming ContractRuntimeExceptions can be created. */
     @Test
     public void createContractRuntimeExceptions() {
         final ContractRuntimeException cre1 = new ContractRuntimeException("failure");
@@ -387,17 +379,17 @@ public void createContractRuntimeExceptions() {
     public 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);
@@ -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 956f774a..893aa81e 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;
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 53cc5fcc..9da03bbc 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 edd4e799..3cc4df28 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,12 +5,12 @@
  */
 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;
+
+import org.hyperledger.fabric.shim.ChaincodeException;
+import org.junit.jupiter.api.Test;
 
 public class TransactionExceptionTest {
 
@@ -71,7 +71,8 @@ public void testMessageAndPayloadArgConstructor() {
 
     @Test
     public void testMessagePayloadAndCauseArgConstructor() {
-        final ChaincodeException e = new ChaincodeException("Failure", new byte[] {'P', 'a', 'y', 'l', 'o', 'a', 'd'}, new Error("Cause"));
+        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"));
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 cbf1f2ce..67d006d3 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 {
     @Test
     public void noReturnValue()
-            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
+            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
+                    SecurityException {
         JSONTransactionSerializer jts = new JSONTransactionSerializer();
         SerializerRegistryImpl serializerRegistry = spy(new SerializerRegistryImpl());
         ContractExecutionService ces = new ContractExecutionService(serializerRegistry);
@@ -51,18 +51,19 @@ public void noReturnValue()
 
         when(txFn.getRouting()).thenReturn(routing);
         when(req.getArgs()).thenReturn(new ArrayList());
-        when(routing.getMethod()).thenReturn(SampleContract.class.getMethod("noReturn", new Class[] {Context.class}));
+        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 {
+            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");
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 169ad41f..eb15c8c9 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;
@@ -224,7 +223,6 @@ 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
@@ -279,8 +277,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 8204b343..903a287f 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,10 @@
 package org.hyperledger.fabric.contract.metadata;
 
 import contract.SampleContract;
+import java.io.InputStream;
+import java.io.Serializable;
+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,19 +22,20 @@
 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"
+            + "       \"$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" + "";
 
     // fields are private, so use reflection to bypass this for unit testing
@@ -53,7 +58,6 @@ public void beforeAndAfterEach() {
         setMetadataBuilderField("contractMap", new HashMap>());
         setMetadataBuilderField("overallInfoMap", new HashMap());
         setMetadataBuilderField("schemaClient", new DefaultSchemaClient());
-
     }
 
     @Test
@@ -74,9 +78,7 @@ public void defaultSchemasNotLoadedFromNetwork() {
             public InputStream get(final String uri) {
                 throw new RuntimeException("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 d06e6d6d..4139c165 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;
@@ -21,8 +21,7 @@
 public class TypeSchemaTest {
 
     @BeforeEach
-    public void beforeEach() {
-    }
+    public void beforeEach() {}
 
     @Test
     public void putIfNotNull() {
@@ -90,8 +89,7 @@ public void getItems() {
     }
 
     @DataType
-    class MyType {
-    }
+    class MyType {}
 
     @Test
     public void getTypeClass() {
@@ -138,7 +136,6 @@ public void getTypeClass() {
         array.put("type", "array");
         array.put("items", ts);
         assertThat(array.getTypeClass(mockRegistry), equalTo(MyType[].class));
-
     }
 
     @Test
@@ -188,7 +185,6 @@ public void typeConvertPrimitives() {
 
         rts = TypeSchema.typeConvert(boolean.class);
         assertThat(rts.getType(), equalTo("boolean"));
-
     }
 
     @Test
@@ -235,6 +231,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 0a564013..a948720c 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,7 +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.equalTo;
+import static org.hamcrest.Matchers.startsWith;
+
 import contract.SampleContract;
+import java.lang.reflect.Method;
+import java.security.Permission;
 import org.hyperledger.fabric.contract.Context;
 import org.hyperledger.fabric.contract.ContractInterface;
 import org.hyperledger.fabric.contract.ContractRuntimeException;
@@ -14,14 +21,6 @@
 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 {
     @Test
     public void constructor() throws NoSuchMethodException, SecurityException {
@@ -31,9 +30,7 @@ public void constructor() throws NoSuchMethodException, SecurityException {
     }
 
     @Contract(name = "", info = @Info())
-    public class FailureTestObject {
-
-    }
+    public class FailureTestObject {}
 
     private boolean fail;
     private final int step = 1;
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 015357ec..f08e3bd4 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,17 +5,16 @@
  */
 package org.hyperledger.fabric.contract.routing;
 
-import org.hyperledger.fabric.contract.MyType2;
-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;
 
+import java.util.Map;
+import org.hyperledger.fabric.contract.MyType2;
+import org.hyperledger.fabric.contract.routing.impl.DataTypeDefinitionImpl;
+import org.junit.jupiter.api.Test;
+
 public class DataTypeDefinitionTest {
     @Test
     public void constructor() {
@@ -38,7 +37,5 @@ public void constructor() {
         assertThat(ts, hasEntry("required", new String[] {"true", "false"}));
         assertThat(ts, hasEntry("enum", new String[] {"a", "bee", "cee", "dee"}));
         assertThat(ts, hasEntry("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 823dd06f..84524443 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 {
     @Test
     public void constructor() throws NoSuchMethodException, SecurityException {
-        final Parameter[] params = String.class.getMethod("concat", String.class).getParameters();
+        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 28cd785e..9ec68a68 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,15 +5,14 @@
  */
 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 {
     @Test
     public void constructor() throws NoSuchMethodException, SecurityException {
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 1096ceac..428a9483 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,32 +24,18 @@
 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 {
     @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
@@ -50,7 +44,8 @@ public void constructor() throws NoSuchMethodException, SecurityException {
         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");
 
@@ -62,7 +57,8 @@ public 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");
 
@@ -76,7 +72,6 @@ public void property() throws NoSuchMethodException, SecurityException {
         final TypeSchema rts = txfn.getReturnSchema();
         System.out.println(ts);
         assertEquals(ts, rts);
-
     }
 
     @Test
@@ -88,5 +83,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 0fc5f419..16c59648 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,15 +5,14 @@
  */
 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 {
     @Test
     public void addDataType() {
@@ -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 2286435d..489919d4 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,15 +30,6 @@
 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 {
     @SystemStub
@@ -73,7 +72,8 @@ public ChaincodeMessage newInvokeFn(final String[] 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 {
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 daa3a511..42800291 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
@@ -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 b57c9e5c..eb562ade 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,7 +10,6 @@
 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;
@@ -21,18 +20,13 @@ public class MetricsTest {
 
     public static class TestProvider implements MetricsProvider {
 
-        public TestProvider() {
-
-        }
+        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
@@ -51,9 +45,12 @@ public void metricsEnabledUnknownProvider() {
             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
@@ -63,7 +60,6 @@ public void metricsNoProvider() {
 
             final MetricsProvider provider = Metrics.initialize(props);
             assertTrue(provider instanceof DefaultProvider);
-
         }
 
         @Test
@@ -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 985e4be4..0da931aa 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,7 +13,6 @@
 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;
@@ -84,10 +83,11 @@ public int getActiveCount() {
             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 6fd7ef03..7cd97a1a 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,18 +33,6 @@
 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 {
     @SystemStub
@@ -42,81 +41,115 @@ public class ChaincodeBaseTest {
     @Test
     public 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);
+        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);
+        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);
+        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() {
         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);
+        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);
+        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);
+        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);
+        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);
+        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();
     }
@@ -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,
+    public 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);
@@ -302,19 +339,13 @@ public void connectChaincodeBase() throws IOException {
 
         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");
@@ -324,12 +355,9 @@ public void onCompleted() {
 
     @Test
     public void connectChaincodeBaseNull() {
-        Assertions.assertThrows(
-                IllegalArgumentException.class,
-                () -> {
-                    final ChaincodeBase cb = new EmptyChaincode();
-                    cb.connectToPeer(null);
-                }
-        );
+        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 8b52bbfd..3ab40706 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,9 +17,6 @@
 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 {
     @SystemStub
@@ -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 37b8db4d..ccf3185a 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;
@@ -102,8 +101,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 +114,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 +127,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 +152,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 +206,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,7 +286,6 @@ public String getMspId() {
             // TODO Auto-generated method stub
             return null;
         }
-
     }
 
     @Test
@@ -300,5 +303,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 800ec670..7b70b388 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,17 +5,17 @@
  */
 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;
 
+import java.nio.charset.StandardCharsets;
+import org.junit.jupiter.api.Test;
+
 public 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));
+        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());
@@ -23,7 +23,8 @@ public void testResponse() {
 
     @Test
     public void testResponseWithCode() {
-        Chaincode.Response resp = new Chaincode.Response(200, "No message", "no payload".getBytes(StandardCharsets.UTF_8));
+        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,8 +35,11 @@ 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());
@@ -43,11 +47,16 @@ public void testResponseWithCode() {
 
     @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);
+        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 5e7108f3..d3832502 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,25 @@
  */
 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.Collectors;
+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 +41,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 {
     private static final String TEST_CHANNEL = "testChannel";
+
     @SystemStub
     private final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
@@ -75,8 +75,7 @@ void initNull() throws IOException {
                 () -> {
                     ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(null);
                 },
-                "chaincodeBase can't be null"
-        );
+                "chaincodeBase can't be null");
     }
 
     @Test
@@ -112,21 +111,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
@@ -154,41 +149,50 @@ void connectAndReceiveRegister() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
-            @Override
-            public void onNext(final ChaincodeMessage value) {
-                assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
-                assertEquals("\u0012\u0004mycc", value.getPayload().toStringUtf8());
-            }
-
-            @Override
-            public void onError(final Throwable t) {
-                assertNull(t);
-            }
-
-            @Override
-            public void onCompleted() {
-            }
-        });
+        final StreamObserver connect =
+                chatChaincodeWithPeer.connect(new StreamObserver() {
+                    @Override
+                    public void onNext(final ChaincodeMessage value) {
+                        assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
+                        assertEquals("\u0012\u0004mycc", value.getPayload().toStringUtf8());
+                    }
+
+                    @Override
+                    public void onError(final Throwable t) {
+                        assertNull(t);
+                    }
+
+                    @Override
+                    public void onCompleted() {}
+                });
         assertNotNull(connect);
 
         final ByteString payload = org.hyperledger.fabric.protos.peer.ChaincodeInput.newBuilder()
-                .addArgs(ByteString.copyFromUtf8("")).build()
+                .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(Collectors.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) {
@@ -196,16 +200,24 @@ public void onCompleted() {
         }
 
         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(Collectors.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,22 +237,22 @@ void connectAndReceiveRegisterComplete() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
-            @Override
-            public void onNext(final ChaincodeMessage value) {
-                assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
-                assertEquals("\u0012\u0004mycc", value.getPayload().toStringUtf8());
-            }
-
-            @Override
-            public void onError(final Throwable t) {
-                assertNull(t);
-            }
-
-            @Override
-            public void onCompleted() {
-            }
-        });
+        final StreamObserver connect =
+                chatChaincodeWithPeer.connect(new StreamObserver() {
+                    @Override
+                    public void onNext(final ChaincodeMessage value) {
+                        assertEquals(ChaincodeMessage.Type.REGISTER, value.getType());
+                        assertEquals("\u0012\u0004mycc", value.getPayload().toStringUtf8());
+                    }
+
+                    @Override
+                    public void onError(final Throwable t) {
+                        assertNull(t);
+                    }
+
+                    @Override
+                    public void onCompleted() {}
+                });
         connect.onCompleted();
     }
 
@@ -256,19 +268,17 @@ void connectAndReceiveRegisterException() throws IOException {
         Metrics.initialize(props);
 
         ChatChaincodeWithPeer chatChaincodeWithPeer = new ChatChaincodeWithPeer(chaincodeBase);
-        final StreamObserver connect = chatChaincodeWithPeer.connect(new StreamObserver() {
-            @Override
-            public void onNext(final ChaincodeMessage value) {
-            }
+        final StreamObserver connect =
+                chatChaincodeWithPeer.connect(new StreamObserver() {
+                    @Override
+                    public void onNext(final ChaincodeMessage value) {}
 
-            @Override
-            public void onError(final Throwable t) {
-            }
+                    @Override
+                    public void onError(final Throwable t) {}
 
-            @Override
-            public void onCompleted() {
-            }
-        });
+                    @Override
+                    public void onCompleted() {}
+                });
         connect.onError(new Exception("some_error"));
     }
 
@@ -287,24 +297,21 @@ void connectOnCompletedException() throws IOException {
 
         Assertions.assertDoesNotThrow(
                 () -> {
-                    final StreamObserver connect = chatChaincodeWithPeer
-                            .connect(new StreamObserver() {
-                        @Override
-                        public void onNext(final ChaincodeMessage value) {
-                        }
-
-                        @Override
-                        public void onError(final Throwable t) {
-                        }
-
-                        @Override
-                        public void onCompleted() {
-                            throw new RuntimeException("some_error");
-                        }
-                    });
+                    final StreamObserver connect =
+                            chatChaincodeWithPeer.connect(new StreamObserver() {
+                                @Override
+                                public void onNext(final ChaincodeMessage value) {}
+
+                                @Override
+                                public void onError(final Throwable t) {}
+
+                                @Override
+                                public void onCompleted() {
+                                    throw new RuntimeException("some_error");
+                                }
+                            });
                 },
-                "some_error"
-        );
+                "some_error");
     }
 
     @Test
@@ -318,16 +325,13 @@ void testMockChaincodeBase() throws IOException {
 
         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() {}
         }));
     }
 
@@ -344,8 +348,7 @@ void testMockChaincodeBaseThrowIOException() throws IOException {
 
         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 +356,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 c14163e7..87e8474e 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,10 +20,6 @@
 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 {
     @SystemStub
@@ -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 d1d23adb..3983ce57 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;
 
+import org.junit.jupiter.api.Test;
+
 public class StateBasedEndorsementTest {
     @Test
     public void testRoleType() {
-        assertThat(StateBasedEndorsement.RoleType.forVal("MEMBER")).isEqualTo(StateBasedEndorsement.RoleType.RoleTypeMember);
-        assertThat(StateBasedEndorsement.RoleType.forVal("PEER")).isEqualTo(StateBasedEndorsement.RoleType.RoleTypePeer);
+        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 08896e60..750e24f0 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,12 +5,11 @@
  */
 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 {
     @Test
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 332fa347..195a672e 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;
 
+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;
+
 public class StateBasedEndorsementImplTest {
 
     @Test
     public 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() {
 
-        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);
+        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 0ebd3c6b..490be49b 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,25 +60,6 @@
 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 {
 
@@ -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);
 
@@ -109,9 +108,10 @@ 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);
+                .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);
@@ -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);
 
@@ -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,22 +253,22 @@ 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
@@ -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,16 +340,14 @@ 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
@@ -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,16 +415,14 @@ 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
@@ -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,9 +486,7 @@ 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
@@ -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);
@@ -540,9 +554,10 @@ 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);
+                .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,19 +575,23 @@ 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"));
     }
 
@@ -595,9 +614,10 @@ 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);
+                .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();
@@ -624,9 +644,10 @@ 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());
     }
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 97da696b..2a7c561e 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,16 +6,15 @@
 
 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 {
 
     private final String txId = "txid";
@@ -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 c3cf24d8..2bdf9c87 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,11 +23,6 @@
 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 {
     @SystemStub
@@ -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 6ef01199..fd51e718 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,12 +27,6 @@
 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 {
     @SystemStub
@@ -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 8d2b4720..b053a869 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;
@@ -41,8 +40,8 @@ class GetStateByRangeTests {
 
         @BeforeEach
         public void beforeEach() throws Exception {
-            final ChaincodeMessage mockMessage = ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "",
-                    "key");
+            final ChaincodeMessage mockMessage =
+                    ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", "key");
             mockHandler = mock(ChaincodeInvocationTask.class);
             final ByteString mockString = QueryResponse.newBuilder().build().toByteString();
 
@@ -105,12 +104,10 @@ public void unbounded() throws InvalidProtocolBufferException {
         @Test
         public 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 ae4ee29a..7fd6b760 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,14 +23,6 @@
 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 {
 
     private InvocationTaskManager itm;
@@ -42,8 +41,7 @@ public void setup() {
 
         perfLogger = LogManager.getLogManager().getLogger("org.hyperledger.Performance");
         perfLogger.setLevel(Level.ALL);
-        this.itm.setResponseConsumer((value) -> {
-        });
+        this.itm.setResponseConsumer((value) -> {});
     }
 
     @AfterEach
@@ -61,51 +59,47 @@ public void register() throws UnsupportedEncodingException {
     @Test
     public 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 {
 
         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 {
 
-        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 {
 
-        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 51fc0193..2dc72dc9 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,14 +6,6 @@
 
 package org.hyperledger.fabric.shim.impl;
 
-import com.google.protobuf.ByteString;
-import com.google.protobuf.Timestamp;
-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;
@@ -23,6 +15,13 @@
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Timestamp;
+import java.time.Instant;
+import java.util.stream.Stream;
+import org.hyperledger.fabric.shim.ledger.KeyModification;
+import org.junit.jupiter.api.Test;
+
 public class KeyModificationImplTest {
 
     @Test
@@ -30,64 +29,66 @@ public 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());
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setTxId("txid")
+                        .build());
         assertThat(km.getTxId(), is(equalTo("txid")));
     }
 
     @Test
     public void testGetValue() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setValue(ByteString.copyFromUtf8("value"))
-                .build());
+        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))));
     }
 
     @Test
     public void testGetStringValue() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setValue(ByteString.copyFromUtf8("value"))
-                .build());
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setValue(ByteString.copyFromUtf8("value"))
+                        .build());
         assertThat(km.getStringValue(), is(equalTo("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());
+        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)));
     }
 
     @Test
     public void testIsDeleted() {
-        Stream.of(true, false)
-                .forEach(b -> {
-                    final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+        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(), is(b));
+        });
     }
 
     @Test
     public void testHashCode() {
-        final KeyModification km = new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
-                .setIsDelete(false)
-                .build());
+        final KeyModification km =
+                new KeyModificationImpl(org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.newBuilder()
+                        .setIsDelete(false)
+                        .build());
 
         int expectedHashCode = 31;
         expectedHashCode = expectedHashCode + 1237;
@@ -96,24 +97,25 @@ public void testHashCode() {
         expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode();
 
         assertEquals(expectedHashCode, km.hashCode(), "Wrong hash code");
-
     }
 
     @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());
+        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));
     }
-
 }
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 216398d6..3b8bbf43 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,17 +6,17 @@
 
 package org.hyperledger.fabric.shim.impl;
 
-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.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.google.protobuf.ByteString;
+import org.hyperledger.fabric.protos.ledger.queryresult.KV;
+import org.junit.jupiter.api.Test;
 
 public class KeyValueImplTest {
 
@@ -57,8 +57,7 @@ public void testGetStringValue() {
 
     @Test
     public void testHashCode() {
-        final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder()
-                .build());
+        final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder().build());
 
         int expectedHashCode = 31;
         expectedHashCode = expectedHashCode + "".hashCode();
@@ -92,7 +91,5 @@ public void testEquals() {
         assertFalse(kv1.equals(kv2));
         assertFalse(kv1.equals(kv3));
         assertTrue(kv1.equals(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 9f312564..3d1b299f 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,25 +6,23 @@
 
 package org.hyperledger.fabric.shim.impl;
 
-import static org.hamcrest.Matchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
 import static org.junit.jupiter.api.Assertions.fail;
 
+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 {
 
     @Test
     public void getMetadata() {
-        final QueryResultsIteratorWithMetadataImpl testIter = new QueryResultsIteratorWithMetadataImpl<>(null, "", "",
-                prepareQueryResponse().toByteString(), queryResultBytesToKv);
+        final QueryResultsIteratorWithMetadataImpl testIter = new QueryResultsIteratorWithMetadataImpl<>(
+                null, "", "", prepareQueryResponse().toByteString(), queryResultBytesToKv);
         assertThat(testIter.getMetadata().getBookmark(), is("asdf"));
         assertThat(testIter.getMetadata().getFetchedRecordsCount(), is(2));
     }
@@ -32,7 +30,8 @@ public void getMetadata() {
     @Test
     public void getInvalidMetadata() {
         try {
-            new QueryResultsIteratorWithMetadataImpl<>(null, "", "", prepareQueryResponseWrongMeta().toByteString(), queryResultBytesToKv);
+            new QueryResultsIteratorWithMetadataImpl<>(
+                    null, "", "", prepareQueryResponseWrongMeta().toByteString(), queryResultBytesToKv);
             fail();
         } catch (final RuntimeException e) {
         }
@@ -55,16 +54,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 2fce7d4f..d2bac2f8 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,6 +13,9 @@
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.is;
 
+import java.util.Arrays;
+import org.junit.jupiter.api.Test;
+
 public class CompositeKeyTest {
     @Test
     public void testValidateSimpleKeys() {
@@ -108,14 +107,15 @@ public void testParseCompositeKey() {
 
     @Test
     public void testParseCompositeKeyInvalidObjectType() {
-        assertThatThrownBy(() -> CompositeKey.parseCompositeKey("ab\udbff\udfffc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))
+        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"))
+        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 badf8ca6..710b9eb0 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,9 +44,7 @@ public ChaincodeMockPeer(final List scenario, final int port) {
         this.server = sb.addService(this.service).build();
     }
 
-    /**
-     * Start serving requests.
-     */
+    /** Start serving requests. */
     public void start() throws IOException {
         server.start();
         LOGGER.info("Server started, listening on " + port);
@@ -65,9 +59,7 @@ public void run() {
         });
     }
 
-    /**
-     * Stop serving requests and shutdown resources.
-     */
+    /** Stop serving requests and shutdown resources. */
     public void stop() {
         if (server != null) {
             server.shutdownNow();
@@ -99,21 +91,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() {
         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;
     }
@@ -161,8 +148,7 @@ 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() {
 
@@ -180,7 +166,8 @@ public void onNext(final ChaincodeMessage 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);
@@ -195,7 +182,8 @@ public void onNext(final ChaincodeMessage chaincodeMessage) {
                                     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++;
                         }
@@ -210,30 +198,30 @@ public void onError(final Throwable throwable) {
                 }
 
                 @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 {
+    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 e) {
+                            }
+                        }
+                    }),
+                    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 625de587..34ea010b 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 95b31012..37ef42b0 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 fae2dd60..96e63c7a 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 813732ee..96e2fcc0 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,7 +25,7 @@ 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;
@@ -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 00207270..2c137d93 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 fc87811d..0acebac6 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 6d085fe5..8419ee2d 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 67070196..6bac3ac3 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 9ca3b547..dceae3b3 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 b048295d..e6eed042 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 156f7353..95d80e03 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 6dc16d47..b96e7425 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 e282b23d..501ed1ce 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 fced5b3e..331b15e3 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 cab82313..26c52724 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,7 +26,7 @@ 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;
@@ -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 81f823bd..25c66c42 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 f913ea6c..d219b405 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 dc0f4fa0..b6ab6a5c 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 6216363d..12836483 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 38bf768a..51e0a1bf 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 {
 
     public 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) {
@@ -55,9 +50,12 @@ public void tracesEnabledUnknownProvider() {
             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
@@ -67,7 +65,6 @@ public void tracesNoProvider() {
 
             final TracesProvider provider = Traces.initialize(props);
             assertTrue(provider instanceof DefaultTracesProvider);
-
         }
 
         @Test
@@ -78,7 +75,6 @@ public void tracesOpenTelemetryProvider() {
 
             final TracesProvider provider = Traces.initialize(props);
             assertTrue(provider instanceof OpenTelemetryTracesProvider);
-
         }
 
         @Test
@@ -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 7740b341..e36075fd 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,13 +5,13 @@
  */
 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 {
 
     @Test
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 fca985db..9c9278be 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,11 +13,20 @@
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+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;
+
 public class OpenTelemetryPropertiesTest {
 
     @Test
     public void testOverrideValue() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "bar"), Collections.singletonMap("foo", "foobar"));
+        OpenTelemetryProperties props = new OpenTelemetryProperties(
+                Collections.singletonMap("foo", "bar"), Collections.singletonMap("foo", "foobar"));
         assertThat(props.getString("foo")).isEqualTo("foobar");
     }
 
@@ -42,7 +42,6 @@ public void testCanGetDurationHours() {
         assertThat(props.getDuration("foo")).isEqualTo(Duration.of(5, HOURS));
     }
 
-
     @Test
     public void testCanGetDurationMinutes() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "5m"));
@@ -87,7 +86,6 @@ public void testGetLong() {
         assertThat(props.getLong("bar")).isNull();
     }
 
-
     @Test
     public void testGetInt() {
         OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "500003"));
@@ -111,7 +109,8 @@ public void testGetList() {
 
     @Test
     public void testGetMap() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "foo=bar,foobar=noes"));
+        OpenTelemetryProperties props =
+                new OpenTelemetryProperties(Collections.singletonMap("foo", "foo=bar,foobar=noes"));
         Map expected = new HashMap<>();
         expected.put("foo", "bar");
         expected.put("foobar", "noes");
@@ -120,7 +119,8 @@ public void testGetMap() {
 
     @Test
     public void testGetMapInvalid() {
-        OpenTelemetryProperties props = new OpenTelemetryProperties(Collections.singletonMap("foo", "foo/bar,foobar/noes"));
+        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 7b03a3f2..6aeda3e8 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,13 +37,6 @@
 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 {
 
     private final class ContextGetterChaincode extends ChaincodeBase {
@@ -58,7 +57,6 @@ public Properties getChaincodeConfig() {
         }
     }
 
-
     @Test
     public void testProvider() {
         OpenTelemetryTracesProvider provider = new OpenTelemetryTracesProvider();
@@ -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 2bfa9bd6..5baa2ff9 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;
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 00000000..1dc4fe86
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,5 @@
+[versions]
+spotless = "6.25.0"
+
+[plugins]
+spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index d64cd491..a4b76b95 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 0aaefbca..df97d72b 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.10.2-bin.zip
 networkTimeout=10000
 validateDistributionUrl=true
 zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
index 1aa94a42..f5feea6d 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 7101f8e4..9b42019c 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/settings.gradle b/settings.gradle
index c384cfad..3837c43e 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'