Java Code Examples for org.hyperledger.fabric.sdk.HFClient#createNewInstance()

The following examples show how to use org.hyperledger.fabric.sdk.HFClient#createNewInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
public ChaincodeManager(String username, FabricConfig fabricConfig)
		throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, TransactionException {
	this.config = fabricConfig;

	orderers = this.config.getOrderers();
	peers = this.config.getPeers();
	chaincode = this.config.getChaincode();

	client = HFClient.createNewInstance();
	log.debug("Create instance of HFClient");
	client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
	log.debug("Set Crypto Suite of HFClient");

	fabricOrg = getFabricOrg(username, config.openCATLS());
	channel = getChannel();
	chaincodeID = getChaincodeID();

	client.setUserContext(fabricOrg.getPeerAdmin());
}
 
Example 2
Source File: FabricEventService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public void unRegisterContractListener(ContractEventListenerRequest contractEventListenerRequest) throws InvalidArgumentException {

        String channelName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                contractEventListenerRequest.getLeagueCode();

        ChannelBean channelBean = ChannelContext.getChannelContext(channelName);
        if(channelBean == null){
            HFClient client = HFClient.createNewInstance();
            Channel currentChannel = super.initChannel(client, contractEventListenerRequest);
            channelBean = new ChannelBean();
            channelBean.setChannel(currentChannel);
            ChannelContext.addChannelContext(channelName,channelBean);
        }

        for(BlockChainContractFunDTO funDTO : contractEventListenerRequest.getFunList()) {
            for (BlockChainContractFunEventDTO eventDTO : funDTO.getEventDTOList()) {

                String channelContractName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                        contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                        contractEventListenerRequest.getLeagueCode() +
                        contractEventListenerRequest.getBlockChainContractDTO().getContractCode() +
                        funDTO.getFunCode() +
                        eventDTO.getEventCode();

                String eventListenerHandle = ChannelContext.getChainCodeEventHandlerContext
                        (channelContractName);

                channelBean.getChannel().unregisterBlockListener(eventListenerHandle);
                ChannelContext.removeChainCodeEventHandlerContext(channelContractName);

            }
            channelBean.setContractEventCount(channelBean.getContractEventCount() - 1);
            if (channelBean.getContractEventCount() == 0) {
                ChannelContext.removeChannelContext(channelName);
            }
        }
    }
 
Example 3
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public QueryResult query(QueryRequest queryRequest) {
    HFClient client = HFClient.createNewInstance();
    QueryResult queryResult = null;
    try {
        Channel currentChannel = super.initChannel(client, queryRequest);

        FabricTemplate fabricTemplate = new FabricTemplate();
        FabricTemplate.setClient(client);
        List<String> peers = FabricUtils.converPeerNodeKey(queryRequest.getStrategyOrgList());

        ChaincodeID chainCodeId = ChaincodeID.newBuilder()
                .setName(queryRequest.getBlockChainContractDTO().getContractKey())
                .setVersion(queryRequest.getBlockChainContractDTO().getVersion())
                .setPath("").build();
        queryResult = fabricTemplate.query(currentChannel, queryRequest.getBlockChainContractFunDTO().getFunKey(),
                queryRequest.getArgs(),
                chainCodeId, peers);
        queryResult.setOrderNo(queryRequest.getOrderNo());
        queryResult.setRequestId(IdUtil.fastUUID());
        queryResult.setRequestContext(JSONUtil.toJsonStr(queryRequest));

        queryResult.setStatus(ResponseCodeEnum.SUCCESS.getCode());
        queryResult.setResponseContext(JSONUtil.toJsonStr(queryResult));

    }catch(Exception e){
        log.error("Fabric SDK query 出错: " + e.getMessage());
        e.printStackTrace();
        queryResult = new QueryResult();
        queryResult.setOrderNo(queryRequest.getOrderNo());
        queryResult.setRequestId(IdUtil.fastUUID());
        queryResult.setRequestContext(JSONUtil.toJsonStr(queryRequest));
        queryResult.setStatus(ResponseCodeEnum.PROCESS_ERROR.getCode());
        queryResult.setErrorMsg(e.getMessage());
    }
    return queryResult;
}
 
