Hyperledger Chaincode Java - PhyrexTsai/docker-compose-files GitHub Wiki

Java ChaincodeBase

MapExample

This example implements Map on chaincode, key-value includes [get, put, del].

Code sample :

public class MapExample extends ChaincodeBase {

	@Override
	public String run(ChaincodeStub stub, String function, String[] args) {
		switch (function) {
		case "put":
			for (int i = 0; i < args.length; i += 2)
				stub.putState(args[i], args[i + 1]);
			break;
		case "del":
			for (String arg : args)
				stub.delState(arg);
			break;
		}
		return null;
	}

	@Override
	public String query(ChaincodeStub stub, String function, String[] args) {
		return stub.getState(args[0]);
	}

	@Override
	public String getChaincodeID() {
		return "map";
	}

	public static void main(String[] args) throws Exception {
		new MapExample().start(args);
	}
}

Method

  • run(ChaincodeStub stub, String function, String[] args)
peer chaincode deploy -l java ... -c '{"Args": ["put", "a", "100"]}'

function -> "put"
args[0]: key -> "a"
args[1]: value -> "100"

peer chaincode invoke -l java ... -c '{"Args": ["del", "a", "b"]}'

function -> "del"
args[0]: key -> "a"
args[1]: key -> "b"
  • query(ChaincodeStub stub, String function, String[] args)
peer chaincode query -l java ... -c '{ "Args": ["query", "a"]}'

function -> "query"
args[0]: key -> "a" (get value from key "a")
  • getChaincodeID()

    • return the name of the chaincode
  • main()

    • initialize with start(args)

Reference