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

The following examples show how to use org.hyperledger.fabric.sdk.HFClient#setUserContext() . 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: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
public Channel reconstructChannel(List<Peer> peers, HFClient client) {
    checkConfig();
    try {
        org.apache.log4j.Level setTo = null;
        setTo = org.apache.log4j.Level.DEBUG;
        org.apache.log4j.Logger.getLogger("org.hyperledger.fabric").setLevel(setTo);

        Channel newChannel = null;

        client.setUserContext(user);
        newChannel = client.newChannel(channelName);
        for (String orderName : userOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, userOrg.getOrdererLocation(orderName),
                    conf.getOrdererProperties(orderName)));
        }
        
        for (Peer peer : peers) {
            logger.debug(peer.getName());

            newChannel.addPeer(peer);
            userOrg.addPeer(peer);
        }
        newChannel.initialize();
        return newChannel;

    } catch (Exception e) {
        String errMsg = "QueryBlock | reconstructChannel " + e;
        logger.error(errMsg);
        throw new BlkchnException(errMsg, e);
    }

}
 
Example 2
Source File: FabricUtils.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public static Channel initChannel(HFClient client, BlockChainOrgUserDTO userDTO, BlockChainOrgDTO currentOrgDTO,
                                  BlockChainChannelDTO channelDTO, BaasRouteDTO routeDTO, List<BlockChainOrdererDTO> ordererList) throws Exception {
    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

    // 实例化用户需要先在控制台-证书管理中申请客户端证书,申请的企业名称需要与当前登录账户实名认证的企业名称相同
    FabricUser user = new FabricUser(userDTO.getOrgUserName(), new FabricEnrollment(userDTO.getOrgUserKey(), userDTO.getOrgUserCert()),
            currentOrgDTO.getMspId());

    client.setUserContext(user);

    Channel chain = client.newChannel(channelDTO.getChannelKey());

    for(BlockChainOrdererDTO ordererDTO: ordererList) {
        chain.addOrderer(client.newOrderer(ordererDTO.getOrdererKey(), routeDTO.getEndPoint(),
                FabricConfig.getOrderProperties(routeDTO.getSecretId(),routeDTO.getSecretKey(),ordererDTO.getOrdererKey())));
    }

    for(BlockChainOrgNodeDTO nodeDTO : currentOrgDTO.getNodeList()){
        chain.addPeer(client.newPeer(nodeDTO.getNodeKey(), routeDTO.getEndPoint(), FabricConfig.getPeerProperties(routeDTO.getSecretId(),
                routeDTO.getSecretKey(),nodeDTO.getNodeKey())),
                createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER,
                        Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
        //registerEventsForFilteredBlocks()
    }


    chain.initialize();

    return chain;
}
 
Example 3
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 4
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 5
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdate1() throws Exception {

    // Setup client and channel instances
    HFClient client = getTheClient();
    Channel channel = constructChannel(client, FOO_CHANNEL_NAME);

    final ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
            .setVersion(CHAIN_CODE_VERSION)
            .setPath(CHAIN_CODE_PATH).build();

    final String channelName = channel.getName();

    out("Running testUpdate1 - Channel %s", channelName);

    final Collection<String> peersOrganizationMSPIDs = channel.getPeersOrganizationMSPIDs();
    assertNotNull(peersOrganizationMSPIDs);
    assertEquals(1, peersOrganizationMSPIDs.size());
    assertEquals("Org1MSP", peersOrganizationMSPIDs.iterator().next());

    int moveAmount = 5;
    String originalVal = queryChaincodeForCurrentValue(client, channel, chaincodeID);
    String newVal = "" + (Integer.parseInt(originalVal) + moveAmount);

    out("Original value = %s", originalVal);

    //user registered user
    client.setUserContext(orgRegisteredUsers.get("Org1")); // only using org1

    // Move some assets
    moveAmount(client, channel, chaincodeID, "a", "b", "" + moveAmount, null).thenApply(transactionEvent -> {
        // Check that they were moved
        queryChaincodeForExpectedValue(client, channel, newVal, chaincodeID);
        return null;

    }).thenApply(transactionEvent -> {
        // Move them back
        try {
            return moveAmount(client, channel, chaincodeID, "b", "a", "" + moveAmount, null).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }).thenApply(transactionEvent -> {
        // Check that they were moved back
        queryChaincodeForExpectedValue(client, channel, originalVal, chaincodeID);
        return null;

    }).exceptionally(e -> {
        if (e instanceof CompletionException && e.getCause() != null) {
            e = e.getCause();
        }
        if (e instanceof TransactionEventException) {
            BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
            if (te != null) {

                e.printStackTrace(System.err);
                fail(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()));
            }
        }

        e.printStackTrace(System.err);
        fail(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()));

        return null;

    }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);

    channel.shutdown(true); // Force channel to shutdown clean up resources.

    out("testUpdate1 - done");
    out("That's all folks!");
}
 