Example 4
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public InvokeAsyncQueryResult asyncQueryResult(InvokeAsyncQueryRequest invokeAsyncQueryRequest)  {
    HFClient client = HFClient.createNewInstance();
    Channel currentChannel = super.initChannel(client, invokeAsyncQueryRequest);

    FabricTemplate fabricTemplate = new FabricTemplate();
    FabricTemplate.setClient(client);

    InvokeAsyncQueryResult result = fabricTemplate.asyncQueryResult(currentChannel,invokeAsyncQueryRequest.getTxId());

    result.setOrderNo(invokeAsyncQueryRequest.getOrderNo());
    result.setRequestContext(JSONUtil.toJsonStr(invokeAsyncQueryRequest));
    result.setReturnNo(invokeAsyncQueryRequest.getTxId());
    result.setResponseContext(JSONUtil.toJsonStr(result));
    return result;
}
 
Example 5
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public void runFabricTest(final SampleStore sampleStore) throws Exception {
    ////////////////////////////
    // Setup client

    //Create instance of client.
    HFClient client = HFClient.createNewInstance();

    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
    client.setUserContext(sampleStore.getMember(TEST_ADMIN_NAME, "peerOrg2"));

    SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg2");

    Channel barChannel = sampleStore.getChannel(client, BAR_CHANNEL_NAME);

    barChannel.initialize();
    runChannel(client, barChannel, sampleOrg, 10);
    assertFalse(barChannel.isShutdown());
    assertTrue(barChannel.isInitialized());

    if (testConfig.isFabricVersionAtOrAfter("1.3")) {
        Set<String> expect = new HashSet<>(Arrays.asList("COLLECTION_FOR_A", "COLLECTION_FOR_B"));
        Set<String> got = new HashSet<>();

        CollectionConfigPackage queryCollectionsConfig = barChannel.queryCollectionsConfig(CHAIN_CODE_NAME, barChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin());
        for (CollectionConfigPackage.CollectionConfig collectionConfig : queryCollectionsConfig.getCollectionConfigs()) {
            got.add(collectionConfig.getName());

        }
        assertEquals(expect, got);
    }

    out("That's all folks!");
}
 
Example 6
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
public static HFClient initializeClient(FabricConfig fabricConfig) throws InvalidArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, CryptoException, ClassNotFoundException {
    HFClient hfClient = HFClient.createNewInstance();
    hfClient.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
    hfClient.setUserContext(new FabricUser(fabricConfig));
    return hfClient;
}
 
Example 7
Source File: FabricEventService.java    From fabric-java-block with GNU General Public License v3.0 4 votes vote down vote up
public void registerContractListener(ContractEventListenerRequest contractEventListenerRequest) throws InvalidArgumentException {

        String channelName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                contractEventListenerRequest.getLeagueCode();


        ChannelBean channelBean = ChannelContext.getChannelContext(channelName);
        if(channelBean == null){
            HFClient client = HFClient.createNewInstance();
            Channel currentChannel = super.initChannel(client, contractEventListenerRequest);
            channelBean = new ChannelBean();
            channelBean.setChannel(currentChannel);
            ChannelContext.addChannelContext(channelName,channelBean);
        }

       for(BlockChainContractFunDTO funDTO : contractEventListenerRequest.getFunList()){
           for(BlockChainContractFunEventDTO eventDTO : funDTO.getEventDTOList()){

               ContractEvent contractEvent = new ContractEvent();
               contractEvent.setChainNetCode(contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode());
               contractEvent.setChainNetKey(contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetKey());
               contractEvent.setChannelCode(contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode());
               contractEvent.setChannelKey(contractEventListenerRequest.getBlockChainChannelDTO().getChannelKey());
               contractEvent.setContractCode(contractEventListenerRequest.getBlockChainContractDTO().getContractCode());
               contractEvent.setContractKey(contractEventListenerRequest.getBlockChainContractDTO().getContractKey());
               contractEvent.setFunCode(funDTO.getFunCode());
               contractEvent.setFunKey(funDTO.getFunKey());
               contractEvent.setEventCode(eventDTO.getEventCode());
               contractEvent.setEventKey(eventDTO.getEventKey());
               contractEvent.setEvenType(eventDTO.getEventType());
               contractEvent.setLeagueCode(contractEventListenerRequest.getLeagueCode());

               String eventListenerHandle = FabricEventListener.setChainCodeEventListener
                       (channelBean.getChannel(), contractEvent,remoteBlockEventService);

               String channelContractName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                       contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                       contractEventListenerRequest.getLeagueCode() +
                       contractEventListenerRequest.getBlockChainContractDTO().getContractCode() +
                       funDTO.getFunCode() +
                       eventDTO.getEventCode();

               ChannelContext.addChainCodeEventHandlerContext
                       (channelContractName,eventListenerHandle);

           }
           channelBean.setContractEventCount(channelBean.getContractEventCount() + 1);
       }



    }
 
