├── settings.gradle ├── manual ├── credential.png ├── use-scalar-dl-sandbox.md └── README.md ├── tutorial ├── img │ ├── structure.jpg │ ├── sequence-diagram.png │ ├── command-class-diagram.jpg │ └── contract-class-diagram.jpg └── draw.io.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ ├── resources │ │ └── log4j.properties │ └── java │ │ └── com │ │ └── scalar │ │ └── am │ │ ├── command │ │ ├── ListType.java │ │ ├── ValidateAsset.java │ │ ├── List.java │ │ ├── AddType.java │ │ ├── AssetHistory.java │ │ ├── ReturnAsset.java │ │ ├── BorrowAsset.java │ │ ├── AddAsset.java │ │ ├── LedgerClientExecutor.java │ │ └── Init.java │ │ ├── AssetManager.java │ │ └── contract │ │ ├── AddTypeContract.java │ │ ├── ListTypeContract.java │ │ ├── AssetHistoryContract.java │ │ ├── AddAssetContract.java │ │ ├── StatusChangeContract.java │ │ └── ListContract.java ├── test │ └── java │ │ └── com │ │ └── scalar │ │ └── am │ │ └── contract │ │ ├── ContractTest.java │ │ ├── ListTypeContractTest.java │ │ ├── AddTypeContractTest.java │ │ ├── AssetHistoryContractTest.java │ │ ├── ListContractTest.java │ │ ├── AddAssetContractTest.java │ │ └── StatusChangeContractTest.java └── integration-test │ └── java │ └── com │ └── scalar │ └── am │ └── e2e │ └── EndToEnd.java ├── fixture ├── bar-key.pem ├── foo-key.pem ├── bar.pem └── foo.pem ├── NOTICE.md ├── COPYRIGHT ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'am' 2 | 3 | -------------------------------------------------------------------------------- /manual/credential.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/manual/credential.png -------------------------------------------------------------------------------- /tutorial/img/structure.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/tutorial/img/structure.jpg -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /tutorial/img/sequence-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/tutorial/img/sequence-diagram.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | build/ 3 | out/ 4 | /contract 5 | .classpath 6 | .settings 7 | .project 8 | am-1.0.jar 9 | .vscode/ 10 | .gradle/ 11 | -------------------------------------------------------------------------------- /tutorial/img/command-class-diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/tutorial/img/command-class-diagram.jpg -------------------------------------------------------------------------------- /tutorial/img/contract-class-diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scalar-labs/getting-started-with-scalardl/HEAD/tutorial/img/contract-class-diagram.jpg -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=error,stdout 2 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 3 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /fixture/bar-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEICcJGMEw3dyXUGFu/5a36HqY0ynZi9gLUfKgYWMYgr/IoAoGCCqGSM49 3 | AwEHoUQDQgAEBGuhqumyh7BVNqcNKAQQipDGooUpURve2dO66pQCgjtSfu7lJV20 4 | XYWdrgo0Y3eXEhvK0lsURO9N0nrPiQWT4A== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /fixture/foo-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEIIbElY/Vs5nEoVGsHZ8G9icxZcsRlT2DcHIfxFNkZrnHoAoGCCqGSM49 3 | AwEHoUQDQgAE/TzGEcYJNcwe5d+BlPuxuwiIhMhKpMpTMZM94L+bRhDPFn4nMigc 4 | Cijley7qhOfwplVrTtnNLTNMD82ttwnR7g== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /manual/use-scalar-dl-sandbox.md: -------------------------------------------------------------------------------- 1 | # Apply for using Scalar DL Sandbox 2 | 3 | Please follow the steps below: 4 | 5 | 1. Go to https://scalar-labs.com/sandbox/ 6 | 2. Click `Sign in Github` button 7 | 3. Enter your Github account and password 8 | 4. Permit Scalar DL Sandbox to access your email 9 | 5. Click `Download` button to download the private key and certificate 10 | 11 | Your credential will be displayed in the field `scalar.ledger.client.authorization.credential` of the client.properties. 12 | Like the image below. 13 | ![credential](credential.png) -------------------------------------------------------------------------------- /NOTICE.md: -------------------------------------------------------------------------------- 1 | This project uses following products: 2 | 3 | |Name|Copyright|License|Link| 4 | |----|---------|-------|----| 5 | |picocli|Remko Popma|Apache|https://picocli.info/| 6 | |junit|The JUnit Team|Eclipse Public|https://junit.org/junit5/| 7 | |mockito|Mockito contributors|MIT|https://site.mockito.org/| 8 | |gradle (and related plugins)|CopGradle Inc.|Apache|https://gradle.org/| 9 | |google-java-format|Google Inc.|Apache|https://github.com/google/google-java-format| 10 | |scalardl-client-sdk|Scalar, Inc.|AGPL|https://github.com/scalar-labs/scalardl-client-sdk| 11 | |gradle-capsule-plugin|Danny Kirchmeier|MIT|https://github.com/danthegoodman/gradle-capsule-plugin| 12 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/ListType.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.ListTypeContract; 4 | import javax.json.Json; 5 | import picocli.CommandLine; 6 | 7 | @CommandLine.Command(name = "list-type", description = "List the existing types of asset") 8 | public class ListType extends LedgerClientExecutor implements Runnable { 9 | 10 | @CommandLine.Option( 11 | names = {"-h", "--help"}, 12 | usageHelp = true, 13 | description = "display this help and exit") 14 | boolean help; 15 | 16 | @Override 17 | public void run() { 18 | executeContract(ListTypeContract.class.getCanonicalName(), Json.createObjectBuilder().build()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | A simple asset management application for the purpose of demonstration for Scalar DL. 2 | 3 | Copyright (C) 2019 Scalar, Inc. 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Affero General Public License as published 7 | by the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Affero General Public License for more details. 14 | 15 | You should have received a copy of the GNU Affero General Public License 16 | along with this program. If not, see . 17 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/ValidateAsset.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import picocli.CommandLine; 4 | 5 | @CommandLine.Command( 6 | name = "validate", 7 | description = "validate if an asset data has not been tampered") 8 | public class ValidateAsset extends LedgerClientExecutor implements Runnable { 9 | @CommandLine.Option( 10 | names = {"-h", "--help"}, 11 | usageHelp = true, 12 | description = "display this help and exit") 13 | boolean help; 14 | 15 | @CommandLine.Parameters( 16 | arity = "1..*", 17 | paramLabel = "asset", 18 | description = "the asset or directly") 19 | private String[] arguments; 20 | 21 | @Override 22 | public void run() { 23 | String id = 24 | (arguments.length == 1) 25 | ? arguments[0] 26 | : getHashHexString(arguments[0] + "_" + arguments[1]); 27 | 28 | validateAsset(id); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /fixture/bar.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICizCCAjKgAwIBAgIUMEUDTdWsQpftFkqs6bCd6U++4nEwCgYIKoZIzj0EAwIw 3 | bzELMAkGA1UEBhMCSlAxDjAMBgNVBAgTBVRva3lvMQ4wDAYDVQQHEwVUb2t5bzEf 4 | MB0GA1UEChMWU2FtcGxlIEludGVybWVkaWF0ZSBDQTEfMB0GA1UEAxMWU2FtcGxl 5 | IEludGVybWVkaWF0ZSBDQTAeFw0xODA5MTAwODA3MDBaFw0yMTA5MDkwODA3MDBa 6 | MEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJ 7 | bnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC 8 | AAQEa6Gq6bKHsFU2pw0oBBCKkMaihSlRG97Z07rqlAKCO1J+7uUlXbRdhZ2uCjRj 9 | d5cSG8rSWxRE703Ses+JBZPgo4HVMIHSMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE 10 | DDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBRDd2MS9Ndo68PJ 11 | y9K/RNY6syZW0zAfBgNVHSMEGDAWgBR+Y+v8yByDNp39G7trYrTfZ0UjJzAxBggr 12 | BgEFBQcBAQQlMCMwIQYIKwYBBQUHMAGGFWh0dHA6Ly9sb2NhbGhvc3Q6ODg4OTAq 13 | BgNVHR8EIzAhMB+gHaAbhhlodHRwOi8vbG9jYWxob3N0Ojg4ODgvY3JsMAoGCCqG 14 | SM49BAMCA0cAMEQCIC/Bo4oNU6yHFLJeme5ApxoNdyu3rWyiqWPxJmJAr9L0AiBl 15 | Gc/v+yh4dHIDhCrimajTQAYOG9n0kajULI70Gg7TNw== 16 | -----END CERTIFICATE----- 17 | -------------------------------------------------------------------------------- /fixture/foo.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICjTCCAjKgAwIBAgIUOt6KMwZpclftxxQzdJsptjxNjdMwCgYIKoZIzj0EAwIw 3 | bzELMAkGA1UEBhMCSlAxDjAMBgNVBAgTBVRva3lvMQ4wDAYDVQQHEwVUb2t5bzEf 4 | MB0GA1UEChMWU2FtcGxlIEludGVybWVkaWF0ZSBDQTEfMB0GA1UEAxMWU2FtcGxl 5 | IEludGVybWVkaWF0ZSBDQTAeFw0xODA5MTAwODA2MDBaFw0yMTA5MDkwODA2MDBa 6 | MEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJ 7 | bnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC 8 | AAT9PMYRxgk1zB7l34GU+7G7CIiEyEqkylMxkz3gv5tGEM8WficyKBwKKOV7LuqE 9 | 5/CmVWtO2c0tM0wPza23CdHuo4HVMIHSMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE 10 | DDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBS1Neb+7m9wyM2h 11 | oRs75x86gbzS5TAfBgNVHSMEGDAWgBR+Y+v8yByDNp39G7trYrTfZ0UjJzAxBggr 12 | BgEFBQcBAQQlMCMwIQYIKwYBBQUHMAGGFWh0dHA6Ly9sb2NhbGhvc3Q6ODg4OTAq 13 | BgNVHR8EIzAhMB+gHaAbhhlodHRwOi8vbG9jYWxob3N0Ojg4ODgvY3JsMAoGCCqG 14 | SM49BAMCA0kAMEYCIQDxqVzuhLWxnX6fajucPcjCcvtWTl/4fAAN/n8Py1qmfwIh 15 | AKtP641f4dGZTV0R6uMYDrZjunwbG+kmt9+vSuE8rjO0 16 | -----END CERTIFICATE----- 17 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/ContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | public abstract class ContractTest { 4 | protected static final String TYPE_EX = "book"; 5 | protected static final long TIMESTAMP_EX = 1540453242790L; 6 | protected static final String ID_EX = "E156FF48B704CA23C99FD07527B178DB"; 7 | protected static final String ASSET_EX = "Human History"; 8 | protected static final String NAME_EX = "comic"; 9 | protected static final String ASSET_ID_EX = "comic"; 10 | protected static final String MESSAGE_EX = "test Exception"; 11 | protected static final String HOLDER_ID_1_EX = "Tester1"; 12 | protected static final String HOLDER_ID_2_EX = "Tester2"; 13 | protected static final int AGE_EX = 1; 14 | protected static final String RESULT = "result"; 15 | protected static final String SUCCESS = "success"; 16 | protected static final String FAILURE = "failure"; 17 | protected static final String MESSAGE = "message"; 18 | protected static final String IN_STOCK = "in-stock"; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/List.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.ListContract; 4 | import javax.json.Json; 5 | import javax.json.JsonObject; 6 | import picocli.CommandLine; 7 | 8 | /** This class defines the behaviour of list CLI command */ 9 | @CommandLine.Command(name = "list", description = "List the assets of the given type") 10 | public class List extends LedgerClientExecutor implements Runnable { 11 | 12 | @CommandLine.Option( 13 | names = {"-h", "--help"}, 14 | usageHelp = true, 15 | description = "display this help and exit") 16 | boolean help; 17 | 18 | @CommandLine.Parameters( 19 | index = "0", 20 | paramLabel = "asset_type", 21 | description = "the asset type to get, e.g. : book") 22 | private String type; 23 | 24 | @Override 25 | public void run() { 26 | JsonObject argument = Json.createObjectBuilder().add(ListContract.TYPE, type).build(); 27 | executeContract(ListContract.class.getCanonicalName(), argument); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/AddType.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.AddTypeContract; 4 | import javax.json.Json; 5 | import javax.json.JsonObject; 6 | import picocli.CommandLine; 7 | 8 | /** This class defines the behaviour of add-type CLI command */ 9 | @CommandLine.Command(name = "add-type", description = "Add the asset type") 10 | public class AddType extends LedgerClientExecutor implements Runnable { 11 | 12 | @CommandLine.Option( 13 | names = {"-h", "--help"}, 14 | usageHelp = true, 15 | description = "display this help and exit") 16 | private boolean help; 17 | 18 | @CommandLine.Parameters( 19 | index = "0", 20 | paramLabel = "asset_type", 21 | description = "the asset type to add, e.g. : book") 22 | private String type; 23 | 24 | @Override 25 | public void run() { 26 | JsonObject argument = Json.createObjectBuilder().add(AddTypeContract.NAME, type).build(); 27 | this.executeContract(AddTypeContract.class.getCanonicalName(), argument); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/AssetHistory.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.AssetHistoryContract; 4 | import javax.json.Json; 5 | import javax.json.JsonObject; 6 | import picocli.CommandLine; 7 | 8 | /** This class defines the behaviour of asset-history CLI command */ 9 | @CommandLine.Command(name = "asset-history", description = "List the assets of the given asset-id") 10 | public class AssetHistory extends LedgerClientExecutor implements Runnable { 11 | 12 | @CommandLine.Option( 13 | names = {"-h", "--help"}, 14 | usageHelp = true, 15 | description = "display this help and exit") 16 | boolean help; 17 | 18 | @CommandLine.Parameters( 19 | arity = "1..*", 20 | paramLabel = "arguments", 21 | description = "can be or directly.") 22 | private String[] arguments; 23 | 24 | @Override 25 | public void run() { 26 | String id = 27 | (arguments.length == 1) 28 | ? arguments[0] 29 | : getHashHexString(arguments[0] + "_" + arguments[1]); 30 | JsonObject argument = Json.createObjectBuilder().add(AssetHistoryContract.ID, id).build(); 31 | executeContract(AssetHistoryContract.class.getCanonicalName(), argument); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/ReturnAsset.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.StatusChangeContract; 4 | import java.util.Date; 5 | import javax.json.Json; 6 | import javax.json.JsonObject; 7 | import picocli.CommandLine; 8 | 9 | @CommandLine.Command(name = "return", description = "Return the asset") 10 | public class ReturnAsset extends LedgerClientExecutor implements Runnable { 11 | @CommandLine.Option( 12 | names = {"-h", "--help"}, 13 | usageHelp = true, 14 | description = "display this help and exit") 15 | boolean help; 16 | 17 | @CommandLine.Parameters( 18 | arity = "1..*", 19 | paramLabel = "arguments", 20 | description = "can be or directly.") 21 | private String[] arguments; 22 | 23 | @Override 24 | public void run() { 25 | String id = 26 | (arguments.length == 1) 27 | ? arguments[0] 28 | : getHashHexString(arguments[0] + "_" + arguments[1]); 29 | JsonObject argument = 30 | Json.createObjectBuilder() 31 | .add(StatusChangeContract.ASSET_ID, id) 32 | .add(StatusChangeContract.TIMESTAMP, new Date().getTime()) 33 | .add(StatusChangeContract.STATUS, StatusChangeContract.IN_STOCK) 34 | .build(); 35 | executeContract(StatusChangeContract.class.getCanonicalName(), argument); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/BorrowAsset.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.StatusChangeContract; 4 | import java.util.Date; 5 | import javax.json.Json; 6 | import javax.json.JsonObject; 7 | import picocli.CommandLine; 8 | 9 | @CommandLine.Command(name = "borrow", description = "Borrow the asset") 10 | public class BorrowAsset extends LedgerClientExecutor implements Runnable { 11 | @CommandLine.Option( 12 | names = {"-h", "--help"}, 13 | usageHelp = true, 14 | description = "display this help and exit") 15 | boolean help; 16 | 17 | @CommandLine.Parameters( 18 | arity = "1..*", 19 | paramLabel = "arguments", 20 | description = "can be or directly.") 21 | private String[] arguments; 22 | 23 | @Override 24 | public void run() { 25 | String id = 26 | (arguments.length == 1) 27 | ? arguments[0] 28 | : getHashHexString(arguments[0] + "_" + arguments[1]); 29 | JsonObject argument = 30 | Json.createObjectBuilder() 31 | .add(StatusChangeContract.ASSET_ID, id) 32 | .add(StatusChangeContract.TIMESTAMP, new Date().getTime()) 33 | .add(StatusChangeContract.STATUS, StatusChangeContract.ON_LOAN) 34 | .build(); 35 | 36 | executeContract(StatusChangeContract.class.getCanonicalName(), argument); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/AddAsset.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.AddAssetContract; 4 | import java.util.Date; 5 | import javax.json.Json; 6 | import javax.json.JsonObject; 7 | import picocli.CommandLine; 8 | 9 | /** This class defines the behaviour of add CLI command */ 10 | @CommandLine.Command(name = "add", description = "Add the asset") 11 | public class AddAsset extends LedgerClientExecutor implements Runnable { 12 | @CommandLine.Option( 13 | names = {"-h", "--help"}, 14 | usageHelp = true, 15 | description = "display this help and exit") 16 | boolean help; 17 | 18 | @CommandLine.Parameters( 19 | index = "0", 20 | paramLabel = "asset_type", 21 | description = "the asset type, e.g : book ") 22 | private String type; 23 | 24 | @CommandLine.Parameters( 25 | index = "1", 26 | paramLabel = "asset", 27 | description = "the asset description, e.g : Lord of the Rings") 28 | private String asset; 29 | 30 | @Override 31 | public void run() { 32 | JsonObject argument = 33 | Json.createObjectBuilder() 34 | .add(AddAssetContract.TYPE, type) 35 | .add(AddAssetContract.ASSET, asset) 36 | .add(AddAssetContract.TIMESTAMP, new Date().getTime()) 37 | .add(AddAssetContract.ID, getHashHexString(type + "_" + asset)) 38 | .build(); 39 | 40 | executeContract(AddAssetContract.class.getCanonicalName(), argument); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/AssetManager.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am; 2 | 3 | import com.scalar.am.command.AddAsset; 4 | import com.scalar.am.command.AddType; 5 | import com.scalar.am.command.AssetHistory; 6 | import com.scalar.am.command.BorrowAsset; 7 | import com.scalar.am.command.Init; 8 | import com.scalar.am.command.List; 9 | import com.scalar.am.command.ListType; 10 | import com.scalar.am.command.ReturnAsset; 11 | import com.scalar.am.command.ValidateAsset; 12 | import picocli.CommandLine; 13 | 14 | /** 15 | * The entry point of the CLI application
16 | * This class references the other subcommands 17 | */ 18 | @CommandLine.Command( 19 | name = "am", 20 | description = "Asset manager application", 21 | version = "1.0", 22 | subcommands = { 23 | Init.class, 24 | AddAsset.class, 25 | AddType.class, 26 | BorrowAsset.class, 27 | ListType.class, 28 | List.class, 29 | ReturnAsset.class, 30 | AssetHistory.class, 31 | ValidateAsset.class 32 | }) 33 | public class AssetManager implements Runnable { 34 | @CommandLine.Option( 35 | names = {"-h", "--help"}, 36 | usageHelp = true, 37 | description = "display this help and exit") 38 | private boolean help; 39 | 40 | public static void main(String[] args) { 41 | // Display the help if no arguments are passed 42 | String[] commandArgs = args.length != 0 ? args : new String[] {"--help"}; 43 | CommandLine.run(new AssetManager(), commandArgs); 44 | } 45 | 46 | @Override 47 | public void run() {} 48 | } 49 | -------------------------------------------------------------------------------- /tutorial/draw.io.xml: -------------------------------------------------------------------------------- 1 | 5Vpbc5s4FP41fozHIG5+tJ20ndlsZ2fdme0+yqBgTQC5Qo7t/fUrgcAIiZgk2Elqd6aBI3Qkfd+5STACi3T/lcLN+k8SoWRkT6L9CNyObNtybI//EZJDKfGnk1IQUxzJh46CJf4PSWH12BZHKFceZIQkDG9UYUiyDIVMkUFKyU597IEk6qgbGCNNsAxhokv/wRFbS6nlTY8N3xCO13LowPbLhhUMH2NKtpkcb2SDh+JXNqew0iUXmq9hRHYNEbgbgQUlhJVX6X6BEoFtBVvZ70tHaz1vijLWp4NTdniCyRZVM/YS3nUe4ScxP3aQmHi/tmJSc4b27AYmOM5GYMafSNADO7byq1j+LbSsaFvC51KorqS2MopdYIfE7Ca8ebfGDC03MBStO25rXLZmacLvLH75gJNkQRJCi77gzhP/uFxO77aYG5g/IcowJ3cmxYwIPQlcoWRe89XQIxkD85xR8ogaLV7x4y1xAvNcTrLmUNyEJMWhvI5gvi6WYtUrbTIjyRKzQ/uGSDL1FZEUMXrgj8hW4EurkV5lefJ+d7RRUHnaumGe9kQKofSLuNZ9tA1+Ic3DbCpgIFOZFGBwn8zYTV54vmiznM1eN6PviO0IfTy37WQkQ33NRsxbBizLGYZX123xahl49U28BgPwap85BOQbmLVlAkSj6l5WsUiwAPtoFKU6Lc6YRv4IJjSAydQe/ZzJgHOZjOUOYzOdgaDg61l76mk7RkV3YBSA0Xy+4B0oDIUlfocpOmE5IpW9ZdQOA/x8sM1ovE1VB7ykpzUT9KsitpbVJ8VvoBw9VR3TBrpjWrbBMb0B/NLrdMsXsd9N/QnKm7JZFP04bNDRx7SCsFJ6j3N24tGOYWuLjKJZniPWc7DTAxlHWTLI0GINs7jPqooJfeOjEXo4PWAfiQb6dXiU67uqR00MHuW5ukfVbvamVGcZfKoFPMqimdh08rtVQsJHFWm+cnr4KVkpbv4VN2NX3O4x+1k9x6+PLSWk1ebTLrpGX3BSae0ENidbGlbbWIkKgzRGTIkRKFJ2wDr6DXRdQ7iqZBQlkOEndd9sAlyO8BfBRelXhUs1Wnp+i7JyNbJTcx/b0hO09LSpLxHQ9BTs14vuZxB6kF1y34BsS9G1uKSW5KY9kxwYwiN93SOroIszrATZIcodGEU3jKenofUmPDecRTGf8DnmOrTOFSli5sBaKeKOmA0OqUjmN+symw+2IfhNji/aQdwKgrGrxwPLEA8sZ4iAELwoRYfi6E6c0SlJujMRP5e++yVhX0/CzodKwrajEuhUZ30vzcLAauWFdjofLg3bJtLPfRy5IClMsyjvucUVA6pmpmZl6bcvd+UUR5EYxBgk1DByCX/3Ddnf5O1D1OPAdAzdwl0c6G/6L7R+jQRXlYbJswD4rfLHdA5vTYwADIFAjx1JBwI1eK+H4CJLNFR4n/St1NuOhUF/37wIL9ZUI6Y45hAB8xNiVp+lK94MrLHrB1PHB17gcDCdQHPuwLS16ej2plcz3XjrPv9Z8Q6cMYfLtT1glQC+G9xVXjPADUyh4zchwALeuMCw4sB7PwZM3yN8nFJezq5ZyUtr/SCVPLBPFOC9K3n/YpU8sDXO7wWcVGP+7fV0yNnlij9aRa0VlI5eUJqsZpCC+j02UuJTKyiOT27vf/D/l7d/XPeWSvuyx2AA59tS6VXG+S3gb/Rri4rcetW8tw/SDZ9xnI13Ry93LnGEUr4KvfIzlPZLTcvvfWb6Cur57fGT0jJFH7/bBXf/Aw== -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/AddTypeContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.Optional; 8 | import javax.json.Json; 9 | import javax.json.JsonObject; 10 | 11 | public class AddTypeContract extends Contract { 12 | 13 | public static final String NAME = "name"; 14 | public static final String TYPE = "type"; 15 | public static final String HOLDER_ID = "holderId"; 16 | 17 | private static final String RESULT = "result"; 18 | private static final String SUCCESS = "success"; 19 | private static final String FAILURE = "failure"; 20 | private static final String MESSAGE = "message"; 21 | 22 | @Override 23 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 24 | if (!argument.containsKey(NAME)) { 25 | throw new ContractContextException("wrong argument."); 26 | } 27 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 28 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 29 | } 30 | 31 | String holderId = property.get().getString(HOLDER_ID); 32 | String name = argument.getString(NAME); 33 | 34 | Optional type = ledger.get(holderId + "-" + name); 35 | if (type.isPresent()) { 36 | return Json.createObjectBuilder() 37 | .add(RESULT, FAILURE) 38 | .add(MESSAGE, "Type " + name + " is already registered.") 39 | .build(); 40 | } 41 | 42 | ledger.put(holderId + "-" + name, Json.createObjectBuilder().build()); 43 | 44 | JsonObject newType = Json.createObjectBuilder().add(NAME, name).build(); 45 | ledger.get(holderId + "-" + TYPE); 46 | ledger.put(holderId + "-" + TYPE, newType); 47 | 48 | return Json.createObjectBuilder() 49 | .add(RESULT, SUCCESS) 50 | .add(MESSAGE, "type " + name + " put completed.") 51 | .build(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/ListTypeContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.database.AssetFilter; 6 | import com.scalar.dl.ledger.exception.ContractContextException; 7 | import com.scalar.dl.ledger.database.Ledger; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArray; 12 | import javax.json.JsonArrayBuilder; 13 | import javax.json.JsonObject; 14 | 15 | public class ListTypeContract extends Contract { 16 | 17 | public static final String TYPE = "type"; 18 | public static final String AGE = "age"; 19 | public static final String TYPES = "types"; 20 | public static final String NAME = "name"; 21 | public static final String HOLDER_ID = "holderId"; 22 | 23 | private static final String RESULT = "result"; 24 | private static final String SUCCESS = "success"; 25 | private static final String FAILURE = "failure"; 26 | private static final String MESSAGE = "message"; 27 | 28 | @Override 29 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 30 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 31 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 32 | } 33 | 34 | String holderId = property.get().getString(HOLDER_ID); 35 | 36 | /** 37 | * Registered types will be put into key: type, thus the history of key: type is just the list 38 | * of registered types E.g. history of type = [ { "name": "book" }, // age: 0 { "name": "phone" 39 | * } // age: 1 ] 40 | */ 41 | AssetFilter filter = new AssetFilter(holderId + "-" + TYPE); 42 | List history = ledger.scan(filter); 43 | if (history.isEmpty()) { 44 | return Json.createObjectBuilder() 45 | .add(RESULT, FAILURE) 46 | .add(MESSAGE, "No types were registered. Use am add-type to create one.") 47 | .build(); 48 | } 49 | 50 | JsonArrayBuilder builder = Json.createArrayBuilder(); 51 | for (Asset h : history) { 52 | JsonObject type = 53 | Json.createObjectBuilder().add(TYPE, h.data().getString(NAME)).add(AGE, h.age()).build(); 54 | builder.add(type); 55 | } 56 | JsonArray types = builder.build(); 57 | 58 | return Json.createObjectBuilder() 59 | .add(RESULT, SUCCESS) 60 | .add(MESSAGE, "get list completed.") 61 | .add(TYPES, types) 62 | .build(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/AssetHistoryContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.database.AssetFilter; 6 | import com.scalar.dl.ledger.exception.ContractContextException; 7 | import com.scalar.dl.ledger.database.Ledger; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArrayBuilder; 12 | import javax.json.JsonObject; 13 | import javax.json.JsonObjectBuilder; 14 | 15 | public class AssetHistoryContract extends Contract { 16 | 17 | public static final String ID = "id"; 18 | public static final String TIMESTAMP = "timestamp"; 19 | public static final String STATUS = "status"; 20 | public static final String AGE = "age"; 21 | public static final String HISTORY = "history"; 22 | public static final String HOLDER_ID = "holderId"; 23 | 24 | private static final String RESULT = "result"; 25 | private static final String SUCCESS = "success"; 26 | private static final String FAILURE = "failure"; 27 | private static final String MESSAGE = "message"; 28 | 29 | @Override 30 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 31 | if (!argument.containsKey(ID)) { 32 | throw new ContractContextException("wrong argument."); 33 | } 34 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 35 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 36 | } 37 | 38 | String holderId = property.get().getString(HOLDER_ID); 39 | String id = argument.getString(ID); 40 | 41 | AssetFilter filter = new AssetFilter(holderId + "-" + id); 42 | List borrowingHistory = ledger.scan(filter); 43 | 44 | if (borrowingHistory.isEmpty()) { 45 | return Json.createObjectBuilder() 46 | .add(RESULT, FAILURE) 47 | .add(MESSAGE, "This asset is not registered") 48 | .build(); 49 | } 50 | 51 | JsonArrayBuilder builder = Json.createArrayBuilder(); 52 | JsonObjectBuilder borrowingRecordBuilder = Json.createObjectBuilder(); 53 | for (Asset history : borrowingHistory) { 54 | borrowingRecordBuilder 55 | .add(TIMESTAMP, history.data().getJsonNumber(TIMESTAMP).longValue()) 56 | .add(STATUS, history.data().getString(STATUS)) 57 | .add(AGE, history.age()); 58 | 59 | if (history.data().containsKey(HOLDER_ID)) { 60 | borrowingRecordBuilder.add(HOLDER_ID, history.data().getString(HOLDER_ID)); 61 | } 62 | builder.add(borrowingRecordBuilder.build()); 63 | } 64 | 65 | return Json.createObjectBuilder() 66 | .add(RESULT, SUCCESS) 67 | .add(MESSAGE, "get history complete.") 68 | .add(HISTORY, builder.build()) 69 | .build(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/AddAssetContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.Optional; 8 | import javax.json.Json; 9 | import javax.json.JsonObject; 10 | 11 | public class AddAssetContract extends Contract { 12 | 13 | public static final String TYPE = "type"; 14 | public static final String ASSET = "asset"; 15 | public static final String ID = "id"; 16 | public static final String NAME = "name"; 17 | public static final String TIMESTAMP = "timestamp"; 18 | public static final String STATUS = "status"; 19 | public static final String IN_STOCK = "in-stock"; 20 | public static final String HOLDER_ID = "holderId"; 21 | 22 | private static final String RESULT = "result"; 23 | private static final String SUCCESS = "success"; 24 | private static final String FAILURE = "failure"; 25 | private static final String MESSAGE = "message"; 26 | 27 | @Override 28 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 29 | if (!argument.containsKey(TYPE) 30 | || !argument.containsKey(ASSET) 31 | || !argument.containsKey(TIMESTAMP) 32 | || !argument.containsKey(ID)) { 33 | throw new ContractContextException("wrong argument."); 34 | } 35 | 36 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 37 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 38 | } 39 | 40 | String holderId = property.get().getString(HOLDER_ID); 41 | String type = argument.getString(TYPE); 42 | String name = argument.getString(ASSET); 43 | long timestamp = argument.getJsonNumber(TIMESTAMP).longValue(); 44 | String id = argument.getString(ID); 45 | 46 | Optional optAsset = ledger.get(holderId + "-" + type); 47 | 48 | if (!optAsset.isPresent()) { 49 | return Json.createObjectBuilder() 50 | .add(RESULT, FAILURE) 51 | .add(MESSAGE, "Type " + type + " not found. Use am add-type to create it.") 52 | .build(); 53 | } 54 | 55 | optAsset = ledger.get(holderId + "-" + id); 56 | 57 | if (optAsset.isPresent()) { 58 | return Json.createObjectBuilder() 59 | .add(RESULT, FAILURE) 60 | .add(MESSAGE, "This asset is already registered.") 61 | .build(); 62 | } 63 | 64 | JsonObject assetStatusJson = 65 | Json.createObjectBuilder().add(TIMESTAMP, timestamp).add(STATUS, IN_STOCK).build(); 66 | ledger.put(holderId + "-" + id, assetStatusJson); 67 | 68 | JsonObject assetNameJson = Json.createObjectBuilder().add(ID, id).add(NAME, name).build(); 69 | ledger.put(holderId + "-" + type, assetNameJson); 70 | 71 | return Json.createObjectBuilder() 72 | .add(RESULT, SUCCESS) 73 | .add(MESSAGE, "asset " + name + " put completed.") 74 | .build(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/ListTypeContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.database.AssetFilter; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArray; 12 | import javax.json.JsonObject; 13 | import org.junit.Assert; 14 | import org.junit.Before; 15 | import org.junit.Rule; 16 | import org.junit.Test; 17 | import org.junit.rules.ExpectedException; 18 | import org.mockito.Mock; 19 | import org.mockito.Mockito; 20 | import org.mockito.MockitoAnnotations; 21 | 22 | public class ListTypeContractTest extends ContractTest { 23 | 24 | private ListTypeContract contract = new ListTypeContract(); 25 | private JsonObject argument; 26 | private JsonObject property; 27 | private JsonObject dataRecords; 28 | private List historyList = new ArrayList(); 29 | 30 | @Mock private Ledger ledger; 31 | @Mock private Asset asset; 32 | 33 | @Rule public ExpectedException thrown = ExpectedException.none(); 34 | 35 | @Before 36 | public void setUp() { 37 | MockitoAnnotations.initMocks(this); 38 | 39 | argument = Json.createObjectBuilder().add(ListTypeContract.TYPE, TYPE_EX).build(); 40 | property = 41 | Json.createObjectBuilder().add(AssetHistoryContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 42 | } 43 | 44 | private void setAssetRecords() { 45 | Mockito.when(asset.id()).thenReturn(ID_EX); 46 | Mockito.when(asset.age()).thenReturn(AGE_EX); 47 | dataRecords = Json.createObjectBuilder().add(ListTypeContract.NAME, NAME_EX).build(); 48 | Mockito.when(asset.data()).thenReturn(dataRecords); 49 | } 50 | 51 | @Test 52 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 53 | // Arrange 54 | JsonObject property = Json.createObjectBuilder().build(); 55 | thrown.expect(ContractContextException.class); 56 | thrown.expectMessage("property: `" + ListTypeContract.HOLDER_ID + "` is mandatory."); 57 | // Act 58 | contract.invoke(ledger, argument, Optional.of(property)); 59 | } 60 | 61 | @Test 62 | public void invoke_QueryWithNonexistingType_ShouldReturnFailure() { 63 | // Arrange 64 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(new ArrayList()); 65 | // Act 66 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 67 | // Assert 68 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 69 | Assert.assertNotNull(response.getString(MESSAGE)); 70 | } 71 | 72 | @Test 73 | public void invoke_QuerySingleAssetType_ShouldSucceed() { 74 | // Arrange 75 | setAssetRecords(); 76 | historyList.add(asset); 77 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(historyList); 78 | // Act 79 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 80 | // Assert 81 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 82 | Assert.assertNotNull(response.get(MESSAGE)); 83 | JsonArray types = response.getJsonArray(ListTypeContract.TYPES); 84 | JsonObject type = types.getJsonObject(0); 85 | Assert.assertEquals(NAME_EX, type.getString(ListTypeContract.TYPE)); 86 | Assert.assertEquals(AGE_EX, type.getInt(ListTypeContract.AGE)); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/AddTypeContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.exception.ContractContextException; 5 | import com.scalar.dl.ledger.database.Ledger; 6 | import java.util.Optional; 7 | import javax.json.Json; 8 | import javax.json.JsonObject; 9 | import org.junit.Assert; 10 | import org.junit.Before; 11 | import org.junit.Rule; 12 | import org.junit.Test; 13 | import org.junit.rules.ExpectedException; 14 | import org.mockito.Mock; 15 | import org.mockito.Mockito; 16 | import org.mockito.MockitoAnnotations; 17 | 18 | public class AddTypeContractTest extends ContractTest { 19 | 20 | private AddTypeContract contract = new AddTypeContract(); 21 | private JsonObject argument; 22 | private JsonObject property; 23 | private JsonObject newType; 24 | 25 | @Mock private Ledger ledger; 26 | @Mock private Asset asset; 27 | 28 | @Rule public ExpectedException thrown = ExpectedException.none(); 29 | 30 | @Before 31 | public void setUp() { 32 | MockitoAnnotations.initMocks(this); 33 | 34 | argument = Json.createObjectBuilder().add(AddTypeContract.NAME, NAME_EX).build(); 35 | property = Json.createObjectBuilder().add(AddAssetContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 36 | } 37 | 38 | private void setAssetRecords() { 39 | Mockito.when(asset.id()).thenReturn(ID_EX); 40 | Mockito.when(asset.age()).thenReturn(AGE_EX); 41 | Mockito.when(asset.data()).thenReturn(null); 42 | } 43 | 44 | private void setNewType() { 45 | newType = 46 | Json.createObjectBuilder() 47 | .add(AddTypeContract.NAME, argument.getString(AddTypeContract.NAME)) 48 | .build(); 49 | } 50 | 51 | @Test 52 | public void invoke_ArgumentWasNull_ShouldThrowContractContextException() { 53 | // Arrange 54 | JsonObject argument = Json.createObjectBuilder().build(); 55 | thrown.expect(ContractContextException.class); 56 | thrown.expectMessage("wrong argument."); 57 | // Act 58 | contract.invoke(ledger, argument, Optional.empty()); 59 | } 60 | 61 | @Test 62 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 63 | // Arrange 64 | JsonObject property = Json.createObjectBuilder().build(); 65 | thrown.expect(ContractContextException.class); 66 | thrown.expectMessage("property: `" + AddTypeContract.HOLDER_ID + "` is mandatory."); 67 | // Act 68 | contract.invoke(ledger, argument, Optional.of(property)); 69 | } 70 | 71 | @Test 72 | public void invoke_TypeAlreadyRegistered_ShouldReturnFailure() { 73 | // Arrange 74 | setAssetRecords(); 75 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + NAME_EX)).thenReturn(Optional.of(asset)); 76 | // Act 77 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 78 | // Assert 79 | Mockito.verify(ledger, Mockito.never()) 80 | .put(HOLDER_ID_1_EX + "-" + AddTypeContract.TYPE, newType); 81 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 82 | Assert.assertNotNull(response.getString(MESSAGE)); 83 | } 84 | 85 | @Test 86 | public void invoke_InsertNewType_ShouldRunProperly() { 87 | // Arrange 88 | setNewType(); 89 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + NAME_EX)).thenReturn(Optional.empty()); 90 | // Act 91 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 92 | // Assert 93 | Mockito.verify(ledger, Mockito.times(1)) 94 | .put(HOLDER_ID_1_EX + "-" + AddTypeContract.TYPE, newType); 95 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 96 | Assert.assertNotNull(response.getString(MESSAGE)); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/AssetHistoryContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.database.AssetFilter; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArray; 12 | import javax.json.JsonObject; 13 | import org.junit.Assert; 14 | import org.junit.Before; 15 | import org.junit.Rule; 16 | import org.junit.Test; 17 | import org.junit.rules.ExpectedException; 18 | import org.mockito.Mock; 19 | import org.mockito.Mockito; 20 | import org.mockito.MockitoAnnotations; 21 | 22 | public class AssetHistoryContractTest extends ContractTest { 23 | 24 | private AssetHistoryContract contract = new AssetHistoryContract(); 25 | private JsonObject argument; 26 | private JsonObject property; 27 | private JsonObject dataRecords; 28 | 29 | @Mock private Ledger ledger; 30 | @Mock private Asset asset; 31 | 32 | @Rule public ExpectedException thrown = ExpectedException.none(); 33 | 34 | @Before 35 | public void setUp() { 36 | MockitoAnnotations.initMocks(this); 37 | 38 | argument = Json.createObjectBuilder().add(AssetHistoryContract.ID, ID_EX).build(); 39 | property = 40 | Json.createObjectBuilder().add(AssetHistoryContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 41 | } 42 | 43 | private void setAssetRecords() { 44 | Mockito.when(asset.id()).thenReturn(ID_EX); 45 | Mockito.when(asset.age()).thenReturn(AGE_EX); 46 | dataRecords = 47 | Json.createObjectBuilder() 48 | .add(AssetHistoryContract.TIMESTAMP, TIMESTAMP_EX) 49 | .add(AssetHistoryContract.STATUS, IN_STOCK) 50 | .build(); 51 | Mockito.when(asset.data()).thenReturn(dataRecords); 52 | } 53 | 54 | @Test 55 | public void invoke_ArgumentWasNull_ShouldThrowContractContextException() { 56 | // Arrange 57 | JsonObject argument = Json.createObjectBuilder().build(); 58 | thrown.expect(ContractContextException.class); 59 | thrown.expectMessage("wrong argument."); 60 | // Act 61 | contract.invoke(ledger, argument, Optional.empty()); 62 | } 63 | 64 | @Test 65 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 66 | // Arrange 67 | JsonObject property = Json.createObjectBuilder().build(); 68 | thrown.expect(ContractContextException.class); 69 | thrown.expectMessage("property: `" + AssetHistoryContract.HOLDER_ID + "` is mandatory."); 70 | // Act 71 | contract.invoke(ledger, argument, Optional.of(property)); 72 | } 73 | 74 | @Test 75 | public void invoke_QueryNonexistingAsset_ShouldReturnFailure() { 76 | // Arrange 77 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(new ArrayList()); 78 | // Act 79 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 80 | // Assert 81 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 82 | Assert.assertNotNull(response.getString(MESSAGE)); 83 | } 84 | 85 | @Test 86 | public void invoke_AssetHistoryGiven_ShouldReturnHistoryOfAsset() { 87 | // Arrange 88 | setAssetRecords(); 89 | List borrowList = new ArrayList(); 90 | borrowList.add(asset); 91 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(borrowList); 92 | // Act 93 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 94 | // Assert 95 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 96 | Assert.assertNotNull(response.get(MESSAGE)); 97 | JsonArray types = response.getJsonArray(AssetHistoryContract.HISTORY); 98 | JsonObject type = types.getJsonObject(0); 99 | Assert.assertEquals( 100 | TIMESTAMP_EX, type.getJsonNumber(AssetHistoryContract.TIMESTAMP).longValue()); 101 | Assert.assertEquals(IN_STOCK, type.getString(AssetHistoryContract.STATUS)); 102 | Assert.assertEquals(AGE_EX, type.getInt(AssetHistoryContract.AGE)); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/StatusChangeContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.Optional; 8 | import javax.json.Json; 9 | import javax.json.JsonObject; 10 | import javax.json.JsonObjectBuilder; 11 | 12 | public class StatusChangeContract extends Contract { 13 | 14 | public static final String ASSET_ID = "asset_id"; 15 | public static final String TIMESTAMP = "timestamp"; 16 | public static final String STATUS = "status"; 17 | public static final String HOLDER_ID = "holderId"; 18 | 19 | private static final String RESULT = "result"; 20 | private static final String SUCCESS = "success"; 21 | private static final String FAILURE = "failure"; 22 | private static final String MESSAGE = "message"; 23 | 24 | public static final String ON_LOAN = "on-loan"; 25 | public static final String IN_STOCK = "in-stock"; 26 | 27 | @Override 28 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 29 | if (!argument.containsKey(ASSET_ID) 30 | || !argument.containsKey(STATUS) 31 | || !argument.containsKey(TIMESTAMP)) { 32 | throw new ContractContextException("wrong argument."); 33 | } 34 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 35 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 36 | } 37 | 38 | String holderId = property.get().getString(HOLDER_ID); 39 | String id = argument.getString(ASSET_ID); 40 | String newStatus = argument.getString(STATUS); 41 | long timestamp = argument.getJsonNumber(TIMESTAMP).longValue(); 42 | 43 | Optional asset = ledger.get(holderId + "-" + id); 44 | if (!asset.isPresent()) { 45 | return Json.createObjectBuilder() 46 | .add(RESULT, FAILURE) 47 | .add(MESSAGE, "Asset not found.") 48 | .build(); 49 | } 50 | 51 | JsonObject data = asset.get().data(); 52 | if (!data.containsKey(STATUS)) { 53 | return Json.createObjectBuilder() 54 | .add(RESULT, FAILURE) 55 | .add(MESSAGE, String.format("%s is not an asset", id)) 56 | .build(); 57 | } 58 | if (data.getString(STATUS).equals(newStatus)) { 59 | return Json.createObjectBuilder() 60 | .add(RESULT, FAILURE) 61 | .add( 62 | MESSAGE, 63 | String.format( 64 | "Asset is already %s.", ON_LOAN.equals(newStatus) ? "borrowed" : "returned")) 65 | .build(); 66 | } 67 | 68 | if (!property.isPresent()) { 69 | return Json.createObjectBuilder() 70 | .add(RESULT, FAILURE) 71 | .add(MESSAGE, "The property is missing") 72 | .build(); 73 | } 74 | if (!property.get().containsKey(HOLDER_ID)) { 75 | return Json.createObjectBuilder() 76 | .add(RESULT, FAILURE) 77 | .add(MESSAGE, "The property `holderId` is missing") 78 | .build(); 79 | } 80 | 81 | JsonObjectBuilder newDataBuilder = Json.createObjectBuilder(); 82 | if (newStatus.equals(ON_LOAN)) { 83 | newDataBuilder.add(HOLDER_ID, holderId).add(TIMESTAMP, timestamp).add(STATUS, newStatus); 84 | } else if (newStatus.equals(IN_STOCK)) { 85 | if (!data.containsKey(HOLDER_ID)) { 86 | return Json.createObjectBuilder() 87 | .add(RESULT, FAILURE) 88 | .add(MESSAGE, "Can not return asset without holderId") 89 | .build(); 90 | } 91 | if (!data.getString(HOLDER_ID).equals(holderId)) { 92 | return Json.createObjectBuilder() 93 | .add(RESULT, FAILURE) 94 | .add(MESSAGE, "Can not return asset borrowed by another user") 95 | .build(); 96 | } 97 | newDataBuilder.add(TIMESTAMP, timestamp).add(STATUS, newStatus); 98 | } 99 | ledger.put(holderId + "-" + id, newDataBuilder.build()); 100 | return Json.createObjectBuilder() 101 | .add(RESULT, SUCCESS) 102 | .add(MESSAGE, ON_LOAN.equals(newStatus) ? "Borrowed" : "Returned") 103 | .build(); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/contract/ListContract.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.contract.Contract; 5 | import com.scalar.dl.ledger.database.AssetFilter; 6 | import com.scalar.dl.ledger.exception.ContractContextException; 7 | import com.scalar.dl.ledger.database.Ledger; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArrayBuilder; 12 | import javax.json.JsonObject; 13 | import javax.json.JsonObjectBuilder; 14 | 15 | public class ListContract extends Contract { 16 | 17 | public static final String TYPE = "type"; 18 | public static final String ID = "id"; 19 | public static final String STATUS = "status"; 20 | public static final String NAME = "name"; 21 | public static final String TIMESTAMP = "timestamp"; 22 | public static final String HOLDER_ID = "holderId"; 23 | 24 | private static final String RESULT = "result"; 25 | private static final String SUCCESS = "success"; 26 | private static final String FAILURE = "failure"; 27 | private static final String MESSAGE = "message"; 28 | 29 | @Override 30 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 31 | if (!argument.containsKey(TYPE)) { 32 | throw new ContractContextException("wrong argument."); 33 | } 34 | if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) { 35 | throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory."); 36 | } 37 | 38 | String holderId = property.get().getString(HOLDER_ID); 39 | String type = argument.getString(TYPE); 40 | AssetFilter filter = new AssetFilter(holderId + "-" + type); 41 | 42 | List assetList = ledger.scan(filter); 43 | 44 | if (assetList.isEmpty()) { // means the type is not created yet 45 | return Json.createObjectBuilder() 46 | .add(RESULT, FAILURE) 47 | .add(MESSAGE, "Type " + type + " not found. Use am add-type to create it.") 48 | .build(); 49 | } 50 | 51 | /* 52 | * The history of key: is a list. E.g. history of book = [ {}, // initiated value when 53 | * book is created (age: 0) { "id": "ff02d8f3e5a85419df55ced87bf1bd68", "name": 54 | * "Java in a nutshell" }, // the first added book (age: 1) { "id": 55 | * "d41d8cd98f00b204e9800998ecf8427e", "name": "Java the good part" }, the second added book 56 | * (age: 2) ] 57 | * 58 | * For each book we have another key: book_ to store its borrowing status E.g. history of 59 | * book_ff02d8f3e5a85419df55ced87bf1bd68 = [ { "timestamp": ..., "status": "in-stock" }, // age: 60 | * 0 { "timestamp": ..., "status": "on-loan" }, // age: 1 ] 61 | */ 62 | JsonArrayBuilder assetsBuilder = Json.createArrayBuilder(); 63 | for (Asset asset : assetList) { 64 | JsonObject data = asset.data(); 65 | if (data.size() == 0) { // initiated one, ignore it 66 | continue; 67 | } 68 | String id = data.getString(ID); 69 | String name = data.getString(NAME); 70 | 71 | Optional borrowingStatus = ledger.get(holderId + "-" + id); 72 | if (!borrowingStatus.isPresent()) { 73 | /** 74 | * Abnormal case. We found an asset in list but no borrowing status record. Just ignore it 75 | */ 76 | continue; 77 | } 78 | 79 | JsonObjectBuilder statusBuilder = Json.createObjectBuilder(); 80 | statusBuilder 81 | .add(ID, id) 82 | .add(NAME, name) 83 | .add(TIMESTAMP, borrowingStatus.get().data().getJsonNumber(TIMESTAMP).longValue()) 84 | .add(STATUS, borrowingStatus.get().data().getString(STATUS)); 85 | 86 | if (borrowingStatus.get().data().containsKey(HOLDER_ID)) { 87 | statusBuilder.add(HOLDER_ID, borrowingStatus.get().data().getString(HOLDER_ID)); 88 | } 89 | 90 | assetsBuilder.add(statusBuilder.build()); 91 | } 92 | 93 | return Json.createObjectBuilder() 94 | .add(RESULT, SUCCESS) 95 | .add(MESSAGE, "get list completed.") 96 | .add(type, assetsBuilder.build()) 97 | .build(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/ListContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.database.AssetFilter; 5 | import com.scalar.dl.ledger.exception.ContractContextException; 6 | import com.scalar.dl.ledger.database.Ledger; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import javax.json.Json; 11 | import javax.json.JsonArray; 12 | import javax.json.JsonObject; 13 | import org.junit.Assert; 14 | import org.junit.Before; 15 | import org.junit.Rule; 16 | import org.junit.Test; 17 | import org.junit.rules.ExpectedException; 18 | import org.mockito.Mock; 19 | import org.mockito.Mockito; 20 | import org.mockito.MockitoAnnotations; 21 | 22 | public class ListContractTest extends ContractTest { 23 | 24 | private ListContract contract = new ListContract(); 25 | private JsonObject argument; 26 | private JsonObject property; 27 | private JsonObject dataRecords; 28 | private List list = new ArrayList(); 29 | 30 | @Mock private Ledger ledger; 31 | @Mock private Asset asset; 32 | 33 | @Rule public ExpectedException thrown = ExpectedException.none(); 34 | 35 | @Before 36 | public void setUp() { 37 | MockitoAnnotations.initMocks(this); 38 | 39 | argument = Json.createObjectBuilder().add(ListContract.TYPE, TYPE_EX).build(); 40 | property = 41 | Json.createObjectBuilder().add(AssetHistoryContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 42 | } 43 | 44 | private void setStatusRecords() { 45 | 46 | Mockito.when(asset.id()).thenReturn(ID_EX); 47 | Mockito.when(asset.age()).thenReturn(AGE_EX); 48 | 49 | dataRecords = 50 | Json.createObjectBuilder() 51 | .add(ListContract.ID, ID_EX) 52 | .add(ListContract.NAME, NAME_EX) 53 | .add(ListContract.TIMESTAMP, TIMESTAMP_EX) 54 | .add(ListContract.STATUS, IN_STOCK) 55 | .add(ListContract.HOLDER_ID, HOLDER_ID_1_EX) 56 | .build(); 57 | Mockito.when(asset.data()).thenReturn(dataRecords); 58 | 59 | list.add(asset); 60 | } 61 | 62 | @Test 63 | public void invoke_ArgumentWasNull_ShouldThrowContractContextException() { 64 | // Arrange 65 | JsonObject argument = Json.createObjectBuilder().build(); 66 | thrown.expect(ContractContextException.class); 67 | thrown.expectMessage("wrong argument."); 68 | // Act 69 | contract.invoke(ledger, argument, Optional.empty()); 70 | } 71 | 72 | @Test 73 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 74 | // Arrange 75 | JsonObject property = Json.createObjectBuilder().build(); 76 | thrown.expect(ContractContextException.class); 77 | thrown.expectMessage("property: `" + ListContract.HOLDER_ID + "` is mandatory."); 78 | // Act 79 | contract.invoke(ledger, argument, Optional.of(property)); 80 | } 81 | 82 | @Test 83 | public void invoke_QueryNonExistingType_ShouldReturnFailure() { 84 | // Arrange 85 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(new ArrayList()); 86 | // Act 87 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 88 | // Assert 89 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 90 | Assert.assertNotNull(response.getString(MESSAGE)); 91 | } 92 | 93 | @Test 94 | public void invoke_QueryBookList_ShouldReturnProperly() { 95 | // Arrange 96 | setStatusRecords(); 97 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(list); 98 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + ID_EX)).thenReturn(Optional.of(asset)); 99 | // Act 100 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 101 | // Assert 102 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 103 | Assert.assertNotNull(response.getString(MESSAGE)); 104 | 105 | JsonArray assets = response.getJsonArray(TYPE_EX); 106 | Assert.assertEquals(1, assets.size()); 107 | 108 | JsonObject asset = assets.getJsonObject(0); 109 | Assert.assertEquals(ID_EX, asset.getString(ListContract.ID)); 110 | Assert.assertEquals(NAME_EX, asset.getString(ListContract.NAME)); 111 | Assert.assertEquals(TIMESTAMP_EX, asset.getJsonNumber(ListContract.TIMESTAMP).longValue()); 112 | Assert.assertEquals(IN_STOCK, asset.getString(ListContract.STATUS)); 113 | Assert.assertEquals(HOLDER_ID_1_EX, asset.getString(ListContract.HOLDER_ID)); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/AddAssetContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.exception.ContractContextException; 5 | import com.scalar.dl.ledger.database.Ledger; 6 | import java.util.Date; 7 | import java.util.Optional; 8 | import javax.json.Json; 9 | import javax.json.JsonObject; 10 | import org.junit.Assert; 11 | import org.junit.Before; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.junit.rules.ExpectedException; 15 | import org.mockito.Mock; 16 | import org.mockito.Mockito; 17 | import org.mockito.MockitoAnnotations; 18 | 19 | public class AddAssetContractTest extends ContractTest { 20 | 21 | private AddAssetContract contract = new AddAssetContract(); 22 | private JsonObject argument; 23 | private JsonObject property; 24 | private JsonObject assetStatusJson; 25 | private JsonObject assetNameJson; 26 | 27 | @Mock private Ledger ledger; 28 | @Mock private Asset asset; 29 | @Mock private Asset asset1; 30 | 31 | @Rule public ExpectedException thrown = ExpectedException.none(); 32 | 33 | @Before 34 | public void setUp() { 35 | MockitoAnnotations.initMocks(this); 36 | 37 | argument = 38 | Json.createObjectBuilder() 39 | .add(AddAssetContract.ID, ID_EX) 40 | .add(AddAssetContract.TIMESTAMP, new Date().getTime()) 41 | .add(AddAssetContract.TYPE, TYPE_EX) 42 | .add(AddAssetContract.ASSET, ASSET_EX) 43 | .build(); 44 | 45 | property = Json.createObjectBuilder().add(AddAssetContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 46 | } 47 | 48 | private void setLegerPutValue() { 49 | assetStatusJson = 50 | Json.createObjectBuilder() 51 | .add(AddAssetContract.TIMESTAMP, argument.getJsonNumber(AddAssetContract.TIMESTAMP)) 52 | .add(AddAssetContract.STATUS, IN_STOCK) 53 | .build(); 54 | assetNameJson = 55 | Json.createObjectBuilder() 56 | .add(AddAssetContract.ID, argument.getString(AddAssetContract.ID)) 57 | .add(AddAssetContract.NAME, argument.getString(AddAssetContract.ASSET)) 58 | .build(); 59 | } 60 | 61 | @Test 62 | public void invoke_ArgumentWasNull_ShouldThrowContractContextException() { 63 | // Arrange 64 | JsonObject argument = Json.createObjectBuilder().build(); 65 | thrown.expect(ContractContextException.class); 66 | thrown.expectMessage("wrong argument."); 67 | // Act 68 | contract.invoke(ledger, argument, Optional.empty()); 69 | } 70 | 71 | @Test 72 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 73 | // Arrange 74 | JsonObject property = Json.createObjectBuilder().build(); 75 | thrown.expect(ContractContextException.class); 76 | thrown.expectMessage("property: `" + AddAssetContract.HOLDER_ID + "` is mandatory."); 77 | // Act 78 | contract.invoke(ledger, argument, Optional.of(property)); 79 | } 80 | 81 | @Test 82 | public void invoke_AddNonExistingAsset_ShouldReturnFailure() { 83 | // Arrange 84 | Mockito.when(ledger.get(TYPE_EX)).thenReturn(Optional.empty()); 85 | // Act 86 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 87 | // Assert 88 | Mockito.verify(ledger, Mockito.never()).put(ID_EX, assetStatusJson); 89 | Mockito.verify(ledger, Mockito.never()).put(TYPE_EX, assetStatusJson); 90 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 91 | Assert.assertNotNull(response.getString(MESSAGE)); 92 | } 93 | 94 | @Test 95 | public void invoke_AddAlreadyRegisteredAsset_ShouldReturnFailure() { 96 | // Arrange 97 | Mockito.when(ledger.get(TYPE_EX)).thenReturn(Optional.of(asset)); 98 | Mockito.when(ledger.get(ID_EX)).thenReturn(Optional.of(asset1)); 99 | // Act 100 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 101 | // Assert 102 | Mockito.verify(ledger, Mockito.never()).put(ID_EX, assetStatusJson); 103 | Mockito.verify(ledger, Mockito.never()).put(TYPE_EX, assetStatusJson); 104 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 105 | Assert.assertNotNull(response.getString(MESSAGE)); 106 | } 107 | 108 | @Test 109 | public void invoke_AddRegisteredAsset_ShouldRunProperly() { 110 | // Arrange 111 | setLegerPutValue(); 112 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + TYPE_EX)).thenReturn(Optional.of(asset)); 113 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + ID_EX)).thenReturn(Optional.empty()); 114 | // Act 115 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 116 | // Assert 117 | Mockito.verify(ledger, Mockito.times(1)).put(HOLDER_ID_1_EX + "-" + ID_EX, assetStatusJson); 118 | Mockito.verify(ledger, Mockito.times(1)).put(HOLDER_ID_1_EX + "-" + TYPE_EX, assetNameJson); 119 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 120 | Assert.assertNotNull(response.getString(MESSAGE)); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/LedgerClientExecutor.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.google.inject.Guice; 4 | import com.google.inject.Injector; 5 | import com.scalar.dl.client.config.ClientConfig; 6 | import com.scalar.dl.client.service.ClientModule; 7 | import com.scalar.dl.client.service.ClientService; 8 | import com.scalar.dl.ledger.model.ContractExecutionResult; 9 | import com.scalar.dl.ledger.model.LedgerValidationResult; 10 | import com.scalar.dl.ledger.service.StatusCode; 11 | 12 | import java.io.File; 13 | import java.security.MessageDigest; 14 | import java.security.NoSuchAlgorithmException; 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | import javax.json.Json; 18 | import javax.json.JsonObject; 19 | import javax.json.JsonWriter; 20 | import javax.json.JsonWriterFactory; 21 | import javax.json.stream.JsonGenerator; 22 | import javax.xml.bind.DatatypeConverter; 23 | 24 | /** Class used to execute method on a {@link com.scalar.dl.ledger.database.Ledger} */ 25 | abstract class LedgerClientExecutor { 26 | 27 | private ClientConfig loadClientConfig() throws Exception { 28 | File file = new File(System.getProperty("user.dir") + File.separator + "client.properties"); 29 | return new ClientConfig(file); 30 | } 31 | 32 | /** 33 | * Execute the contract on the ledger.
34 | * First, it will lookup on the configuration which id has been used to register the contract and 35 | * then execute it.
36 | * The output will be printed to the standard output. 37 | * 38 | * @param contractName the contract name 39 | * @param contractParameter the parameter that will be passed to the contract 40 | */ 41 | protected void executeContract(String contractName, JsonObject contractParameter) { 42 | try { 43 | ClientConfig config = loadClientConfig(); 44 | String contractId = contractName + "_" + config.getCertHolderId(); 45 | 46 | LedgerExecutorFunction f = 47 | (clientService) -> { 48 | JsonObject object = 49 | (contractParameter != null) 50 | ? contractParameter 51 | : Json.createObjectBuilder().build(); 52 | try { 53 | ContractExecutionResult result = clientService.executeContract(contractId, object); 54 | prettyPrintJson(result.getResult().get()); 55 | } catch (Exception ex) { 56 | System.err.println("Error during contract execution"); 57 | } 58 | }; 59 | 60 | this.executeOnLedger(f); 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | } 64 | } 65 | 66 | protected void validateAsset(String id) { 67 | try { 68 | ClientConfig config = loadClientConfig(); 69 | String contractId = config.getCertHolderId() + "-" + id; 70 | LedgerExecutorFunction f = 71 | (clientService) -> { 72 | LedgerValidationResult result = clientService.validateLedger(contractId); 73 | if (!(result.getCode().equals(StatusCode.OK))) { 74 | System.err.println("Error during asset validate"); 75 | System.err.println("Status code: " + result.getCode().get()); 76 | return; 77 | } 78 | System.out.println("Asset " + id + " is untampered"); 79 | }; 80 | 81 | executeOnLedger(f); 82 | } catch (Exception e) { 83 | e.printStackTrace(); 84 | } 85 | } 86 | 87 | /** 88 | * Execute the function on the ledger passed on the configuration 89 | * 90 | * @param f the function to execute 91 | */ 92 | protected final void executeOnLedger(LedgerExecutorFunction f) throws Exception { 93 | ClientConfig config = loadClientConfig(); 94 | Injector injector = Guice.createInjector(new ClientModule(config)); 95 | try (ClientService clientService = injector.getInstance(ClientService.class)) { 96 | f.execute(clientService); 97 | } 98 | } 99 | 100 | /** 101 | * Pretty print the json to the standard output 102 | * 103 | * @param jsonObject the json to print 104 | */ 105 | protected void prettyPrintJson(JsonObject jsonObject) { 106 | if (jsonObject != null) { 107 | System.out.println("[Return]"); 108 | Map config = new HashMap<>(1); 109 | config.put(JsonGenerator.PRETTY_PRINTING, true); 110 | JsonWriterFactory factory = Json.createWriterFactory(config); 111 | JsonWriter writer = factory.createWriter(System.out); 112 | writer.writeObject(jsonObject); 113 | writer.close(); 114 | } 115 | } 116 | 117 | @FunctionalInterface 118 | protected interface LedgerExecutorFunction { 119 | void execute(ClientService service) throws Exception; 120 | } 121 | 122 | protected static String getHashHexString(String name) { 123 | String hashed = null; 124 | try { 125 | if (name != null) { 126 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 127 | byte[] bytes = md5.digest(name.getBytes()); 128 | hashed = DatatypeConverter.printHexBinary(bytes); 129 | } 130 | } catch (NoSuchAlgorithmException e) { 131 | e.printStackTrace(); 132 | } 133 | 134 | return hashed; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/integration-test/java/com/scalar/am/e2e/EndToEnd.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.e2e; 2 | 3 | import com.scalar.am.AssetManager; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.PrintStream; 6 | import java.io.StringReader; 7 | import java.io.UnsupportedEncodingException; 8 | import javax.json.Json; 9 | import javax.json.JsonArray; 10 | import javax.json.JsonObject; 11 | import javax.json.JsonObjectBuilder; 12 | import javax.json.JsonReader; 13 | import javax.json.stream.JsonParsingException; 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | import picocli.CommandLine; 17 | 18 | public class EndToEnd { 19 | 20 | final String RESULT = "result"; 21 | final String MESSAGE = "message"; 22 | final String SUCCESS = "success"; 23 | 24 | JsonObject result = null; 25 | 26 | public JsonObject getCommandOutput(String... args) throws UnsupportedEncodingException { 27 | JsonObject result = null; 28 | String[] commandArgs = args.length != 0 ? args : new String[] {"--help"}; 29 | ByteArrayOutputStream output = new ByteArrayOutputStream(); 30 | try (PrintStream ps = new PrintStream(output, true, "UTF-8")) { 31 | PrintStream previousOut = System.out; 32 | System.setOut(ps); 33 | CommandLine.run(new AssetManager(), ps, commandArgs); 34 | System.setOut(previousOut); 35 | } 36 | String commandOutput = output.toString().replace("[Return]", ""); 37 | System.out.println(commandOutput); 38 | try { 39 | JsonReader jsonReader = Json.createReader(new StringReader(commandOutput)); 40 | result = jsonReader.readObject(); 41 | jsonReader.close(); 42 | } catch (JsonParsingException e) { 43 | result = null; 44 | } 45 | 46 | return result; 47 | } 48 | 49 | @Test 50 | public void runEndToEnd() throws UnsupportedEncodingException { 51 | // init 52 | String address = System.getenv("SCALAR_NETWORK_ADDRESS"); 53 | String port = System.getenv("SCALAR_NETWORK_PORT"); 54 | result = 55 | getCommandOutput( 56 | "init", "./fixture/foo-key.pem", "./fixture/foo.pem", "-host", address, "-p", port); 57 | JsonObject initExpected = null; 58 | Assert.assertEquals(initExpected, result); 59 | // add-type 60 | result = getCommandOutput("add-type", "book"); 61 | JsonObject addTypeExpected = 62 | Json.createObjectBuilder() 63 | .add(RESULT, SUCCESS) 64 | .add(MESSAGE, "type book put completed.") 65 | .build(); 66 | Assert.assertEquals(addTypeExpected, result); 67 | // list-type 68 | result = getCommandOutput("list-type"); 69 | JsonObjectBuilder listTypeExpected = 70 | Json.createObjectBuilder().add(RESULT, SUCCESS).add(MESSAGE, "get list completed."); 71 | JsonObject typesJson = Json.createObjectBuilder().add("type", "book").add("age", 0).build(); 72 | JsonArray types = Json.createArrayBuilder().add(typesJson).build(); 73 | listTypeExpected.add("types", types); 74 | Assert.assertEquals(listTypeExpected.build(), result); 75 | // list 76 | result = getCommandOutput("list", "book"); 77 | JsonObjectBuilder listExpected = Json.createObjectBuilder(); 78 | JsonArray book = Json.createArrayBuilder().build(); 79 | listExpected.add(RESULT, SUCCESS).add(MESSAGE, "get list completed.").add("book", book); 80 | Assert.assertEquals(listExpected.build(), result); 81 | // add 82 | result = getCommandOutput("add", "book", "comicexample"); 83 | JsonObject addExpected = 84 | Json.createObjectBuilder() 85 | .add(RESULT, SUCCESS) 86 | .add(MESSAGE, "asset comicexample put completed.") 87 | .build(); 88 | Assert.assertEquals(addExpected, result); 89 | // asset-history 90 | result = getCommandOutput("asset-history", "book", "comicexample"); 91 | JsonObjectBuilder assetHistoryExpected = 92 | Json.createObjectBuilder().add(RESULT, SUCCESS).add(MESSAGE, "get history complete."); 93 | JsonObjectBuilder assetHistoryJson = Json.createObjectBuilder(); 94 | long timestamp = 0; 95 | JsonArray resultHistoryArray = result.getJsonArray("history"); 96 | for (int i = 0; i < resultHistoryArray.size(); i++) { 97 | JsonObject resultHistoryObject = resultHistoryArray.getJsonObject(i); 98 | timestamp = resultHistoryObject.getJsonNumber("timestamp").longValue(); 99 | } 100 | assetHistoryJson.add("timestamp", timestamp).add("status", "in-stock").add("age", 0); 101 | JsonArray history = Json.createArrayBuilder().add(assetHistoryJson).build(); 102 | assetHistoryExpected.add("history", history); 103 | Assert.assertEquals(assetHistoryExpected.build(), result); 104 | // borrow 105 | result = getCommandOutput("borrow", "book", "comicexample"); 106 | JsonObject borrowExpected = 107 | Json.createObjectBuilder().add(RESULT, SUCCESS).add(MESSAGE, "Borrowed").build(); 108 | Assert.assertEquals(borrowExpected, result); 109 | // return 110 | result = getCommandOutput("return", "book", "comicexample"); 111 | JsonObject returnExpected = 112 | Json.createObjectBuilder().add(RESULT, SUCCESS).add(MESSAGE, "Returned").build(); 113 | Assert.assertEquals(returnExpected, result); 114 | // validate 115 | result = getCommandOutput("validate", "book"); 116 | JsonObject validateExpected = null; 117 | Assert.assertEquals(validateExpected, result); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /manual/README.md: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | This is a simple command-line interface application for demonstration purposes of Scalar DL. 3 | Users can use this application to create asset categories, create new assets and borrow/return assets. 4 | All states of assets are shared with all the other users on the same Scalar DL network. 5 | 6 | ## Build the the application 7 | 8 | Please install JDK 8 before building and launching this application. 9 | 10 | To launch the application, two things are necessary : 11 | - a self-contained jar file containing the Scalar DL client libraries and the source code of this application 12 | - a folder named *contract* which contains the contract files used by the application 13 | 14 | To generate these files, please run the following command. A contract 15 | folder will be created in the application's root directory. 16 | ``` 17 | ./gradlew prepare 18 | ``` 19 | 20 | ## Command-line interface 21 | 22 | A executable jar file `am-1.0.jar` can be generated in the root folder using `./gradlew prepare`. 23 | We can use this pattern to execute different commands. 24 | 25 | ``` 26 | java -jar am-1.0.jar [|] 27 | ``` 28 | 29 | ### `init` command 30 | `init` command is used to generate a config file `client.properties` so that the other commands can use it to connect to a Scalar DL network afterwards. 31 | 32 | ``` 33 | java -jar am-1.0.jar init [-h] [-tls] [-credential=] [-host=] [-p=] private-key certificate 34 | ``` 35 | 36 | #### Connect to Scalar DL Sandbox 37 | We can test this application with Scalar DL Sandbox provided by Scalar, Inc. 38 | Please refer [this](./use-scalar-dl-sandbox.md) to apply for your holder id, private key, certificate and authentication credential. 39 | When you have your `key`, `certificate` and `credential`, use following `init` command example to generate the `client.properties` for connecting to Scalar DL Sandbox. 40 | ``` 41 | java -jar am-1.0.jar init -tls -credential='Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx== 42 | ' -host='sandbox.scalar-labs.com' -p=443 /tmp/foo-key.pem /tmp/foo.pem 43 | ``` 44 | 45 | #### Options 46 | |name|usage| 47 | |----|-----| 48 | |-h|Display help| 49 | |-host=``|Use the host address to connect to one server of the Scalar DL network. Default: `localhost`| 50 | |-p=``|Use the port to connect to the one server of the Scalar DL network. Default: `50051`| 51 | |-tls|Enable TLS connection| 52 | |-credential=``|Specify the authentication token to connect to the Scalar DL network| 53 | 54 | #### Arguments 55 | |name|usage| 56 | |----|-----| 57 | |private-key|The path of private key file| 58 | |certificate|The path of certificate file| 59 | 60 | ### `list-type` command 61 | To list existing asset categories. 62 | 63 | ``` 64 | java -jar am-1.0.jar list-type 65 | ``` 66 | 67 | ### `add-type` command 68 | To add a new asset category. 69 | 70 | ``` 71 | java -jar am-1.0.jar add-type [-h] asset_type 72 | ``` 73 | 74 | #### Options 75 | |name|usage| 76 | |----|-----| 77 | |-h|Display help| 78 | 79 | #### Arguments 80 | |name|usage| 81 | |----|-----| 82 | |asset_type|New category's name| 83 | 84 | 85 | ### `list` command 86 | To list all existing assets and their borrowing status for the specified category. 87 | 88 | ``` 89 | java -jar am-1.0.jar list [-h] asset_type 90 | ``` 91 | 92 | #### Options 93 | |name|usage| 94 | |----|-----| 95 | |-h|Display help| 96 | 97 | #### Arguments 98 | |name|usage| 99 | |----|-----| 100 | |asset_type|The category's name to list all assets| 101 | 102 | 103 | ### `add` command 104 | To add a new asset to the specified category. 105 | 106 | ``` 107 | java -jar am-1.0.jar add [-h] asset_type asset 108 | ``` 109 | 110 | #### Options 111 | |name|usage| 112 | |----|-----| 113 | |-h|Display help| 114 | 115 | #### Arguments 116 | |name|usage| 117 | |----|-----| 118 | |asset_type|The category's name to add new asset| 119 | |asset|New asset's name| 120 | 121 | ### `borrow` command 122 | To borrow an asset. 123 | 124 | ``` 125 | java -jar am-1.0.jar borrow [-h] arguments... 126 | ``` 127 | 128 | #### Options 129 | |name|usage| 130 | |----|-----| 131 | |-h|Display help| 132 | 133 | #### Arguments 134 | Can be either format of ` ` 135 | 136 | |name|usage| 137 | |----|-----| 138 | |type|The category's name of the borrowing asset| 139 | |name|The borrowing asset's name| 140 | 141 | or format of `` 142 | 143 | |name|usage| 144 | |----|-----| 145 | |id|The borrowing asset's id| 146 | 147 | ### `return` command 148 | 149 | To return an asset. 150 | 151 | ``` 152 | java -jar am-1.0.jar return [-h] arguments... 153 | ``` 154 | 155 | #### Options 156 | |name|usage| 157 | |----|-----| 158 | |-h|Display help| 159 | 160 | #### Arguments 161 | Can be either format of ` ` 162 | 163 | |name|usage| 164 | |----|-----| 165 | |type|The category's name of the returning asset| 166 | |name|The returning asset's name| 167 | 168 | or format of `` 169 | 170 | |name|usage| 171 | |----|-----| 172 | |id|The returning asset's id| 173 | 174 | ### `asset-history` command 175 | To display the borrowing status for the specified asset. 176 | 177 | ``` 178 | java -jar am-1.0.jar asset-history [-h] arguments... 179 | ``` 180 | 181 | #### Options 182 | |name|usage| 183 | |----|-----| 184 | |-h|Display help| 185 | 186 | #### Arguments 187 | Can be either format of ` ` 188 | 189 | |name|usage| 190 | |----|-----| 191 | |type|The category's name of the asset| 192 | |name|The asset's name| 193 | 194 | or format of `` 195 | 196 | |name|usage| 197 | |----|-----| 198 | |id|The asset's id| 199 | 200 | ### `validate` command 201 | To validate tamper-evidence for the specified asset. 202 | 203 | ``` 204 | java -jar am-1.0.jar validate [-h] asset... 205 | ``` 206 | #### Options 207 | |name|usage| 208 | |----|-----| 209 | |-h|Display help| 210 | 211 | #### Arguments 212 | Can be either format of ` ` 213 | 214 | |name|usage| 215 | |----|-----| 216 | |type|The category's name of the asset| 217 | |name|The asset's name| 218 | 219 | or format of `` 220 | 221 | |name|usage| 222 | |----|-----| 223 | |id|The asset's id| 224 | -------------------------------------------------------------------------------- /src/main/java/com/scalar/am/command/Init.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.command; 2 | 3 | import com.scalar.am.contract.AddAssetContract; 4 | import com.scalar.am.contract.AddTypeContract; 5 | import com.scalar.am.contract.AssetHistoryContract; 6 | import com.scalar.am.contract.ListContract; 7 | import com.scalar.am.contract.ListTypeContract; 8 | import com.scalar.am.contract.StatusChangeContract; 9 | import com.scalar.dl.client.config.ClientConfig; 10 | import com.scalar.dl.client.service.ClientService; 11 | import java.io.File; 12 | import java.io.FileOutputStream; 13 | import java.io.IOException; 14 | import java.io.OutputStream; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.nio.file.StandardCopyOption; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | import java.util.Optional; 21 | import java.util.Properties; 22 | import java.util.UUID; 23 | import javax.json.Json; 24 | import javax.json.JsonObject; 25 | import picocli.CommandLine; 26 | 27 | /** This class defines the behaviour of init CLI command */ 28 | @CommandLine.Command(name = "init", description = "Initialize the asset management application") 29 | public class Init extends LedgerClientExecutor implements Runnable { 30 | @CommandLine.Option( 31 | names = {"-host"}, 32 | description = "the host address of the scalar DL installation", 33 | defaultValue = "localhost") 34 | private String host; 35 | 36 | @CommandLine.Option( 37 | names = { 38 | "-p", 39 | }, 40 | description = "the port of the scalar DL installation", 41 | defaultValue = "50051") 42 | private int port; 43 | 44 | @CommandLine.Option( 45 | names = {"-tls"}, 46 | description = "enable TLS connection") 47 | private boolean tls; 48 | 49 | @CommandLine.Option( 50 | names = {"-credential"}, 51 | description = "the authentication cerdential", 52 | defaultValue = "") 53 | private String credential; 54 | 55 | @CommandLine.Option( 56 | names = {"-h"}, 57 | usageHelp = true, 58 | description = "display this help and exit") 59 | private boolean help; 60 | 61 | @CommandLine.Parameters( 62 | index = "0", 63 | paramLabel = "private-key", 64 | description = "path to the private key") 65 | private File privateKey; 66 | 67 | @CommandLine.Parameters( 68 | index = "1", 69 | paramLabel = "certificate", 70 | description = "path to the certificate") 71 | private File certificate; 72 | 73 | private static final String CONTRACT_DIR = 74 | System.getProperty("user.dir") + File.separator + "contract"; 75 | private static final String CLIENT_PROPERTIES_PATH = 76 | System.getProperty("user.dir") + File.separator + "client.properties"; 77 | 78 | @Override 79 | public void run() { 80 | try { 81 | ClientConfig clientConfig = createClientConfig(); 82 | LedgerExecutorFunction f = 83 | (clientService) -> { 84 | registerCertificate(clientService); 85 | registerContracts(clientService, clientConfig); 86 | }; 87 | executeOnLedger(f); 88 | } catch (Exception e) { 89 | 90 | e.printStackTrace(); 91 | } 92 | } 93 | 94 | String copyKey() throws IOException { 95 | Path privateKeyCopy = 96 | new File(System.getProperty("user.dir") + File.separator + privateKey.getName()).toPath(); 97 | Path privateKey = this.privateKey.toPath(); 98 | Files.copy(privateKey, privateKeyCopy, StandardCopyOption.REPLACE_EXISTING); 99 | return privateKeyCopy.toAbsolutePath().toString(); 100 | } 101 | 102 | String copyCert() throws IOException { 103 | Path certificateCopy = 104 | new File(System.getProperty("user.dir") + File.separator + certificate.getName()).toPath(); 105 | Path certificate = this.certificate.toPath(); 106 | Files.copy(certificate, certificateCopy, StandardCopyOption.REPLACE_EXISTING); 107 | return certificateCopy.toAbsolutePath().toString(); 108 | } 109 | 110 | private ClientConfig createClientConfig() throws Exception { 111 | String privateKeyPath = copyKey(); 112 | String certPath = copyCert(); 113 | 114 | Properties prop = new Properties(); 115 | prop.setProperty(ClientConfig.SERVER_HOST, this.host); 116 | prop.setProperty(ClientConfig.SERVER_PORT, Integer.toString(this.port)); 117 | prop.setProperty(ClientConfig.CERT_HOLDER_ID, UUID.randomUUID().toString()); 118 | prop.setProperty(ClientConfig.CERT_VERSION, Integer.toString(1)); 119 | prop.setProperty(ClientConfig.CERT_PATH, certPath); 120 | prop.setProperty(ClientConfig.PRIVATE_KEY_PATH, privateKeyPath); 121 | prop.setProperty(ClientConfig.TLS_ENABLED, String.valueOf(this.tls)); 122 | prop.setProperty(ClientConfig.AUTHORIZATION_CREDENTIAL, this.credential); 123 | 124 | OutputStream output = new FileOutputStream(CLIENT_PROPERTIES_PATH); 125 | prop.store(output, null); 126 | output.close(); 127 | 128 | return new ClientConfig(prop); 129 | } 130 | 131 | private void registerCertificate(ClientService service) throws Exception { 132 | try { 133 | service.registerCertificate(); 134 | } catch (Exception ex) { 135 | throw new Exception("Error during certificate registration"); 136 | } 137 | } 138 | 139 | private void registerContracts(ClientService service, ClientConfig config) throws Exception { 140 | String holderId = config.getCertHolderId(); 141 | 142 | List> contracts = 143 | Arrays.asList( 144 | AddAssetContract.class, 145 | AddTypeContract.class, 146 | ListTypeContract.class, 147 | ListContract.class, 148 | StatusChangeContract.class, 149 | AssetHistoryContract.class); 150 | 151 | JsonObject property = Json.createObjectBuilder().add("holderId", holderId).build(); 152 | 153 | for (Class contract : contracts) { 154 | File file = new File(CONTRACT_DIR + File.separator + contract.getSimpleName() + ".class"); 155 | if (!file.exists()) { 156 | throw new Exception("Can not find contract: " + contract.getSimpleName()); 157 | } 158 | 159 | String name = contract.getCanonicalName(); 160 | String id = name + "_" + holderId; 161 | String path = file.getAbsolutePath(); 162 | 163 | try { 164 | service.registerContract(id, name, path, Optional.ofNullable(property)); 165 | } catch (Exception ex) { 166 | throw new Exception("Failed to register contract"); 167 | } 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/test/java/com/scalar/am/contract/StatusChangeContractTest.java: -------------------------------------------------------------------------------- 1 | package com.scalar.am.contract; 2 | 3 | import com.scalar.dl.ledger.asset.Asset; 4 | import com.scalar.dl.ledger.exception.ContractContextException; 5 | import com.scalar.dl.ledger.database.Ledger; 6 | import java.util.Date; 7 | import java.util.Optional; 8 | import javax.json.Json; 9 | import javax.json.JsonObject; 10 | import javax.json.JsonObjectBuilder; 11 | import org.junit.Assert; 12 | import org.junit.Before; 13 | import org.junit.Rule; 14 | import org.junit.Test; 15 | import org.junit.rules.ExpectedException; 16 | import org.mockito.Mock; 17 | import org.mockito.Mockito; 18 | import org.mockito.MockitoAnnotations; 19 | 20 | public class StatusChangeContractTest extends ContractTest { 21 | 22 | private StatusChangeContract contract = new StatusChangeContract(); 23 | private JsonObjectBuilder argumentBuilder = Json.createObjectBuilder(); 24 | private JsonObjectBuilder assetStatusJsonBuilder = Json.createObjectBuilder(); 25 | private JsonObjectBuilder propertyBuilder = Json.createObjectBuilder(); 26 | 27 | @Mock private Ledger ledger; 28 | @Mock private Asset asset; 29 | 30 | @Rule public ExpectedException thrown = ExpectedException.none(); 31 | 32 | @Before 33 | public void setUp() { 34 | MockitoAnnotations.initMocks(this); 35 | 36 | argumentBuilder 37 | .add(StatusChangeContract.ASSET_ID, ASSET_ID_EX) 38 | .add(StatusChangeContract.TIMESTAMP, new Date().getTime()); 39 | 40 | Mockito.when(asset.id()).thenReturn(ID_EX); 41 | Mockito.when(asset.age()).thenReturn(AGE_EX); 42 | } 43 | 44 | private void setNewStatusAndCurrentStatus(String newStatus, String currentStatus) { 45 | argumentBuilder.add(StatusChangeContract.STATUS, newStatus); 46 | if (currentStatus != null) { 47 | assetStatusJsonBuilder.add(StatusChangeContract.STATUS, currentStatus); 48 | } 49 | } 50 | 51 | private void setHasContractHolderIdAndHasAssetHolderId( 52 | String contractHolderId, String assetHolderId) { 53 | propertyBuilder.add(StatusChangeContract.HOLDER_ID, contractHolderId); 54 | assetStatusJsonBuilder.add(StatusChangeContract.HOLDER_ID, assetHolderId); 55 | } 56 | 57 | @Test 58 | public void invoke_ArgumentWasNull_ShouldThrowContractContextException() { 59 | // Arrange 60 | JsonObject argument = Json.createObjectBuilder().build(); 61 | thrown.expect(ContractContextException.class); 62 | thrown.expectMessage("wrong argument."); 63 | // Act 64 | contract.invoke(ledger, argument, Optional.empty()); 65 | // Assert 66 | Mockito.verify(ledger, Mockito.never()).put(ASSET_ID_EX, assetStatusJsonBuilder.build()); 67 | } 68 | 69 | @Test 70 | public void invoke_PropertyWasNull_ShouldThrowContractContextException() { 71 | // Arrange 72 | JsonObject property = Json.createObjectBuilder().build(); 73 | JsonObject argument = 74 | argumentBuilder.add(StatusChangeContract.STATUS, StatusChangeContract.ON_LOAN).build(); 75 | thrown.expect(ContractContextException.class); 76 | thrown.expectMessage("property: `" + StatusChangeContract.HOLDER_ID + "` is mandatory."); 77 | // Act 78 | contract.invoke(ledger, argument, Optional.of(property)); 79 | } 80 | 81 | @Test 82 | public void invoke_QueryNonexistingAsset_ShouldReturnFailure() { 83 | // Arrange 84 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + ASSET_ID_EX)).thenReturn(Optional.empty()); 85 | JsonObject argument = 86 | Json.createObjectBuilder() 87 | .add(StatusChangeContract.ASSET_ID, ASSET_ID_EX) 88 | .add(StatusChangeContract.TIMESTAMP, 0) // N/A 89 | .add(StatusChangeContract.STATUS, "") // N/A 90 | .build(); 91 | JsonObject property = 92 | propertyBuilder.add(StatusChangeContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 93 | // Act 94 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 95 | // Assert 96 | Mockito.verify(ledger, Mockito.never()).put(ASSET_ID_EX, assetStatusJsonBuilder.build()); 97 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 98 | Assert.assertNotNull(response.getString(MESSAGE)); 99 | } 100 | 101 | @Test 102 | public void invoke_BorrowAlreadyBorrowedAsset_ShouldReturnFailure() { 103 | // Arrange 104 | setNewStatusAndCurrentStatus(StatusChangeContract.ON_LOAN, StatusChangeContract.ON_LOAN); 105 | Mockito.when(asset.data()).thenReturn(assetStatusJsonBuilder.build()); 106 | Mockito.when(ledger.get(ASSET_ID_EX)).thenReturn(Optional.of(asset)); 107 | JsonObject property = 108 | propertyBuilder.add(StatusChangeContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 109 | // Act 110 | JsonObject response = contract.invoke(ledger, argumentBuilder.build(), Optional.of(property)); 111 | // Assert 112 | Mockito.verify(ledger, Mockito.never()).put(ASSET_ID_EX, assetStatusJsonBuilder.build()); 113 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 114 | Assert.assertNotNull(response.getString(MESSAGE)); 115 | } 116 | 117 | @Test 118 | public void invoke_ReturnAlreadyInStockAsset_ShouldReturnFailure() { 119 | // Arrange 120 | setNewStatusAndCurrentStatus(StatusChangeContract.IN_STOCK, StatusChangeContract.IN_STOCK); 121 | Mockito.when(asset.data()).thenReturn(assetStatusJsonBuilder.build()); 122 | Mockito.when(ledger.get(ASSET_ID_EX)).thenReturn(Optional.of(asset)); 123 | JsonObject property = 124 | propertyBuilder.add(StatusChangeContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 125 | // Act 126 | JsonObject response = contract.invoke(ledger, argumentBuilder.build(), Optional.of(property)); 127 | // Assert 128 | Mockito.verify(ledger, Mockito.never()).put(ASSET_ID_EX, assetStatusJsonBuilder.build()); 129 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 130 | Assert.assertNotNull(response.getString(MESSAGE)); 131 | } 132 | 133 | @Test 134 | public void invoke_BorrowedAssetanOtherUser_ShouldReturnFailure() { 135 | // Arrange 136 | setNewStatusAndCurrentStatus(StatusChangeContract.IN_STOCK, StatusChangeContract.ON_LOAN); 137 | setHasContractHolderIdAndHasAssetHolderId(HOLDER_ID_1_EX, HOLDER_ID_2_EX); 138 | Mockito.when(asset.data()).thenReturn(assetStatusJsonBuilder.build()); 139 | Mockito.when(ledger.get(ASSET_ID_EX)).thenReturn(Optional.of(asset)); 140 | // Act 141 | JsonObject response = 142 | contract.invoke(ledger, argumentBuilder.build(), Optional.of(propertyBuilder.build())); 143 | // Assert 144 | Mockito.verify(ledger, Mockito.never()).put(ASSET_ID_EX, assetStatusJsonBuilder.build()); 145 | Assert.assertEquals(FAILURE, response.getString(RESULT)); 146 | Assert.assertNotNull(response.getString(MESSAGE)); 147 | } 148 | 149 | @Test 150 | public void invoke_ReturnOnLoanAsset_ShouldRunProperly() { 151 | // Arrange 152 | JsonObject currentStatus = 153 | Json.createObjectBuilder() 154 | .add(StatusChangeContract.STATUS, StatusChangeContract.ON_LOAN) 155 | .add(StatusChangeContract.HOLDER_ID, HOLDER_ID_1_EX) 156 | .add(StatusChangeContract.TIMESTAMP, new Date().getTime()) 157 | .build(); 158 | Mockito.when(asset.data()).thenReturn(currentStatus); 159 | Mockito.when(ledger.get(HOLDER_ID_1_EX + "-" + ASSET_ID_EX)).thenReturn(Optional.of(asset)); 160 | long timestamp = new Date().getTime(); 161 | JsonObject argument = 162 | Json.createObjectBuilder() 163 | .add(StatusChangeContract.TIMESTAMP, timestamp) 164 | .add(StatusChangeContract.STATUS, StatusChangeContract.IN_STOCK) 165 | .add(StatusChangeContract.ASSET_ID, ASSET_ID_EX) 166 | .build(); 167 | JsonObject property = 168 | Json.createObjectBuilder().add(StatusChangeContract.HOLDER_ID, HOLDER_ID_1_EX).build(); 169 | // Act 170 | JsonObject response = contract.invoke(ledger, argument, Optional.of(property)); 171 | // Assert 172 | JsonObject assertObject = 173 | Json.createObjectBuilder() 174 | .add(StatusChangeContract.TIMESTAMP, timestamp) 175 | .add(StatusChangeContract.STATUS, StatusChangeContract.IN_STOCK) 176 | .build(); 177 | Mockito.verify(ledger, Mockito.times(1)).put(HOLDER_ID_1_EX + "-" + ASSET_ID_EX, assertObject); 178 | Assert.assertEquals(SUCCESS, response.getString(RESULT)); 179 | Assert.assertNotNull(response.getString(MESSAGE)); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Write your first Scalar DLT application 2 | 3 | - [Write your first Scalar DLT application](#write-your-first-scalar-dlt-application) 4 | - [Overview](#overview) 5 | - [Asset management application](#asset-management-application) 6 | - [Use Scalar DL Client SDK](#use-scalar-dl-client-sdk) 7 | - [Implement contracts](#implement-contracts) 8 | - [Read data from the ledger](#read-data-from-the-ledger) 9 | - [Write data to the ledger](#write-data-to-the-ledger) 10 | - [Look up data history](#look-up-data-history) 11 | - [Test your contract implementation](#test-your-contract-implementation) 12 | - [Unit Test](#unit-test) 13 | - [Mock the ledger object](#mock-the-ledger-object) 14 | - [Assert the result of execution](#assert-the-result-of-execution) 15 | - [Use Scalar DL Emulator](#Use-Scalar-DL-Emulator) 16 | - [Develop client (application)](#Develop-client-application) 17 | - [Register certificate](#register-certificate) 18 | - [Register a contract](#register-a-contract) 19 | - [Execute a contract](#Execute-a-contract) 20 | - [Validate ledger data integrity](#Validate-ledger-data-integrity) 21 | 22 | In this tutorial we introduce how to implement a simple asset management application on Scalar DLT solution. 23 | If you haven't tried this application yet, please refer to [here](./manual/README.md). 24 | 25 | ## Overview 26 | 27 | Scalar DLT is a distributed ledger platform. 28 | A Scalar DL network exposes a key-value semantics called ledger to clients. 29 | Clients can register digitally-signed programs called contracts, which can create, read and update records in a ledger, and later on send requests to the network to execute registered contracts. 30 | 31 | The authentication, confidentiality and integrity is based on PKI. 32 | Ledger data stored in the network is tamper-evident based on digital signature and determinism, so even network administrators can not tamper the data nor create the client's asset by spoofing. 33 | 34 | ### Asset management application 35 | 36 | We implement the asset management application to explain how to develop Scalar DLT contracts and applications. 37 | The simple asset management application is a command-line interface (CLI) application used to create and list asset types, create and list assets, borrow or return asset, and display borrowing history of asset. 38 | It supports the following commands. 39 | 40 | |command|description| 41 | |-------|-----------| 42 | |init |Initialize asset management application| 43 | |add-type |Create an asset type| 44 | |list-type|List all created types| 45 | |add |Add an asset of specified type| 46 | |list |List all added assets of specified type| 47 | |borrow |Borrow an asset| 48 | |return |Return an asset| 49 | |asset-history |List the borrowing history of an asset| 50 | |validate |Validate if an asset data has not been tampered| 51 | 52 | We create contracts corresponding to commands to manipulate the ledger. 53 | 54 | |contract| 55 | |---------| 56 | |AddAssetContract| 57 | |AddTypeContract| 58 | |ListContract| 59 | |ListTypeContract| 60 | |StateChangeContract| 61 | |AssetHistoryContract| 62 | 63 | This architecture figure shows the communication between the application (client-side) and the Scalar DL network. 64 | ![structure](./tutorial/img/structure.jpg) 65 | 66 | ## Use Scalar DL Client SDK 67 | [Scalar DL Client SDK](https://github.com/scalar-labs/scalardl-client-sdk) supports Java. 68 | It has two main parts `contract` and `client`. 69 | We can create contracts to `create`, `read`, or `update` assets in the ledger, and also to get the modification history for a particular asset. 70 | In order to execute a contract it has to be registered on the Scalar DL network. 71 | 72 | ### Implement contracts 73 | 74 | Contracts are executed on Scalar DL networks. They are able to read and write data into the ledger of the Scalar DL network. 75 | A contract needs to be a public Java class which extends the `com.scalar.dl.ledger.contract.Contract` class of the Ledger library. 76 | Contract implementation guidelines : 77 | - A single contract code should not involve overly complicated business logic. If you have a complicated business logic, disassemble the logic and use nested invocation 78 | - Use of external Java libraries except the DLT libraries is not allowed 79 | - Inner classes are allowed 80 | - Nesting contract invocation is possible 81 | - The `invoke()` method must be a deterministic function 82 | 83 | A contract's implementation may look like 84 | ``` 85 | import com.scalar.dl.ledger.contract.Contract; 86 | import com.scalar.dl.ledger.database.Ledger; 87 | import java.util.Optional; 88 | import javax.json.Json; 89 | import javax.json.JsonObject; 90 | 91 | public class MyContract extends Contract { 92 | @Override 93 | public JsonObject invoke(Ledger ledger, JsonObject argument, Optional property) { 94 | // read or write data and respond to clients here 95 | } 96 | } 97 | ``` 98 | The `invoke()` method defines the entry point of the contract. 99 | 100 | The `ledger` parameter provides a key-value-like interface to the backend ledger database. 101 | It provides methods to insert, update, read and retrieve the modification history of a given key. 102 | 103 | The `argument` parameter is the parameter passed to the contract in JSON format. 104 | The JSON object should have a property called `nonce` of type `String`. The nonce should be a globally unique number and we recommend using a UUID as a nonce. 105 | 106 | The `property` parameter is an optional JSON object that is set during the contract registration process. 107 | 108 | #### Read data from the ledger 109 | The `Optional get(String key)` method of `ledger` object is used to retrieve the current value of for the given key 110 | 111 | ```java 112 | Optional opt = ledger.get("somekey"); 113 | if (opt.isPresent()) { 114 | Asset asset = opt.get(); 115 | int age = asset.age(); 116 | JsonObject value = asset.data(); 117 | } 118 | ``` 119 | 120 | The **age** refers to the current modification iteration of the key. It starts at 0 when an asset is inserted. 121 | 122 | Check [ListContract](./src/main/java/com/scalar/am/contract/ListContract.java). 123 | We implemented it to get the borrowing status of the specified asset with codes. 124 | 125 | ```java 126 | Optional borrowingStatus = ledger.get(id); 127 | long timestamp = borrowingStatus.get().data().getJsonNumber("timestamp").longValue(); // our value is in format of JSON 128 | String status = borrowingStatus.get().data().getString("status"); 129 | ``` 130 | 131 | #### Write data to the ledger 132 | The `void put(String key, JsonObject value)` method of `ledger` object is used to write a JsonObject as value with the given key. 133 | 134 | **Important** blind write are not permitted, reading the data with get(String key) is necessary previous to insertion. 135 | 136 | ```java 137 | ledger.get("somekey"); // avoid blind write 138 | ledger.put("somekey", Json.createObjectBuilder().build()); 139 | ``` 140 | 141 | Check [AddTypeContract](./src/main/java/com/scalar/am/contract/AddTypeContract.java). 142 | We implemented it to create a new asset category. 143 | 144 | ``` 145 | Optional opt = ledger.get(name); 146 | if (opt.isPresent()) { 147 | return Json.createObjectBuilder() 148 | .add("message", "Type " + name + " is already registered.") 149 | .build(); 150 | } 151 | 152 | ledger.put(name, Json.createObjectBuilder().build()); 153 | ``` 154 | 155 | #### Look up data history 156 | The `List scan(String key)` method of `ledger` object is used to retrieve the modification history for a given key. 157 | 158 | ```java 159 | AssetFilter filter = new AssetFilter(key); 160 | List history = ledger.scan(filter); 161 | for (Asset asset : history) { 162 | String id = asset.id(); 163 | int age = asset.age(); 164 | JsonObject value = asset.data(); 165 | } 166 | ``` 167 | The **AssetFilter** object specify by default that the whole asset history (from oldest to newest) will be returned. If only a subset of the history is needed, it can be parameterized as in the following. 168 | 169 | ```java 170 | //History from age 5 to 9 171 | new AssetFilter(id).withStartVersion(5, true).withEndVersion(10, false); 172 | //History from age 5 to the latest state 173 | new AssetFilter(id).withStartVersion(5, true); 174 | ``` 175 | 176 | Check [ListTypeContract](./src/main/java/com/scalar/am/contract/ListTypeContract.java). 177 | We implemented it to list a registered asset categories. 178 | 179 | ```java 180 | AssetFilter filter = new AssetFilter("type"); 181 | List history = ledger.scan(filter); 182 | if (history.isEmpty()) { 183 | return Json.createObjectBuilder() 184 | .add(MESSAGE, "No types were registered. Use am add-type to create one.") 185 | .build(); 186 | } 187 | 188 | JsonArrayBuilder builder = Json.createArrayBuilder(); 189 | for (Asset h : history) { 190 | JsonObject type = 191 | Json.createObjectBuilder().add("type", h.data().getString("name")).add("age", h.age()).build(); 192 | builder.add(type); 193 | } 194 | JsonArray types = builder.build(); 195 | ``` 196 | 197 | ### Test your contract implementation 198 | 199 | #### Unit Test 200 | Unit testing contract is a good approach to demonstrate how to use the contract and what the contract does. 201 | In this section we will use [junit](https://junit.org/junit4/) and [mockito](https://site.mockito.org/) to introduce a unit test sample. 202 | 203 | ##### Mock the ledger object 204 | 205 | To write unit test for a contract we can use the mockito library to mock a ledger object. 206 | 207 | In the `invoke` method of [ListTypeContract](./src/main/java/com/scalar/am/contract/ListTypeContract.java), 208 | 209 | ```java 210 | AssetFilter filter = new AssetFilter(type); 211 | List history = ledger.scan(filter); 212 | 213 | if (history.isEmpty()) { 214 | return Json.createObjectBuilder.add("result". "failure") 215 | .add("message", "No types were registered. Use am add-type to create one.") 216 | .build(); 217 | ``` 218 | 219 | we can see that first all the versions of asset `type` are retrieved. If the asset `type` does not exist in the ledger, the code wil return an error. 220 | If we want to unit test this behaviour, we can mock the ledger object (by `Mock` annotation) to return an empty list when scan is called (set by `when` and `thenReturn` functions) with any parameters (by `any` function). 221 | 222 | ```java 223 | import org.mockito.Mock; 224 | import org.mockito.Mockito; 225 | 226 | @Mock private Ledger ledger; 227 | Mockito.when(ledger.scan(Mockito.any(AssetFilter.class))).thenReturn(new ArrayList()); 228 | ``` 229 | 230 | ##### Assert the result of execution 231 | 232 | Then we can execute `ListTypeContact.invoke` with the mocked ledger and assert the response to confirm the code certainly goes into the block that we expected. 233 | 234 | ```java 235 | import org.junit.Assert; 236 | 237 | ListTypeContract contract = new ListTypeContract(); 238 | JsonObject argument = Json.createObjectBuilder.add("type", "book").build(); 239 | JsonObject response = contract.invoke(ledger, argument, null); 240 | Assert.assertEquals("failure", response.getString("result"); 241 | Assert.assertNotNull(response.get(MESSAGE)); 242 | ``` 243 | 244 | #### Use Scalar DL Emulator 245 | Scalar also provides a [contract emulator](https://github.com/scalar-labs/scalardl-emulator) that can be used to test our contracts. 246 | 247 | ### Develop client (application) 248 | 249 | ClientService class in Scalar DL client SDK provides interface for these main features: 250 | - register certificate 251 | - register contract 252 | - list registered contracts 253 | - execute contract 254 | 255 | It is an autoclosable class so the code might look like 256 | 257 | ```java 258 | Injector injector = Guice.createInjector(new ClientModule(config)); 259 | try (ClientService clientService = injector.getInstance(ClientService.class)) { 260 | ... 261 | } 262 | ``` 263 | 264 | Notice that we need a ClientConfig to create a ClientService. 265 | ClientConfig can be initiated with Properties of following format: 266 | 267 | ``` 268 | scalar.dl.client.server.host=
269 | scalar.dl.client.server.port= 270 | scalar.dl.client.cert_holder_id= 271 | scalar.dl.client.cert_path= 272 | scalar.dl.client.cert_version= 273 | scalar.dl.client.private_key_path= 274 | scalar.dl.client.tls.enabled= 275 | scalar.dl.client.authorization.credential=Basic: 276 | ``` 277 | 278 | #### Register certificate 279 | 280 | Scalar DLT network verifies the signatures attached in `Contract registration` and `Contract execution` requests with X.509 certificate to authenticate users. 281 | We can use `registerCertificate()` method of ClientService to register a certificate specified in the config. 282 | 283 | 284 | ```java 285 | clientService.registerCertificate(); 286 | ``` 287 | 288 | Check [Init](./src/main/java/com/scalar/am/command/Init.java). 289 | We registered certificate when user execute `init` command, and check the response from Scalar DL network. 290 | 291 | ```java 292 | try { 293 | clientService.registerCertificate(); 294 | } catch (Exception ex) { 295 | throw new Exception("Error during certificate registration"); 296 | } 297 | ``` 298 | 299 | User is identified by `Holder ID`. 300 | You can specify different versions to register multiple certificates for the same holder id. 301 | After a certificate is registered, the private key will be used to sign `Contract registration` and `Contract execution` requests. 302 | 303 | 304 | #### Register a contract 305 | We can use `registerContract(String id, String name, String path, Optional properties)` method of ClientService to register a contract class file. 306 | 307 | **Remark:** As the private key of the user is passed to sign the contract, only the user who registered the contract, or another user holding the same key, will have access to that contract. 308 | 309 | Ceeck [Init](./src/main/java/com/scalar/am/command/Init.java). 310 | We register all asset management contracts when user execute `init` command. 311 | 312 | ```java 313 | for (Path contract : contractList) { 314 | String className = com.google.common.io.Files.getNameWithoutExtension(contract.getFileName().toString()); 315 | String contractPath = contract.toString(); 316 | String contractId = config.getContractId(className); 317 | String canonicalName = contractId.substring(0, contractId.indexOf("_")); 318 | JsonObject property = null; 319 | 320 | try { 321 | service.registerContract(contractId, canonicalName, contractPath, Optional.ofNullable(property)); 322 | } catch (Exception ex) { 323 | System.err.println("Error during contract registration"); 324 | throw new Exception("Failed to register contract"); 325 | } 326 | } 327 | ``` 328 | 329 | #### Execute a contract 330 | We can use `ContractExecutionResult executeContract(String id, JsonObject argument)` method of ClientService to execute registered contracts. 331 | Check [LedgerClientExecutor](./src/main/java/com/scalar/am/command/LedgerClientExecutor.java). 332 | It is a generic function for command runners. It loads the response's JSON to JsonObject. 333 | 334 | ```java 335 | try { 336 | ContractExecutionResult result = clientService.executeContract(contractId, object); 337 | if (response.getResult().isPresent()) { 338 | JsonObject result = result.getResult().get(); 339 | } 340 | } catch (Exception ex) { 341 | System.err.println("Error during contract execution"); 342 | return; 343 | } 344 | ``` 345 | 346 | #### Validate ledger data integrity 347 | 348 | We can use `LedgerValidationResult validateLedger(String assetId)` to validate if the asset data stored on the ledger has not been tempered. 349 | It is to be noted that any registered user can validate any asset of the ledger. 350 | Check [ValidateAsset](./src/main/java/com/scalar/am/command/ValidateAsset.java). 351 | 352 | ```java 353 | LedgerValidationResult result = clientService.validateLedger(id); 354 | if (!(result.getCode().equals(StatusCode.OK))) { 355 | System.err.println("Error during asset validate"); 356 | System.err.println("Status code: " + result.getCode().get()); 357 | return; 358 | } 359 | System.out.println("Asset " + id + " is untampered"); 360 | ``` 361 | 362 | 363 | Another example of contract implementation can be found in [com.scalar.contract](https://github.com/scalar-labs/indetail/tree/master/AM_application/src/main/java/com/scalar/am/contract) package. 364 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This software is dual-licensed under both the AGPL and a commercial license. 2 | You can be released from the requirements of the following AGPL license by 3 | purchasing a commercial license. For more information, please contact Scalar, Inc. 4 | 5 | 6 | GNU AFFERO GENERAL PUBLIC LICENSE 7 | Version 3, 19 November 2007 8 | 9 | Copyright (C) 2007 Free Software Foundation, Inc. 10 | Everyone is permitted to copy and distribute verbatim copies 11 | of this license document, but changing it is not allowed. 12 | 13 | Preamble 14 | 15 | The GNU Affero General Public License is a free, copyleft license for 16 | software and other kinds of works, specifically designed to ensure 17 | cooperation with the community in the case of network server software. 18 | 19 | The licenses for most software and other practical works are designed 20 | to take away your freedom to share and change the works. By contrast, 21 | our General Public Licenses are intended to guarantee your freedom to 22 | share and change all versions of a program--to make sure it remains free 23 | software for all its users. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | Developers that use our General Public Licenses protect your rights 33 | with two steps: (1) assert copyright on the software, and (2) offer 34 | you this License which gives you legal permission to copy, distribute 35 | and/or modify the software. 36 | 37 | A secondary benefit of defending all users' freedom is that 38 | improvements made in alternate versions of the program, if they 39 | receive widespread use, become available for other developers to 40 | incorporate. Many developers of free software are heartened and 41 | encouraged by the resulting cooperation. However, in the case of 42 | software used on network servers, this result may fail to come about. 43 | The GNU General Public License permits making a modified version and 44 | letting the public access it on a server without ever releasing its 45 | source code to the public. 46 | 47 | The GNU Affero General Public License is designed specifically to 48 | ensure that, in such cases, the modified source code becomes available 49 | to the community. It requires the operator of a network server to 50 | provide the source code of the modified version running there to the 51 | users of that server. Therefore, public use of a modified version, on 52 | a publicly accessible server, gives the public access to the source 53 | code of the modified version. 54 | 55 | An older license, called the Affero General Public License and 56 | published by Affero, was designed to accomplish similar goals. This is 57 | a different license, not a version of the Affero GPL, but Affero has 58 | released a new version of the Affero GPL which permits relicensing under 59 | this license. 60 | 61 | The precise terms and conditions for copying, distribution and 62 | modification follow. 63 | 64 | TERMS AND CONDITIONS 65 | 66 | 0. Definitions. 67 | 68 | "This License" refers to version 3 of the GNU Affero General Public License. 69 | 70 | "Copyright" also means copyright-like laws that apply to other kinds of 71 | works, such as semiconductor masks. 72 | 73 | "The Program" refers to any copyrightable work licensed under this 74 | License. Each licensee is addressed as "you". "Licensees" and 75 | "recipients" may be individuals or organizations. 76 | 77 | To "modify" a work means to copy from or adapt all or part of the work 78 | in a fashion requiring copyright permission, other than the making of an 79 | exact copy. The resulting work is called a "modified version" of the 80 | earlier work or a work "based on" the earlier work. 81 | 82 | A "covered work" means either the unmodified Program or a work based 83 | on the Program. 84 | 85 | To "propagate" a work means to do anything with it that, without 86 | permission, would make you directly or secondarily liable for 87 | infringement under applicable copyright law, except executing it on a 88 | computer or modifying a private copy. Propagation includes copying, 89 | distribution (with or without modification), making available to the 90 | public, and in some countries other activities as well. 91 | 92 | To "convey" a work means any kind of propagation that enables other 93 | parties to make or receive copies. Mere interaction with a user through 94 | a computer network, with no transfer of a copy, is not conveying. 95 | 96 | An interactive user interface displays "Appropriate Legal Notices" 97 | to the extent that it includes a convenient and prominently visible 98 | feature that (1) displays an appropriate copyright notice, and (2) 99 | tells the user that there is no warranty for the work (except to the 100 | extent that warranties are provided), that licensees may convey the 101 | work under this License, and how to view a copy of this License. If 102 | the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | 1. Source Code. 106 | 107 | The "source code" for a work means the preferred form of the work 108 | for making modifications to it. "Object code" means any non-source 109 | form of a work. 110 | 111 | A "Standard Interface" means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of 113 | interfaces specified for a particular programming language, one that 114 | is widely used among developers working in that language. 115 | 116 | The "System Libraries" of an executable work include anything, other 117 | than the work as a whole, that (a) is included in the normal form of 118 | packaging a Major Component, but which is not part of that Major 119 | Component, and (b) serves only to enable use of the work with that 120 | Major Component, or to implement a Standard Interface for which an 121 | implementation is available to the public in source code form. A 122 | "Major Component", in this context, means a major essential component 123 | (kernel, window system, and so on) of the specific operating system 124 | (if any) on which the executable work runs, or a compiler used to 125 | produce the work, or an object code interpreter used to run it. 126 | 127 | The "Corresponding Source" for a work in object code form means all 128 | the source code needed to generate, install, and (for an executable 129 | work) run the object code and to modify the work, including scripts to 130 | control those activities. However, it does not include the work's 131 | System Libraries, or general-purpose tools or generally available free 132 | programs which are used unmodified in performing those activities but 133 | which are not part of the work. For example, Corresponding Source 134 | includes interface definition files associated with source files for 135 | the work, and the source code for shared libraries and dynamically 136 | linked subprograms that the work is specifically designed to require, 137 | such as by intimate data communication or control flow between those 138 | subprograms and other parts of the work. 139 | 140 | The Corresponding Source need not include anything that users 141 | can regenerate automatically from other parts of the Corresponding 142 | Source. 143 | 144 | The Corresponding Source for a work in source code form is that 145 | same work. 146 | 147 | 2. Basic Permissions. 148 | 149 | All rights granted under this License are granted for the term of 150 | copyright on the Program, and are irrevocable provided the stated 151 | conditions are met. This License explicitly affirms your unlimited 152 | permission to run the unmodified Program. The output from running a 153 | covered work is covered by this License only if the output, given its 154 | content, constitutes a covered work. This License acknowledges your 155 | rights of fair use or other equivalent, as provided by copyright law. 156 | 157 | You may make, run and propagate covered works that you do not 158 | convey, without conditions so long as your license otherwise remains 159 | in force. You may convey covered works to others for the sole purpose 160 | of having them make modifications exclusively for you, or provide you 161 | with facilities for running those works, provided that you comply with 162 | the terms of this License in conveying all material for which you do 163 | not control copyright. Those thus making or running the covered works 164 | for you must do so exclusively on your behalf, under your direction 165 | and control, on terms that prohibit them from making any copies of 166 | your copyrighted material outside their relationship with you. 167 | 168 | Conveying under any other circumstances is permitted solely under 169 | the conditions stated below. Sublicensing is not allowed; section 10 170 | makes it unnecessary. 171 | 172 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 173 | 174 | No covered work shall be deemed part of an effective technological 175 | measure under any applicable law fulfilling obligations under article 176 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 177 | similar laws prohibiting or restricting circumvention of such 178 | measures. 179 | 180 | When you convey a covered work, you waive any legal power to forbid 181 | circumvention of technological measures to the extent such circumvention 182 | is effected by exercising rights under this License with respect to 183 | the covered work, and you disclaim any intention to limit operation or 184 | modification of the work as a means of enforcing, against the work's 185 | users, your or third parties' legal rights to forbid circumvention of 186 | technological measures. 187 | 188 | 4. Conveying Verbatim Copies. 189 | 190 | You may convey verbatim copies of the Program's source code as you 191 | receive it, in any medium, provided that you conspicuously and 192 | appropriately publish on each copy an appropriate copyright notice; 193 | keep intact all notices stating that this License and any 194 | non-permissive terms added in accord with section 7 apply to the code; 195 | keep intact all notices of the absence of any warranty; and give all 196 | recipients a copy of this License along with the Program. 197 | 198 | You may charge any price or no price for each copy that you convey, 199 | and you may offer support or warranty protection for a fee. 200 | 201 | 5. Conveying Modified Source Versions. 202 | 203 | You may convey a work based on the Program, or the modifications to 204 | produce it from the Program, in the form of source code under the 205 | terms of section 4, provided that you also meet all of these conditions: 206 | 207 | a) The work must carry prominent notices stating that you modified 208 | it, and giving a relevant date. 209 | 210 | b) The work must carry prominent notices stating that it is 211 | released under this License and any conditions added under section 212 | 7. This requirement modifies the requirement in section 4 to 213 | "keep intact all notices". 214 | 215 | c) You must license the entire work, as a whole, under this 216 | License to anyone who comes into possession of a copy. This 217 | License will therefore apply, along with any applicable section 7 218 | additional terms, to the whole of the work, and all its parts, 219 | regardless of how they are packaged. This License gives no 220 | permission to license the work in any other way, but it does not 221 | invalidate such permission if you have separately received it. 222 | 223 | d) If the work has interactive user interfaces, each must display 224 | Appropriate Legal Notices; however, if the Program has interactive 225 | interfaces that do not display Appropriate Legal Notices, your 226 | work need not make them do so. 227 | 228 | A compilation of a covered work with other separate and independent 229 | works, which are not by their nature extensions of the covered work, 230 | and which are not combined with it such as to form a larger program, 231 | in or on a volume of a storage or distribution medium, is called an 232 | "aggregate" if the compilation and its resulting copyright are not 233 | used to limit the access or legal rights of the compilation's users 234 | beyond what the individual works permit. Inclusion of a covered work 235 | in an aggregate does not cause this License to apply to the other 236 | parts of the aggregate. 237 | 238 | 6. Conveying Non-Source Forms. 239 | 240 | You may convey a covered work in object code form under the terms 241 | of sections 4 and 5, provided that you also convey the 242 | machine-readable Corresponding Source under the terms of this License, 243 | in one of these ways: 244 | 245 | a) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by the 247 | Corresponding Source fixed on a durable physical medium 248 | customarily used for software interchange. 249 | 250 | b) Convey the object code in, or embodied in, a physical product 251 | (including a physical distribution medium), accompanied by a 252 | written offer, valid for at least three years and valid for as 253 | long as you offer spare parts or customer support for that product 254 | model, to give anyone who possesses the object code either (1) a 255 | copy of the Corresponding Source for all the software in the 256 | product that is covered by this License, on a durable physical 257 | medium customarily used for software interchange, for a price no 258 | more than your reasonable cost of physically performing this 259 | conveying of source, or (2) access to copy the 260 | Corresponding Source from a network server at no charge. 261 | 262 | c) Convey individual copies of the object code with a copy of the 263 | written offer to provide the Corresponding Source. This 264 | alternative is allowed only occasionally and noncommercially, and 265 | only if you received the object code with such an offer, in accord 266 | with subsection 6b. 267 | 268 | d) Convey the object code by offering access from a designated 269 | place (gratis or for a charge), and offer equivalent access to the 270 | Corresponding Source in the same way through the same place at no 271 | further charge. You need not require recipients to copy the 272 | Corresponding Source along with the object code. If the place to 273 | copy the object code is a network server, the Corresponding Source 274 | may be on a different server (operated by you or a third party) 275 | that supports equivalent copying facilities, provided you maintain 276 | clear directions next to the object code saying where to find the 277 | Corresponding Source. Regardless of what server hosts the 278 | Corresponding Source, you remain obligated to ensure that it is 279 | available for as long as needed to satisfy these requirements. 280 | 281 | e) Convey the object code using peer-to-peer transmission, provided 282 | you inform other peers where the object code and Corresponding 283 | Source of the work are being offered to the general public at no 284 | charge under subsection 6d. 285 | 286 | A separable portion of the object code, whose source code is excluded 287 | from the Corresponding Source as a System Library, need not be 288 | included in conveying the object code work. 289 | 290 | A "User Product" is either (1) a "consumer product", which means any 291 | tangible personal property which is normally used for personal, family, 292 | or household purposes, or (2) anything designed or sold for incorporation 293 | into a dwelling. In determining whether a product is a consumer product, 294 | doubtful cases shall be resolved in favor of coverage. For a particular 295 | product received by a particular user, "normally used" refers to a 296 | typical or common use of that class of product, regardless of the status 297 | of the particular user or of the way in which the particular user 298 | actually uses, or expects or is expected to use, the product. A product 299 | is a consumer product regardless of whether the product has substantial 300 | commercial, industrial or non-consumer uses, unless such uses represent 301 | the only significant mode of use of the product. 302 | 303 | "Installation Information" for a User Product means any methods, 304 | procedures, authorization keys, or other information required to install 305 | and execute modified versions of a covered work in that User Product from 306 | a modified version of its Corresponding Source. The information must 307 | suffice to ensure that the continued functioning of the modified object 308 | code is in no case prevented or interfered with solely because 309 | modification has been made. 310 | 311 | If you convey an object code work under this section in, or with, or 312 | specifically for use in, a User Product, and the conveying occurs as 313 | part of a transaction in which the right of possession and use of the 314 | User Product is transferred to the recipient in perpetuity or for a 315 | fixed term (regardless of how the transaction is characterized), the 316 | Corresponding Source conveyed under this section must be accompanied 317 | by the Installation Information. But this requirement does not apply 318 | if neither you nor any third party retains the ability to install 319 | modified object code on the User Product (for example, the work has 320 | been installed in ROM). 321 | 322 | The requirement to provide Installation Information does not include a 323 | requirement to continue to provide support service, warranty, or updates 324 | for a work that has been modified or installed by the recipient, or for 325 | the User Product in which it has been modified or installed. Access to a 326 | network may be denied when the modification itself materially and 327 | adversely affects the operation of the network or violates the rules and 328 | protocols for communication across the network. 329 | 330 | Corresponding Source conveyed, and Installation Information provided, 331 | in accord with this section must be in a format that is publicly 332 | documented (and with an implementation available to the public in 333 | source code form), and must require no special password or key for 334 | unpacking, reading or copying. 335 | 336 | 7. Additional Terms. 337 | 338 | "Additional permissions" are terms that supplement the terms of this 339 | License by making exceptions from one or more of its conditions. 340 | Additional permissions that are applicable to the entire Program shall 341 | be treated as though they were included in this License, to the extent 342 | that they are valid under applicable law. If additional permissions 343 | apply only to part of the Program, that part may be used separately 344 | under those permissions, but the entire Program remains governed by 345 | this License without regard to the additional permissions. 346 | 347 | When you convey a copy of a covered work, you may at your option 348 | remove any additional permissions from that copy, or from any part of 349 | it. (Additional permissions may be written to require their own 350 | removal in certain cases when you modify the work.) You may place 351 | additional permissions on material, added by you to a covered work, 352 | for which you have or can give appropriate copyright permission. 353 | 354 | Notwithstanding any other provision of this License, for material you 355 | add to a covered work, you may (if authorized by the copyright holders of 356 | that material) supplement the terms of this License with terms: 357 | 358 | a) Disclaiming warranty or limiting liability differently from the 359 | terms of sections 15 and 16 of this License; or 360 | 361 | b) Requiring preservation of specified reasonable legal notices or 362 | author attributions in that material or in the Appropriate Legal 363 | Notices displayed by works containing it; or 364 | 365 | c) Prohibiting misrepresentation of the origin of that material, or 366 | requiring that modified versions of such material be marked in 367 | reasonable ways as different from the original version; or 368 | 369 | d) Limiting the use for publicity purposes of names of licensors or 370 | authors of the material; or 371 | 372 | e) Declining to grant rights under trademark law for use of some 373 | trade names, trademarks, or service marks; or 374 | 375 | f) Requiring indemnification of licensors and authors of that 376 | material by anyone who conveys the material (or modified versions of 377 | it) with contractual assumptions of liability to the recipient, for 378 | any liability that these contractual assumptions directly impose on 379 | those licensors and authors. 380 | 381 | All other non-permissive additional terms are considered "further 382 | restrictions" within the meaning of section 10. If the Program as you 383 | received it, or any part of it, contains a notice stating that it is 384 | governed by this License along with a term that is a further 385 | restriction, you may remove that term. If a license document contains 386 | a further restriction but permits relicensing or conveying under this 387 | License, you may add to a covered work material governed by the terms 388 | of that license document, provided that the further restriction does 389 | not survive such relicensing or conveying. 390 | 391 | If you add terms to a covered work in accord with this section, you 392 | must place, in the relevant source files, a statement of the 393 | additional terms that apply to those files, or a notice indicating 394 | where to find the applicable terms. 395 | 396 | Additional terms, permissive or non-permissive, may be stated in the 397 | form of a separately written license, or stated as exceptions; 398 | the above requirements apply either way. 399 | 400 | 8. Termination. 401 | 402 | You may not propagate or modify a covered work except as expressly 403 | provided under this License. Any attempt otherwise to propagate or 404 | modify it is void, and will automatically terminate your rights under 405 | this License (including any patent licenses granted under the third 406 | paragraph of section 11). 407 | 408 | However, if you cease all violation of this License, then your 409 | license from a particular copyright holder is reinstated (a) 410 | provisionally, unless and until the copyright holder explicitly and 411 | finally terminates your license, and (b) permanently, if the copyright 412 | holder fails to notify you of the violation by some reasonable means 413 | prior to 60 days after the cessation. 414 | 415 | Moreover, your license from a particular copyright holder is 416 | reinstated permanently if the copyright holder notifies you of the 417 | violation by some reasonable means, this is the first time you have 418 | received notice of violation of this License (for any work) from that 419 | copyright holder, and you cure the violation prior to 30 days after 420 | your receipt of the notice. 421 | 422 | Termination of your rights under this section does not terminate the 423 | licenses of parties who have received copies or rights from you under 424 | this License. If your rights have been terminated and not permanently 425 | reinstated, you do not qualify to receive new licenses for the same 426 | material under section 10. 427 | 428 | 9. Acceptance Not Required for Having Copies. 429 | 430 | You are not required to accept this License in order to receive or 431 | run a copy of the Program. Ancillary propagation of a covered work 432 | occurring solely as a consequence of using peer-to-peer transmission 433 | to receive a copy likewise does not require acceptance. However, 434 | nothing other than this License grants you permission to propagate or 435 | modify any covered work. These actions infringe copyright if you do 436 | not accept this License. Therefore, by modifying or propagating a 437 | covered work, you indicate your acceptance of this License to do so. 438 | 439 | 10. Automatic Licensing of Downstream Recipients. 440 | 441 | Each time you convey a covered work, the recipient automatically 442 | receives a license from the original licensors, to run, modify and 443 | propagate that work, subject to this License. You are not responsible 444 | for enforcing compliance by third parties with this License. 445 | 446 | An "entity transaction" is a transaction transferring control of an 447 | organization, or substantially all assets of one, or subdividing an 448 | organization, or merging organizations. If propagation of a covered 449 | work results from an entity transaction, each party to that 450 | transaction who receives a copy of the work also receives whatever 451 | licenses to the work the party's predecessor in interest had or could 452 | give under the previous paragraph, plus a right to possession of the 453 | Corresponding Source of the work from the predecessor in interest, if 454 | the predecessor has it or can get it with reasonable efforts. 455 | 456 | You may not impose any further restrictions on the exercise of the 457 | rights granted or affirmed under this License. For example, you may 458 | not impose a license fee, royalty, or other charge for exercise of 459 | rights granted under this License, and you may not initiate litigation 460 | (including a cross-claim or counterclaim in a lawsuit) alleging that 461 | any patent claim is infringed by making, using, selling, offering for 462 | sale, or importing the Program or any portion of it. 463 | 464 | 11. Patents. 465 | 466 | A "contributor" is a copyright holder who authorizes use under this 467 | License of the Program or a work on which the Program is based. The 468 | work thus licensed is called the contributor's "contributor version". 469 | 470 | A contributor's "essential patent claims" are all patent claims 471 | owned or controlled by the contributor, whether already acquired or 472 | hereafter acquired, that would be infringed by some manner, permitted 473 | by this License, of making, using, or selling its contributor version, 474 | but do not include claims that would be infringed only as a 475 | consequence of further modification of the contributor version. For 476 | purposes of this definition, "control" includes the right to grant 477 | patent sublicenses in a manner consistent with the requirements of 478 | this License. 479 | 480 | Each contributor grants you a non-exclusive, worldwide, royalty-free 481 | patent license under the contributor's essential patent claims, to 482 | make, use, sell, offer for sale, import and otherwise run, modify and 483 | propagate the contents of its contributor version. 484 | 485 | In the following three paragraphs, a "patent license" is any express 486 | agreement or commitment, however denominated, not to enforce a patent 487 | (such as an express permission to practice a patent or covenant not to 488 | sue for patent infringement). To "grant" such a patent license to a 489 | party means to make such an agreement or commitment not to enforce a 490 | patent against the party. 491 | 492 | If you convey a covered work, knowingly relying on a patent license, 493 | and the Corresponding Source of the work is not available for anyone 494 | to copy, free of charge and under the terms of this License, through a 495 | publicly available network server or other readily accessible means, 496 | then you must either (1) cause the Corresponding Source to be so 497 | available, or (2) arrange to deprive yourself of the benefit of the 498 | patent license for this particular work, or (3) arrange, in a manner 499 | consistent with the requirements of this License, to extend the patent 500 | license to downstream recipients. "Knowingly relying" means you have 501 | actual knowledge that, but for the patent license, your conveying the 502 | covered work in a country, or your recipient's use of the covered work 503 | in a country, would infringe one or more identifiable patents in that 504 | country that you have reason to believe are valid. 505 | 506 | If, pursuant to or in connection with a single transaction or 507 | arrangement, you convey, or propagate by procuring conveyance of, a 508 | covered work, and grant a patent license to some of the parties 509 | receiving the covered work authorizing them to use, propagate, modify 510 | or convey a specific copy of the covered work, then the patent license 511 | you grant is automatically extended to all recipients of the covered 512 | work and works based on it. 513 | 514 | A patent license is "discriminatory" if it does not include within 515 | the scope of its coverage, prohibits the exercise of, or is 516 | conditioned on the non-exercise of one or more of the rights that are 517 | specifically granted under this License. You may not convey a covered 518 | work if you are a party to an arrangement with a third party that is 519 | in the business of distributing software, under which you make payment 520 | to the third party based on the extent of your activity of conveying 521 | the work, and under which the third party grants, to any of the 522 | parties who would receive the covered work from you, a discriminatory 523 | patent license (a) in connection with copies of the covered work 524 | conveyed by you (or copies made from those copies), or (b) primarily 525 | for and in connection with specific products or compilations that 526 | contain the covered work, unless you entered into that arrangement, 527 | or that patent license was granted, prior to 28 March 2007. 528 | 529 | Nothing in this License shall be construed as excluding or limiting 530 | any implied license or other defenses to infringement that may 531 | otherwise be available to you under applicable patent law. 532 | 533 | 12. No Surrender of Others' Freedom. 534 | 535 | If conditions are imposed on you (whether by court order, agreement or 536 | otherwise) that contradict the conditions of this License, they do not 537 | excuse you from the conditions of this License. If you cannot convey a 538 | covered work so as to satisfy simultaneously your obligations under this 539 | License and any other pertinent obligations, then as a consequence you may 540 | not convey it at all. For example, if you agree to terms that obligate you 541 | to collect a royalty for further conveying from those to whom you convey 542 | the Program, the only way you could satisfy both those terms and this 543 | License would be to refrain entirely from conveying the Program. 544 | 545 | 13. Remote Network Interaction; Use with the GNU General Public License. 546 | 547 | Notwithstanding any other provision of this License, if you modify the 548 | Program, your modified version must prominently offer all users 549 | interacting with it remotely through a computer network (if your version 550 | supports such interaction) an opportunity to receive the Corresponding 551 | Source of your version by providing access to the Corresponding Source 552 | from a network server at no charge, through some standard or customary 553 | means of facilitating copying of software. This Corresponding Source 554 | shall include the Corresponding Source for any work covered by version 3 555 | of the GNU General Public License that is incorporated pursuant to the 556 | following paragraph. 557 | 558 | Notwithstanding any other provision of this License, you have 559 | permission to link or combine any covered work with a work licensed 560 | under version 3 of the GNU General Public License into a single 561 | combined work, and to convey the resulting work. The terms of this 562 | License will continue to apply to the part which is the covered work, 563 | but the work with which it is combined will remain governed by version 564 | 3 of the GNU General Public License. 565 | 566 | 14. Revised Versions of this License. 567 | 568 | The Free Software Foundation may publish revised and/or new versions of 569 | the GNU Affero General Public License from time to time. Such new versions 570 | will be similar in spirit to the present version, but may differ in detail to 571 | address new problems or concerns. 572 | 573 | Each version is given a distinguishing version number. If the 574 | Program specifies that a certain numbered version of the GNU Affero General 575 | Public License "or any later version" applies to it, you have the 576 | option of following the terms and conditions either of that numbered 577 | version or of any later version published by the Free Software 578 | Foundation. If the Program does not specify a version number of the 579 | GNU Affero General Public License, you may choose any version ever published 580 | by the Free Software Foundation. 581 | 582 | If the Program specifies that a proxy can decide which future 583 | versions of the GNU Affero General Public License can be used, that proxy's 584 | public statement of acceptance of a version permanently authorizes you 585 | to choose that version for the Program. 586 | 587 | Later license versions may give you additional or different 588 | permissions. However, no additional obligations are imposed on any 589 | author or copyright holder as a result of your choosing to follow a 590 | later version. 591 | 592 | 15. Disclaimer of Warranty. 593 | 594 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 595 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 596 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 597 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 598 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 599 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 600 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 601 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 602 | 603 | 16. Limitation of Liability. 604 | 605 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 606 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 607 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 608 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 609 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 610 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 611 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 612 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 613 | SUCH DAMAGES. 614 | 615 | 17. Interpretation of Sections 15 and 16. 616 | 617 | If the disclaimer of warranty and limitation of liability provided 618 | above cannot be given local legal effect according to their terms, 619 | reviewing courts shall apply local law that most closely approximates 620 | an absolute waiver of all civil liability in connection with the 621 | Program, unless a warranty or assumption of liability accompanies a 622 | copy of the Program in return for a fee. 623 | 624 | END OF TERMS AND CONDITIONS 625 | 626 | How to Apply These Terms to Your New Programs 627 | 628 | If you develop a new program, and you want it to be of the greatest 629 | possible use to the public, the best way to achieve this is to make it 630 | free software which everyone can redistribute and change under these terms. 631 | 632 | To do so, attach the following notices to the program. It is safest 633 | to attach them to the start of each source file to most effectively 634 | state the exclusion of warranty; and each file should have at least 635 | the "copyright" line and a pointer to where the full notice is found. 636 | 637 | 638 | Copyright (C) 639 | 640 | This program is free software: you can redistribute it and/or modify 641 | it under the terms of the GNU Affero General Public License as published 642 | by the Free Software Foundation, either version 3 of the License, or 643 | (at your option) any later version. 644 | 645 | This program is distributed in the hope that it will be useful, 646 | but WITHOUT ANY WARRANTY; without even the implied warranty of 647 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 648 | GNU Affero General Public License for more details. 649 | 650 | You should have received a copy of the GNU Affero General Public License 651 | along with this program. If not, see . 652 | 653 | Also add information on how to contact you by electronic and paper mail. 654 | 655 | If your software can interact with users remotely through a computer 656 | network, you should also make sure that it provides a way for users to 657 | get its source. For example, if your program is a web application, its 658 | interface could display a "Source" link that leads users to an archive 659 | of the code. There are many ways you could offer source, and different 660 | solutions will be better for different programs; see section 13 for the 661 | specific requirements. 662 | 663 | You should also get your employer (if you work as a programmer) or school, 664 | if any, to sign a "copyright disclaimer" for the program, if necessary. 665 | For more information on this, and how to apply and follow the GNU AGPL, see 666 | . 667 | --------------------------------------------------------------------------------