Example 6
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private Channel reconstructChannel(final boolean isSystemChannel, String name, HFClient client, SampleOrg sampleOrg) throws Exception {

        client.setUserContext(isSystemChannel ? ordererAdmin : sampleOrg.getPeerAdmin());
        Channel newChannel = client.newChannel(name);

        for (String orderName : sampleOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName),
                    testConfig.getOrdererProperties(orderName)));
        }

        if (isSystemChannel) { // done
            newChannel.initialize();
            return newChannel;

        }

        assertTrue(sampleOrg.getPeerNames().size() > 1); // need at least two for testing.

        int i = 0;
        for (String peerName : sampleOrg.getPeerNames()) {
            String peerLocation = sampleOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, testConfig.getPeerProperties(peerName));

            //Query the actual peer for which channels it belongs to and check it belongs to this channel
            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(name)) {
                throw new AssertionError(format("Peer %s does not appear to belong to channel %s", peerName, name));
            }
            Channel.PeerOptions peerOptions = createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.CHAINCODE_QUERY,
                    Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.EVENT_SOURCE));

            if (i % 2 == 0) {
                peerOptions.registerEventsForFilteredBlocks(); // we need a mix of each type for testing.
            } else {
                peerOptions.registerEventsForBlocks();
            }
            ++i;

            newChannel.addPeer(peer, peerOptions);
        }

        //For testing of blocks which are not transactions.
        newChannel.registerBlockListener(blockEvent -> {
            eventQueueCaputure.add(blockEvent); // used with the other queued to make sure same.
            // Note peer eventing will always start with sending the last block so this will get the last endorser block
            int transactions = 0;
            int nonTransactions = 0;
            for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {

                if (BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE == envelopeInfo.getType()) {
                    ++transactions;
                } else {
                    assertEquals(BlockInfo.EnvelopeType.ENVELOPE, envelopeInfo.getType());
                    ++nonTransactions;
                }

            }
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions < 2); // non transaction blocks only have one envelope
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions + transactions > 0); // has to be one.
            assertFalse(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions > 0 && transactions > 0); // can't have both.

            if (nonTransactions > 0) { // this is an update block -- don't care about others here.

                if (blockEvent.isFiltered()) {
                    ++eventCountFilteredBlock; // make sure we're seeing non transaction events.
                } else {
                    ++eventCountBlock;
                }
                assertEquals(0, blockEvent.getTransactionCount());
                assertEquals(1, blockEvent.getEnvelopeCount());
                for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) {
                    fail("Got transaction event in a block update"); // only events for update should not have transactions.
                }
            }
        });

        // Register Queued block listeners just for testing use both ways.
        // Ideally an application would have it's own independent thread to monitor and take off elements as fast as they can.
        // This would wait forever however if event could not be put in the queue like if the capacity is at a maximum. For LinkedBlockingQueue so unlikely
        listenerHandler1 = newChannel.registerBlockListener(blockingQueue1);
        assertNotNull(listenerHandler1);
        // This is the same but put a timeout on it.  If its not queued in time like if the queue is full it would generate a log warning and ignore the event.
        listenerHandler2 = newChannel.registerBlockListener(blockingQueue2, 1L, TimeUnit.SECONDS);
        assertNotNull(listenerHandler2);

        newChannel.initialize();

        return newChannel;
    }
 
Example 7
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 8
Source File: End2endNodeIT.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
@Override
Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) throws Exception {
    // override this method since we don't want to construct the channel that's been done.
    // Just get it out of the samplestore!

    client.setUserContext(sampleOrg.getPeerAdmin());

    return sampleStore.getChannel(client, name).initialize();

}
 
Example 9
Source File: End2endIdemixIT.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
@Override
Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) throws Exception {
    // override this method since we don't want to construct the channel that's been done.
    // Just get it out of the samplestore!

    client.setUserContext(sampleOrg.getPeerAdmin());

    return sampleStore.getChannel(client, name).initialize();

}
 
Example 10
Source File: End2endJavaIT.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
@Override
Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) throws Exception {
    // override this method since we don't want to construct the channel that's been done.
    // Just get it out of the samplestore!

    client.setUserContext(sampleOrg.getPeerAdmin());

    return sampleStore.getChannel(client, name).initialize();

}