Example 8
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 4 votes vote down vote up
public InvokeResult invoke(InvokeRequest invokeRequest) {
    HFClient client = HFClient.createNewInstance();
    InvokeResult invokeResult = null;
    try {
        Channel currentChannel = super.initChannel(client, invokeRequest);

        FabricTemplate fabricTemplate = new FabricTemplate();
        FabricTemplate.setClient(client);

        List<String> peers = FabricUtils.converPeerNodeKey(invokeRequest.getStrategyOrgList());

        ChaincodeID chainCodeId = ChaincodeID.newBuilder()
                .setName(invokeRequest.getBlockChainContractDTO().getContractKey())
                .setVersion(invokeRequest.getBlockChainContractDTO().getVersion())
                .setPath("").build();
        invokeResult = fabricTemplate.transaction
                (currentChannel, invokeRequest.getBlockChainContractFunDTO().getFunKey(),
                        invokeRequest.getArgs(),
                        chainCodeId,
                        peers, invokeRequest.getBlockChainContractFunDTO().getAsyncFlag());
        invokeResult.setOrderNo(invokeRequest.getOrderNo());
        invokeResult.setRequestId(IdUtil.fastUUID());
        invokeResult.setRequestContext(JSONUtil.toJsonStr(invokeRequest));
        invokeResult.setReturnNo(invokeResult.getTxId());
        if (AsyncInvokeTypeEnum.ASYNC.getCode().equals(invokeRequest.getBlockChainContractFunDTO().getAsyncFlag())) {
            invokeResult.setStatus(ResponseCodeEnum.PROCESSING.getCode());
        } else {
            invokeResult.setStatus(ResponseCodeEnum.SUCCESS.getCode());
        }
        invokeResult.setResponseContext(JSONUtil.toJsonStr(invokeResult));
    }catch (Exception e){
        log.error("Fabric SDK invoke 出错: " + e.getMessage());
        e.printStackTrace();
        invokeResult = new InvokeResult();
        invokeResult.setOrderNo(invokeRequest.getOrderNo());
        invokeResult.setRequestId(IdUtil.fastUUID());
        invokeResult.setRequestContext(JSONUtil.toJsonStr(invokeRequest));
        invokeResult.setStatus(ResponseCodeEnum.PROCESS_ERROR.getCode());
        invokeResult.setErrorMsg(e.getMessage());
    }
    return invokeResult;
}
 
Example 9
Source File: End2endIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void runFabricTest(final SampleStore sampleStore) throws Exception {

        ////////////////////////////
        // Setup client

        //Create instance of client.
        HFClient client = HFClient.createNewInstance();

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

        ////////////////////////////
        //Construct and run the channels
        SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
        Channel fooChannel = constructChannel(FOO_CHANNEL_NAME, client, sampleOrg);
        sampleStore.saveChannel(fooChannel);
        runChannel(client, fooChannel, true, sampleOrg, 0);

        assertFalse(fooChannel.isShutdown());
        fooChannel.shutdown(true); // Force foo channel to shutdown clean up resources.
        assertTrue(fooChannel.isShutdown());

        assertNull(client.getChannel(FOO_CHANNEL_NAME));
        out("\n");

        sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
        Channel barChannel = constructChannel(BAR_CHANNEL_NAME, client, sampleOrg);
        assertTrue(barChannel.isInitialized());
        /*
         * sampleStore.saveChannel uses {@link Channel#serializeChannel()}
         */
        sampleStore.saveChannel(barChannel);
        assertFalse(barChannel.isShutdown());
        runChannel(client, barChannel, true, sampleOrg, 100); //run a newly constructed bar channel with different b value!
        //let bar channel just shutdown so we have both scenarios.

        out("\nTraverse the blocks for chain %s ", barChannel.getName());

        blockWalker(client, barChannel);

        assertFalse(barChannel.isShutdown());
        assertTrue(barChannel.isInitialized());
        out("That's all folks!");
    }
 
