mirror of
https://github.com/hyperledger/fabric-samples.git
synced 2026-06-17 07:25:10 +00:00
client java application using gateway api in java sdk (#572)
* Added for client java application using gateway api in java sdk Signed-off-by: deeptiraom <41100100+deeptiraom@users.noreply.github.com> * removed eclipse plugin for gradle Signed-off-by: deeptiraom <41100100+deeptiraom@users.noreply.github.com>
This commit is contained in:
parent
2581f10984
commit
e372006be7
8 changed files with 642 additions and 0 deletions
43
asset-transfer-basic/application-gateway-java/build.gradle
Normal file
43
asset-transfer-basic/application-gateway-java/build.gradle
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* This file was generated by the Gradle 'init' task.
|
||||
*
|
||||
* This generated file contains a sample Java project to get you started.
|
||||
* For more details take a look at the Java Quickstart chapter in the Gradle
|
||||
* User Manual available at https://docs.gradle.org/6.5/userguide/tutorial_java_projects.html
|
||||
*/
|
||||
plugins {
|
||||
// Apply the java plugin to add support for Java
|
||||
id 'java'
|
||||
// Apply the application plugin to add support for building a CLI application.
|
||||
id 'application'
|
||||
|
||||
}
|
||||
ext {
|
||||
javaMainClass = "application.java.App"
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// This dependency is used by the application.
|
||||
implementation 'org.hyperledger.fabric:fabric-gateway:1.0.0'
|
||||
implementation 'io.grpc:grpc-netty-shaded:1.42.0'
|
||||
implementation 'com.google.code.gson:gson:2.8.9'
|
||||
|
||||
}
|
||||
|
||||
application {
|
||||
// Define the main class for the application.
|
||||
mainClassName = 'application.java.App'
|
||||
}
|
||||
|
||||
// task for running the app after building dependencies
|
||||
task runApp(type: Exec) {
|
||||
dependsOn build
|
||||
group = "Execution"
|
||||
description = "Run the main class with ExecTask"
|
||||
commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass
|
||||
}
|
||||
|
||||
BIN
asset-transfer-basic/application-gateway-java/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
asset-transfer-basic/application-gateway-java/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
asset-transfer-basic/application-gateway-java/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
asset-transfer-basic/application-gateway-java/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
185
asset-transfer-basic/application-gateway-java/gradlew
vendored
Executable file
185
asset-transfer-basic/application-gateway-java/gradlew
vendored
Executable file
|
|
@ -0,0 +1,185 @@
|
|||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
104
asset-transfer-basic/application-gateway-java/gradlew.bat
vendored
Normal file
104
asset-transfer-basic/application-gateway-java/gradlew.bat
vendored
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
/*
|
||||
* This file was generated by the Gradle 'init' task.
|
||||
*
|
||||
* The settings file is used to specify which projects to include in your build.
|
||||
*
|
||||
* Detailed information about configuring a multi-project build in Gradle can be found
|
||||
* in the user manual at https://docs.gradle.org/6.5/userguide/multi_project_builds.html
|
||||
*/
|
||||
|
||||
rootProject.name = 'application-java'
|
||||
|
|
@ -0,0 +1,286 @@
|
|||
|
||||
/*
|
||||
* Copyright IBM Corp. All Rights Reserved.
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// Running TestApp:
|
||||
// gradle runApp
|
||||
|
||||
package application.java;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.hyperledger.fabric.client.CallOption;
|
||||
import org.hyperledger.fabric.client.CommitException;
|
||||
import org.hyperledger.fabric.client.CommitStatusException;
|
||||
import org.hyperledger.fabric.client.Contract;
|
||||
import org.hyperledger.fabric.client.EndorseException;
|
||||
import org.hyperledger.fabric.client.Gateway;
|
||||
import org.hyperledger.fabric.client.GatewayException;
|
||||
import org.hyperledger.fabric.client.Network;
|
||||
import org.hyperledger.fabric.client.SubmitException;
|
||||
import org.hyperledger.fabric.client.SubmittedTransaction;
|
||||
import org.hyperledger.fabric.client.Status;
|
||||
import org.hyperledger.fabric.client.identity.Identities;
|
||||
import org.hyperledger.fabric.client.identity.Identity;
|
||||
import org.hyperledger.fabric.client.identity.Signer;
|
||||
import org.hyperledger.fabric.client.identity.Signers;
|
||||
import org.hyperledger.fabric.client.identity.X509Identity;
|
||||
import org.hyperledger.fabric.protos.gateway.ErrorDetail;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.grpc.ManagedChannel;
|
||||
|
||||
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
|
||||
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final String mspID = "Org1MSP";
|
||||
private static final String channelName = "mychannel";
|
||||
private static final String chaincodeName = "basic";
|
||||
|
||||
public static String assetId = "asset" + Instant.now().toEpochMilli();
|
||||
|
||||
// Path to crypto materials.
|
||||
private static final Path cryptoPath = Paths.get("..", "..", "test-network", "organizations", "peerOrganizations",
|
||||
"org1.example.com");
|
||||
// Path to user certificate.
|
||||
private static final Path certPath = cryptoPath
|
||||
.resolve(Paths.get("users", "User1@org1.example.com", "msp", "signcerts", "cert.pem"));
|
||||
// Path to user private key directory.
|
||||
private static final Path keyPath = cryptoPath
|
||||
.resolve(Paths.get("users", "User1@org1.example.com", "msp", "keystore"));
|
||||
// Path to peer tls certificate.
|
||||
private static final Path tlsCertPath = cryptoPath
|
||||
.resolve(Paths.get("peers", "peer0.org1.example.com", "tls", "ca.crt"));
|
||||
|
||||
// Gateway peer end point.
|
||||
public static String peerEndpoint = "localhost:7051";
|
||||
public static String overrideAuth = "peer0.org1.example.com";
|
||||
|
||||
public static void main(String[] args)
|
||||
throws Exception {
|
||||
|
||||
// The gRPC client connection should be shared by all Gateway connections to
|
||||
// this endpoint.
|
||||
ManagedChannel channel = newGrpcConnection();
|
||||
|
||||
Gateway.Builder builder = Gateway.newInstance().identity(newIdentity()).signer(newSigner()).connection(channel)
|
||||
// Default timeouts for different gRPC calls
|
||||
.evaluateOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
|
||||
.endorseOptions(CallOption.deadlineAfter(15, TimeUnit.SECONDS))
|
||||
.submitOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
|
||||
.commitStatusOptions(CallOption.deadlineAfter(1, TimeUnit.MINUTES));
|
||||
|
||||
try (Gateway gateway = builder.connect()) {
|
||||
|
||||
// Get a network instance representing the channel where the smart contract is
|
||||
// deployed.
|
||||
Network network = gateway.getNetwork(channelName);
|
||||
|
||||
// Get the smart contract from the network.
|
||||
Contract contract = network.getContract(chaincodeName);
|
||||
|
||||
// Initialize a set of asset data on the ledger using the chaincode 'InitLedger'
|
||||
// function.
|
||||
initLedger(contract);
|
||||
|
||||
// Return all the current assets on the ledger.
|
||||
getAllAssets(contract);
|
||||
|
||||
// Create a new asset on the ledger.
|
||||
createAsset(contract);
|
||||
|
||||
// Update an existing asset asynchronously.
|
||||
transferAssetAsync(contract);
|
||||
|
||||
// Get the asset details by assetID.
|
||||
readAssetById(contract);
|
||||
|
||||
// Update an asset which does not exist.
|
||||
updateNonExistentAsset(contract);
|
||||
|
||||
} finally {
|
||||
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static ManagedChannel newGrpcConnection() throws IOException, CertificateException {
|
||||
Reader tlsCertReader = Files.newBufferedReader(tlsCertPath);
|
||||
X509Certificate tlsCert = Identities.readX509Certificate(tlsCertReader);
|
||||
|
||||
return NettyChannelBuilder.forTarget(peerEndpoint)
|
||||
.sslContext(GrpcSslContexts.forClient().trustManager(tlsCert).build()).overrideAuthority(overrideAuth)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Identity newIdentity() throws IOException, CertificateException {
|
||||
Reader certReader = Files.newBufferedReader(certPath);
|
||||
X509Certificate certificate = Identities.readX509Certificate(certReader);
|
||||
|
||||
return new X509Identity(mspID, certificate);
|
||||
}
|
||||
|
||||
private static Signer newSigner() throws IOException, InvalidKeyException {
|
||||
File dir = new File(keyPath.toString());
|
||||
File[] listOfFiles = dir.listFiles();
|
||||
Path path = Paths.get(listOfFiles[0].getPath());
|
||||
Reader keyReader = Files.newBufferedReader(path);
|
||||
PrivateKey privateKey = Identities.readPrivateKey(keyReader);
|
||||
|
||||
return Signers.newPrivateKeySigner(privateKey);
|
||||
}
|
||||
|
||||
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private static String prettyJson(byte[] json) {
|
||||
return prettyJson(new String(json, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String prettyJson(String json) {
|
||||
JsonElement parsedJson = JsonParser.parseString(json);
|
||||
return gson.toJson(parsedJson);
|
||||
}
|
||||
|
||||
/**
|
||||
* This type of transaction would typically only be run once by an application
|
||||
* the first time it was started after its initial deployment. A new version of
|
||||
* the chaincode deployed later would likely not need to run an "init" function.
|
||||
*/
|
||||
private static void initLedger(Contract contract) throws GatewayException, CommitException {
|
||||
|
||||
System.out.println(
|
||||
"\n" + "--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger");
|
||||
|
||||
contract.submitTransaction("InitLedger");
|
||||
|
||||
System.out.println("*** Transaction committed successfully");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a transaction to query ledger state.
|
||||
*/
|
||||
private static void getAllAssets(Contract contract) throws GatewayException {
|
||||
|
||||
System.out.println(
|
||||
"\n" + "--> Evaluate Transaction: GetAllAssets, function returns all the current assets on the ledger");
|
||||
|
||||
byte[] result = contract.evaluateTransaction("GetAllAssets");
|
||||
|
||||
System.out.println("*** Result: " + prettyJson(result));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a transaction synchronously, blocking until it has been committed to
|
||||
* the ledger.
|
||||
*/
|
||||
private static void createAsset(Contract contract) throws GatewayException, CommitException {
|
||||
|
||||
System.out.println("\n"
|
||||
+ "--> Submit Transaction: CreateAsset, creates new asset with ID, Color, Size, Owner and AppraisedValue arguments");
|
||||
|
||||
contract.submitTransaction("CreateAsset", assetId, "yellow", "5", "Tom", "1300");
|
||||
|
||||
System.out.println("*** Transaction committed successfully");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit transaction asynchronously, allowing the application to process the
|
||||
* smart contract response (e.g. update a UI) while waiting for the commit
|
||||
* notification.
|
||||
*/
|
||||
private static void transferAssetAsync(Contract contract) throws GatewayException {
|
||||
|
||||
System.out.println("\n" + "--> Async Submit Transaction: TransferAsset, updates existing asset owner");
|
||||
|
||||
SubmittedTransaction commit = contract.newProposal("TransferAsset")
|
||||
.addArguments(assetId, "Saptha")
|
||||
.build()
|
||||
.endorse()
|
||||
.submitAsync();
|
||||
|
||||
byte[] result = commit.getResult();
|
||||
String oldOwner = new String(result, StandardCharsets.UTF_8);
|
||||
|
||||
System.out.println(
|
||||
"*** Successfully submitted transaction to transfer ownership from " + oldOwner + " to Saptha");
|
||||
System.out.println("*** Waiting for transaction commit");
|
||||
|
||||
Status status = commit.getStatus();
|
||||
if (!status.isSuccessful()) {
|
||||
throw new RuntimeException("Transaction " + status.getTransactionId() + " failed to commit with status code "
|
||||
+ status.getCode());
|
||||
|
||||
}
|
||||
|
||||
System.out.println("*** Transaction committed successfully");
|
||||
|
||||
}
|
||||
|
||||
private static void readAssetById(Contract contract) throws GatewayException {
|
||||
|
||||
System.out.println("\n" + "--> Evaluate Transaction: ReadAsset, function returns asset attributes");
|
||||
|
||||
byte[] evaluateResult = contract.evaluateTransaction("ReadAsset", assetId);
|
||||
|
||||
System.out.println("*** Result:" + prettyJson(evaluateResult));
|
||||
}
|
||||
|
||||
/**
|
||||
* submitTransaction() will throw an error containing details of any error
|
||||
* responses from the smart contract.
|
||||
*/
|
||||
private static void updateNonExistentAsset(Contract contract) {
|
||||
|
||||
try {
|
||||
System.out.println("\n"
|
||||
+ "--> Submit Transaction: UpdateAsset asset70, asset70 does not exist and should return an error");
|
||||
|
||||
contract.submitTransaction("UpdateAsset", "asset70", "blue", "5", "Tomoko", "300");
|
||||
|
||||
System.out.println("******** FAILED to return an error");
|
||||
|
||||
} catch (EndorseException | SubmitException | CommitStatusException e) {
|
||||
System.out.println("*** Successfully caught the error: ");
|
||||
|
||||
e.printStackTrace(System.out);
|
||||
if (!e.getDetails().isEmpty()) {
|
||||
System.out.println("\n" + "Error Details: ");
|
||||
for (ErrorDetail detail : e.getDetails()) {
|
||||
System.out.println("address: " + detail.getAddress() + ", mspId: " + detail.getMspId()
|
||||
+ ", message: " + detail.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Transaction ID: " + e.getTransactionId());
|
||||
|
||||
} catch (CommitException e) {
|
||||
System.out.println("*** Successfully caught the error: " + e);
|
||||
e.printStackTrace(System.out);
|
||||
System.out.println("Transaction ID: " + e.getTransactionId() + " status code: " + e.getCode());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -41,6 +41,15 @@ gradle run
|
|||
popd
|
||||
stopNetwork
|
||||
|
||||
# Run Java application using gateway
|
||||
createNetwork
|
||||
print "Initializing Java application"
|
||||
pushd ../asset-transfer-basic/application-gateway-java
|
||||
print "Executing Gradle Run"
|
||||
gradle run
|
||||
popd
|
||||
stopNetwork
|
||||
|
||||
# Run Javascript application
|
||||
createNetwork
|
||||
print "Initializing Javascript application"
|
||||
|
|
|
|||
Loading…
Reference in a new issue