Update and Transfer Operations in BigchainDB Part 2

Posted By : Himanshu Bhatt | 25-Sep-2019

Hi, today in this blog I will demonstrate how to perform the transfer operations of assets and adding of metadata and we will look at the details of the transaction, in the previous blog, I showed how to setup BigchainDB and send the data to it. Whenever we update the metadata of the assets or we transfer the assets that operation is called transfer operation in BigchainDB. 

Transfer operations:

Let’s make an API to update the metadata of the same user, we have to add another API in our controller class:

@RestController
public class BigChainController {
    @Autowired
    private BigChainDbService bigChainDbService;
    
    @PostMapping("setBigChainData")
    public ResponseEntity<Object>postBigChainData(@RequestBody MetaDataDto metaDataDto){
        return ResponseHandler.response(bigChainDbService.updateBigchainDataToDb(metaDataDto),"data saved");
    }

    @PutMapping("updateBigchainData")
   public ResponseEntity<Object>updateBigchainData(@RequestParam("assetId") Long assetId,@RequestBody MetaDataDto metaDataDto){
        return ResponseHandler.response(bigChainDbService.saveBigchainDataToDb(metaDataDto),"data saved");
    }

}

Here we are retrieving the bigchaindb data on the basis of the asset id.

 

Let’s make the service class for this which will retrieve the data from the bigchaindb.

  public Map<String, Object> updateBigchainDataToDb(String assetId, MetaDataDto metaDataDto) {
        Map<String, Object> result = new HashMap<>();
        BigchainDbConfigBuilder.baseUrl(EnvVariables.BIGCHAIN_DB_URL).setup();
        PublicKey publicKey = getPublicKey(bigChainDbDetails.getPublicKey());
        BigChainDbGenericCallback callback = new BigChainDbGenericCallback();
        Transaction transferTransaction = null;
        try {
            transferTransaction = BigchainDbTransactionBuilder.init()
                    .addMetaData(metaDataDto)
                    .addInput(null, getSpendFrom(bigChainDbDetails.getTransactionId()), (EdDSAPublicKey) publicKey)
                    .addOutput("1", (EdDSAPublicKey) publicKey)
                    .addAssets(bigChainDbDetails.getAssetId(), String.class)
                    .operation(Operations.TRANSFER)
                    .buildAndSign((EdDSAPublicKey) publicKey, (EdDSAPrivateKey) getPrivateKey(bigChainDbDetails.getPrivateKey()))
                    .sendTransaction(callback.getCallBack());
            logger.info("checking the call back {} in while loop ", callback.isDone());
                       while (!callback.isDone()) {
            }
            if (!callback.isSuccess()) {
                result.put("transactionId", transferTransaction.getId());
                result.put("callBack", callback.isSuccess());
                return result;
            }
        } catch (Exception e) {
            logger.error("exceptioon from transfer Transaction : {}", e.getMessage());
        }
        logger.info("updated transaction:::{}", transferTransaction.getId());
        result.put("transactionId", transferTransaction.getId());
        result.put("callBack", callback.isSuccess());
        return result;
    }

We will add this function to the service class to update the metadata of a user in blockchain this type of operation is transfer operation.

Viewing the transactions:

Let’s view the transaction on the basis of the assetId, we have to make an API on the basis of which we will get all the user transactions we will write the following function in the controller class:

@GetMapping("getTransactions")
    public ResponseEntity<Object> getBigChainDetails(@RequestParam("assetId") Long assetId) {
        return ResponseHandler.response(bigChainDbService.getBigChainDetails(assetId), LocaleService.toLocale("data.fetched"));
    }

 

Let’s write the service class for getting the details of the user:

public List getUsersBigChainDetails(String assetId) {
        Optional<BigChainDbDetails> bigChainDbDetails = bigChainDbRepo.findByAssetId(assetId);
        if (!bigChainDbDetails.isPresent()) {
            throw new DataException(LocaleService.toLocale("Invalid Id"));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<UserBigChainDto> bigchainDbTransactions = objectMapper.readValue(getAllTransactionOnAsset(bigChainDbDetails.get().getAssetId()), new TypeReference<List<UserBigChainDto>>() {
            });
            return bigchainDbTransactions;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

 

public String getAllTransactionOnAsset(String assetId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
        String uri = EnvVariables.BIGCHAIN_DB_URL + "/transactions?asset_id=" + assetId;
        ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
        JSONArray transaction = null;
        try {
            transaction = new JSONArray(result.getBody());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return transaction.toString();
    }

 

Conclusion 

Hence we have successfully demonstrated how BigchainDB works and how to set up this blockchain can be used in many applications.

Related Tags
Request for Proposal

Recaptcha is required.

Sending message..