Example 10
Source File: End2endAndBackAgainIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void runFabricTest(final SampleStore sampleStore) throws Exception {
    ////////////////////////////
    // Setup client

    //Create instance of client.
    HFClient client = HFClient.createNewInstance();

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

    ////////////////////////////
    //Reconstruct and run the channels
    SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
    Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg);
    runChannel(client, fooChannel, sampleOrg, 0);
    assertFalse(fooChannel.isShutdown());
    assertTrue(fooChannel.isInitialized());
    fooChannel.shutdown(true); //clean up resources no longer needed.
    assertTrue(fooChannel.isShutdown());
    out("\n");

    sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
    Channel barChannel = reconstructChannel(BAR_CHANNEL_NAME, client, sampleOrg);
    runChannel(client, barChannel, sampleOrg, 100); //run a newly constructed foo channel with different b value!
    assertFalse(barChannel.isShutdown());
    assertTrue(barChannel.isInitialized());

    if (!testConfig.isRunningAgainstFabric10()) { //Peer eventing service support started with v1.1

        // Now test replay feature of V1.1 peer eventing services.
        byte[] replayChannelBytes = barChannel.serializeChannel();
        barChannel.shutdown(true);

        Channel replayChannel = client.deSerializeChannel(replayChannelBytes);

        out("doing testPeerServiceEventingReplay,0,-1,false");
        testPeerServiceEventingReplay(client, replayChannel, 0L, -1L, false);

        replayChannel = client.deSerializeChannel(replayChannelBytes);
        out("doing testPeerServiceEventingReplay,0,-1,true"); // block 0 is import to test
        testPeerServiceEventingReplay(client, replayChannel, 0L, -1L, true);

        //Now do it again starting at block 1
        replayChannel = client.deSerializeChannel(replayChannelBytes);
        out("doing testPeerServiceEventingReplay,1,-1,false");
        testPeerServiceEventingReplay(client, replayChannel, 1L, -1L, false);

        //Now do it again starting at block 2 to 3
        replayChannel = client.deSerializeChannel(replayChannelBytes);
        out("doing testPeerServiceEventingReplay,2,3,false");
        testPeerServiceEventingReplay(client, replayChannel, 2L, 3L, false);

    }

    out("That's all folks!");
}
 
Example 11
Source File: FabricClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor
 * 
 * @param context
 * @throws CryptoException
 * @throws InvalidArgumentException
 * @throws InvocationTargetException 
 * @throws NoSuchMethodException 
 * @throws ClassNotFoundException 
 * @throws InstantiationException 
 * @throws IllegalAccessException 
 */
public FabricClient(User context) throws CryptoException, InvalidArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
	CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
	// setup the client
	instance = HFClient.createNewInstance();
	instance.setCryptoSuite(cryptoSuite);
	instance.setUserContext(context);
}
 
Example 12
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
private static HFClient getTheClient() throws Exception {

        HFClient client = HFClient.createNewInstance();
        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

        User peerAdmin = getAdminUser(TEST_ORG);
        client.setUserContext(peerAdmin);

        return client;
    }
 
Example 13
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
@Before
    public void checkConfig() throws Exception {

        out("\n\n\nRUNNING: UpdateChannelIT\n");
        resetConfig();
        configHelper.customizeConfig();
//        assertEquals(256, Config.getConfig().getSecurityLevel());

        testSampleOrgs = testConfig.getIntegrationTestsSampleOrgs();

        ////////////////////////////
        // Setup client

        //Create instance of client.
        client = HFClient.createNewInstance();

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

        ////////////////////////////
        //Set up USERS

        //Persistence is not part of SDK. Sample file store is for demonstration purposes only!
        //   MUST be replaced with more robust application implementation  (Database, LDAP)
        File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties");
        //    sampleStoreFile.deleteOnExit();

        sampleStore = new SampleStore(sampleStoreFile);

        //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface

        ////////////////////////////
        // get users for all orgs

        for (SampleOrg sampleOrg : testSampleOrgs) {

            final String orgName = sampleOrg.getName();
            sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName));
        }

        sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");

        SampleOrg sampleOrg2 = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
        baduser = sampleOrg2.getUser("user1");

        final String sampleOrgName = sampleOrg.getName();

        ordererAdmin = sampleStore.getMember(sampleOrgName + "OrderAdmin", sampleOrgName, "OrdererMSP",
                Util.findFileSk(Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/keystore/").toFile()),
                Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/signcerts/[email protected]").toFile());

        httpclient = HttpClients.createDefault();
    }