Hyperledger fabric java sdk setup

+1 vote

I created hyperledger fabric network using command line. Now i want to perform chaincode transaction from java sdk, can any one share steps to invoke chain code from java.

Nov 17, 2018 in Blockchain by Perry
• 17,100 points
2,691 views
hey, Did you get solution??? you able to perform chaincode transaction from java sdk??

please share code or steps if yes
Hey @John. The below solution worked for me. Please try it.

1 answer to this question.

+1 vote

Suppose (assuming) you started the first network from BYFN network in commandline, You can access ,query , invoke chaincode using Fabric Java SDK Dependency. Refer to this code :

public class Test {

    final HFClient client = HFClient.createNewInstance();
    Channel channel;
    QueryByChaincodeRequest qpr;

    void setupCryptoMaterialsForClient() throws CryptoException,
            InvalidArgumentException {
        // Set default crypto suite for HF client

        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

        client.setUserContext(new User() {

            public String getName() {
                return "PeerAdmin";
            }

            public Set<String> getRoles() {
                return null;
            }

            public String getAccount() {
                return null;
            }

            public String getAffiliation() {
                return null;
            }

            public Enrollment getEnrollment() {
                return new Enrollment() {
                    public PrivateKey getKey() {
                        PrivateKey privateKey = null;
                        try {
                            File privateKeyFile = findFileSk("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore");
                            privateKey = getPrivateKeyFromBytes(IOUtils
                                    .toByteArray(new FileInputStream(
                                            privateKeyFile)));
                        } catch (InvalidKeySpecException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (NoSuchProviderException e) {
                            e.printStackTrace();
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        }
                        return privateKey;
                    }

                    public String getCert() {

                        String certificate = null;
                        try {
                            File certificateFile = new File(
                                    "D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem");
                            certificate = new String(IOUtils
                                    .toByteArray(new FileInputStream(
                                            certificateFile)), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return certificate;
                    }
                };
            }

            public String getMspId() {
                return "Org1MSP";
            }
        });
    }

    static File findFileSk(String directorys) {

        File directory = new File(directorys);

        File[] matches = directory.listFiles((dir, name) -> name
                .endsWith("_sk"));

        if (null == matches) {
            throw new RuntimeException(format(
                    "Matches returned null does %s directory exist?", directory
                            .getAbsoluteFile().getName()));
        }

        if (matches.length != 1) {
            throw new RuntimeException(format(
                    "Expected in %s only 1 sk file but found %d", directory
                            .getAbsoluteFile().getName(), matches.length));
        }

        return matches[0];
    }



    static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException,
            NoSuchProviderException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        final Reader pemReader = new StringReader(new String(data));

        final PrivateKeyInfo pemPair;
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            pemPair = (PrivateKeyInfo) pemParser.readObject();
        }

        PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(
                BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);

        return privateKey;
    }

    void createChannel() throws InvalidArgumentException, TransactionException, ProposalException {
        channel = client.newChannel("mychannel");
        Properties ordererProperties = new Properties();
        ordererProperties
                .setProperty(
                        "pemFile",
                        "D:/FabricCert/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt");
        ordererProperties.setProperty("trustServerCertificate", "true"); // testing
                                                                            // environment
                                                                            // only
                                                                            // NOT
                                                                            // FOR
                                                                            // PRODUCTION!
        ordererProperties
                .setProperty("hostnameOverride", "orderer.example.com");
        ordererProperties.setProperty("sslProvider", "openSSL");
        ordererProperties.setProperty("negotiationType", "TLS");
        ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime",
                new Object[] { 5L, TimeUnit.MINUTES });
        ordererProperties.put(
                "grpc.NettyChannelBuilderOption.keepAliveTimeout",
                new Object[] { 8L, TimeUnit.SECONDS });
        channel.addOrderer(client.newOrderer("orderer.example.com",
                "grpcs://localhost:7050", ordererProperties));  // use the network orderer container URL




        Properties peerProperties = new Properties();
        peerProperties.setProperty("pemFile",
         "D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt");
        peerProperties.setProperty("trustServerCertificate", "true"); // testing                                                                //                                                              // PRODUCTION!
         peerProperties.setProperty("hostnameOverride",
         "peer0.org1.example.com");
        peerProperties.setProperty("sslProvider", "openSSL");
        peerProperties.setProperty("negotiationType", "TLS");
        peerProperties
                .put("grpc.NettyChannelBuilderOption.maxInboundMessageSize",
                        9000000);

         channel.addPeer(client.newPeer("peer0.org1.example.com",
         "grpcs://localhost:7051",peerProperties)); // use the network peer container URL

        channel.initialize();
    }


    void queryChain() throws InvalidArgumentException, ProposalException, ChaincodeEndorsementPolicyParseException, IOException {

        // get channel instance from client


        Channel channel2 = client.getChannel("mychannel");


        int blocksize = (int) channel2.queryBlockchainInfo().getHeight();
        System.out.println("NO of Blocks: "+blocksize);



        // create chaincode request
        qpr = client.newQueryProposalRequest();
        // build cc id providing the chaincode name. Version is omitted here.
        ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("mycc")
                .build();
        qpr.setChaincodeID(fabcarCCId);
        // CC function to be called.
        qpr.setFcn("query");
        qpr.setArgs(new String[] { "a" });


        Collection<ProposalResponse> res = channel2.queryByChaincode(qpr,channel2.getPeers());

        // display response
        for (ProposalResponse pres : res) {

            String stringResponse = new String(
                    pres.getChaincodeActionResponsePayload());
            System.out.println("Query Response from Peer " + pres.getPeer().getName() + ":" +stringResponse);

        }
    }



    void invokeChain() throws InvalidArgumentException, ProposalException, ChaincodeEndorsementPolicyParseException, IOException {

        Channel channel = client.getChannel("mychannel");
        TransactionProposalRequest req = client.newTransactionProposalRequest();
        ChaincodeID cid = ChaincodeID.newBuilder().setName("mycc").build();
        req.setChaincodeID(cid);
        req.setFcn("invoke");
        req.setArgs(new String[] { "b", "a", "5" });
        Collection<ProposalResponse> resps = channel
                .sendTransactionProposal(req);

        channel.sendTransaction(resps);
        System.out.println(resps.iterator().next().getMessage());




    }


    public static void main(String args[]) throws Exception {
        Test t = new Test();
        t.setupCryptoMaterialsForClient();
        t.createChannel();
        t.invokeChain();
        //t.queryChain(); For querying

    }
}

Make sure u get and access proper certificates for enrollment and container access . Crypto material would be generated in the folder where the crypto-config.yaml file is available

answered Nov 17, 2018 by Christine
• 15,790 points

Related Questions In Blockchain

+1 vote
2 answers
+1 vote
1 answer
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,451 views
0 votes
1 answer

Invalid Batch or signature in Savtooth

This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE

answered Aug 1, 2018 in Blockchain by digger
• 26,740 points
1,004 views
+1 vote
1 answer
+1 vote
1 answer
0 votes
1 answer

Hyperledger Fabric query system chaincode using node SDK

The Fabric Node SDK actually provides a ...READ MORE

answered Nov 9, 2018 in Blockchain by Christine
• 15,790 points
1,196 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP