BigchainDB Java Spring boot

BigchainDB Java Spring boot is a wonderful combination for java developers with interest in working with the blockchain database. BigchainDB is a database that offers blockchain features/characteristics that can be useful for building solutions that require decentralisation and immutability. We look at how we can integrate a java Spring boot application to use BigchainDB. The example covers 3 main areas:

  • Configuration/initialization.
  • Saving an Asset to BigchainDB.
  • Searching for an Asset in BigChainDB.

The application uses maven and works with java 8 +.

BigchainDB Java Spring boot

The first step is to setup a local test BigchainDB instance on your machine. This requires that you have on your machine installed already Docker and Docker Compose.

  1.  git clone https://github.com/bigchaindb/bigchaindb.git
  2.  cd bigchain
  3.  make run

When you run the command make run, it will download the docker images required to run BigchainDB. It starts the BigchainDB instance and makes it available on the http port 9984.

The next step is to create our Spring boot application. You can use the Spring initializer and create a Spring boot web application which you can open in your favourite IDE.

To the springboot application we add the dependencies for BigchainDB and the springboot starter test.

<dependency>
    <groupId>com.bigchaindb</groupId>
    <artifactId>bigchaindb-driver</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

For the example we will be saving an Asset of a Car to the BigchainDB.We create a Class Car which will represent the Car Asset.

public class Car implements Serializable {

    private String model;
    private String color;
    private String chasisNumber;
    private String manufactureYear;


    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getChasisNumber() {
        return chasisNumber;
    }

    public void setChasisNumber(String chasisNumber) {
        this.chasisNumber = chasisNumber;
    }

    public String getManufactureYear() {
        return manufactureYear;
    }

    public void setManufactureYear(String manufactureYear) {
        this.manufactureYear = manufactureYear;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Car{");
        sb.append("model='").append(model).append('\'');
        sb.append(", color='").append(color).append('\'');
        sb.append(", chasisNumber='").append(chasisNumber).append('\'');
        sb.append(", manufactureYear='").append(manufactureYear).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

There are 2 main things we want to do which are saving data to the BigchainDB and searching for what has been saved in the BigchainDB.Create an interface with the 2 methods we want to use.

public interface CarRepository {
    Car save(Car car);
    List<Car> search(String searchKey);
}

The save is for saving the car asset to the BigchainDB and the search is for searching for data in the BigChainDB using a search key.

INITIALISING CONNECTION TO BIGCHAINDB

Before we can save to the BigchainDB your first have to initialize your connection to the Bigchain instance. A private and public key will be required when accessing you BigchainDb instance.

public class CarRepositoryImpl implements CarRepository {
    private static final Logger LOGGER = LoggerFactory.getLogger(CarRepositoryImpl.class);
    private static final String PUBLIC_KEY = "302a300506032b657003210033c43dc2180936a2a9138a05f06c892d2fb1cfda4562cbc35373bf13cd8ed373";
    private static final String PRIVATE_KEY = "302e020100300506032b6570042204206f6b0cd095f1e83fc5f08bffb79c7c8a30e77a3ab65f4bc659026b76394fcea8";


    private KeyPair keyPair;

    public void setKeyPair(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    public CarRepositoryImpl() {
        buildKeys 
        
        /*This configures a connection to the Bigchain instance, we are using localhost to connect to a local instance
        * but this can be replaced by any instance you may also have*/
        BigchainDbConfigBuilder
                .baseUrl("https://localhost:9984/")
                .setup();
    }

/* builds the KeyPair required for accessing and saving transaction to the blockchain using the public and private keys defined*/
private void buildKeys(){
    try{
        X509EncodedKeySpec encoded = new X509EncodedKeySpec(Utils.hexToBytes(PUBLIC_KEY));
        EdDSAPublicKey keyIn = new EdDSAPublicKey(encoded);
        PKCS8EncodedKeySpec encodedP = new PKCS8EncodedKeySpec(Utils.hexToBytes(PRIVATE_KEY));
        EdDSAPrivateKey keyPr = new EdDSAPrivateKey(encodedP);
        setKeyPair(new KeyPair(keyIn,keyPr));
    }
    catch (Exception e){
        if(LOGGER.isDebugEnabled()){
            LOGGER.error("{}",e);
        }
    }
}

}

This sorts out the process of initializing our connection to the BigChain instance.

Saving data to BigchainDB

For saving data to BigchainDB we use the following method.

@Override
public Car save(Car car) {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> assetData = mapper.convertValue(car, Map.class);//convert Car Object to Map which will be saved as the Asset data
    try {
        Transaction createTransaction = BigchainDbTransactionBuilder
                .init()
                .addAssets(assetData, TreeMap.class)
                .operation(Operations.CREATE)
                .buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate())
                .sendTransaction();
        if(LOGGER.isDebugEnabled()){
            LOGGER.info("transaction created \n{}",createTransaction);
        }
    } catch (IOException e) {
        if(LOGGER.isDebugEnabled()){
            LOGGER.error("{}",e);
        }
        throw new TransactionException(e);
    }
    return car;
}

SEARCHING DATA IN BIGCHAINDB

For searching through data saved in the BigchainDB we use the following method.

@Override
public List<Car> search(String searchKey) {
    List<Car> carList = new ArrayList<>();
    try {
        Assets assets = AssetsApi.getAssets(searchKey);
        List<Asset> assetsList = assets.getAssets();
        assetsList.forEach(asset -> {
            try{
                Car car = stringToObject(tojson(asset.getData()),Car.class);
                carList.add(car);
            }catch (Exception e){
                if(LOGGER.isDebugEnabled()){
                    LOGGER.error("not instance of Car {}",e.getMessage());
                }
            }
        });
    } catch (IOException e) {
        if(LOGGER.isDebugEnabled()){
            LOGGER.error("{}",e);
        }
        throw new TransactionException(e);
    }
    return carList;
}

private String tojson(Object obj){
    ObjectMapper mapper=new ObjectMapper();
    try {
        return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        if(LOGGER.isDebugEnabled()){
            LOGGER.error("{}",e);
        }
        return "";
    }
}

public static <T> T stringToObject(String s, Class<T> clazz) {
    return new Gson().fromJson(s, clazz);
}

With this you are now ready to save and read through data in BigchainDB from your Spring boot application. You can get the full solution on github.

In conclusion the steps for integrating BigchainDB to Spring boot application are fairly simple. A lot more can be achieved from this and great solutions can be build using this blockchain technology.
You can check out other blockchain related articles from here.

Happy coding!!!.

bmukorera

Passionate software engineer with keen interest in solving world problems using technology.He has vast experience in developing enterprise solutions from Telecommunications ,Media,Banking and Consultancy.

You May Also Like

Hyperledger Fabric

Hyperledger : Customising hyperledger explorer

Paynow java spring api

Leave a Reply

Your email address will not be published. Required fields are marked *