Example usage for java.util Collection clear

List of usage examples for java.util Collection clear

Introduction

In this page you can find the example usage for java.util Collection clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this collection (optional operation).

Usage

From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java

/**
 * Import the realms used for a view component
 * @param doc/* w  w  w. ja  va2  s  . c  o  m*/
 * @param siteId
 * @param useNewIDs
 */
private void importRealms(org.w3c.dom.Node doc, Integer siteId, boolean useNewIDs) {
    mappingRealmsSimplePw = new Hashtable<Integer, Integer>();
    mappingRealmsJdbc = new Hashtable<Integer, Integer>();
    mappingRealmsLdap = new Hashtable<Integer, Integer>();
    mappingRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealmsSimplePw = new Hashtable<Integer, Integer>();
    loginPagesRealmsJdbc = new Hashtable<Integer, Integer>();
    loginPagesRealmsLdap = new Hashtable<Integer, Integer>();
    loginPagesRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealm2vc = new Hashtable<Integer, Integer>();
    try {
        SiteHbm site = super.getSiteHbmDao().load(siteId);
        UserHbm userLogged = super.getUserHbmDao().load(AuthenticationHelper.getUserName());
        Iterator itRealms = XercesHelper.findNodes(doc, "//realmSimplePw");
        while (itRealms.hasNext()) {
            if (log.isDebugEnabled())
                log.debug("Found RealmSimplePw to import...");
            Element elmRealm = (Element) itRealms.next();
            Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "simplePwRealmId"));
            RealmSimplePwHbm realm = null;
            if (useNewIDs) {
                realm = getRealmSimplePwHbmDao().create(elmRealm, true);
                realm.setSite(site);
                //realm.setOwner(userLogged);
                mappingRealmsSimplePw.put(id, realm.getSimplePwRealmId()); // mapping OLD-ID to NEW-ID
            } else {
                try {
                    if (log.isDebugEnabled())
                        log.debug("searching RealmSimplePw: " + id);
                    realm = super.getRealmSimplePwHbmDao().load(id);
                    String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                    if (realmName != null && realmName.length() > 0) {
                        realm.setRealmName(realmName);
                    } else {
                        realm.setRealmName(null);
                    }
                    realm.setSite(site);
                    {
                        // import users, first delete all existing ones for this realm
                        Collection toDelete = new ArrayList();
                        toDelete.addAll(realm.getSimplePwRealmUsers());
                        Iterator it = toDelete.iterator();
                        while (it.hasNext()) {
                            super.getRealmSimplePwUserHbmDao().remove(((RealmSimplePwUserHbm) it.next()));
                        }
                        toDelete.clear();
                        realm.getSimplePwRealmUsers().clear();
                        Iterator itUsers = XercesHelper.findNodes(elmRealm,
                                "simplePwRealmUsers/realmSimplePwUser");
                        while (itUsers.hasNext()) {
                            Element elmUser = (Element) itUsers.next();
                            RealmSimplePwUserHbm user = ((RealmSimplePwUserHbmDaoImpl) getRealmSimplePwUserHbmDao())
                                    .create(elmUser, false);
                            user.setSimplePwRealm(realm);

                            realm.getSimplePwRealmUsers().add(user);
                        }
                    }
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("creating RealmSimplePw: " + id);
                    realm = super.getRealmSimplePwHbmDao().create(elmRealm, false);
                    realm.setSite(site);
                }
            }
            String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
            if (loginPageId != null && loginPageId.length() > 0)
                loginPagesRealmsSimplePw.put(id, new Integer(loginPageId));
        }
        itRealms = XercesHelper.findNodes(doc, "//realmLdap");
        while (itRealms.hasNext()) {
            if (log.isDebugEnabled())
                log.debug("Found RealmLdap to import...");
            Element elmRealm = (Element) itRealms.next();
            Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "ldapRealmId"));
            RealmLdapHbm realm = null;
            if (useNewIDs) {
                realm = super.getRealmLdapHbmDao().create(elmRealm, true);
                realm.setSite(site);
                mappingRealmsLdap.put(id, realm.getLdapRealmId()); // mapping OLD-ID to NEW-ID
            } else {
                try {
                    if (log.isDebugEnabled())
                        log.debug("searching RealmLdap: " + id);
                    realm = super.getRealmLdapHbmDao().load(id);
                    String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                    if (realmName != null && realmName.length() > 0) {
                        realm.setRealmName(realmName);
                    } else {
                        realm.setRealmName(null);
                    }
                    String ldapPrefix = XercesHelper.getNodeValue(elmRealm, "ldapPrefix");
                    realm.setLdapPrefix(ldapPrefix);
                    String ldapSuffix = XercesHelper.getNodeValue(elmRealm, "ldapSuffix");
                    realm.setLdapSuffix(ldapSuffix);
                    String ldapUrl = XercesHelper.getNodeValue(elmRealm, "ldapUrl");
                    realm.setLdapUrl(ldapUrl);
                    String ldapAuthenticationType = XercesHelper.getNodeValue(elmRealm,
                            "ldapAuthenticationType");
                    realm.setLdapAuthenticationType(ldapAuthenticationType);
                    realm.setSite(site);
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("creating RealmLdap: " + id);
                    realm = super.getRealmLdapHbmDao().create(elmRealm, false);
                    realm.setSite(site);
                }
            }
            String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
            if (loginPageId != null && loginPageId.length() > 0)
                loginPagesRealmsLdap.put(id, new Integer(loginPageId));
        }
        itRealms = XercesHelper.findNodes(doc, "//realmJdbc");
        while (itRealms.hasNext()) {
            if (log.isDebugEnabled())
                log.debug("Found RealmJdbc to import...");
            Element elmRealm = (Element) itRealms.next();
            Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "jdbcRealmId"));
            RealmJdbcHbm realm = null;
            if (useNewIDs) {
                realm = super.getRealmJdbcHbmDao().create(elmRealm, true);
                realm.setSite(site);
                mappingRealmsJdbc.put(id, realm.getJdbcRealmId()); // mapping OLD-ID to NEW-ID
            } else {
                try {
                    if (log.isDebugEnabled())
                        log.debug("searching RealmJdbc: " + id);
                    realm = super.getRealmJdbcHbmDao().load(id);
                    String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                    if (realmName != null && realmName.length() > 0) {
                        realm.setRealmName(realmName);
                    } else {
                        realm.setRealmName(null);
                    }
                    String jndiName = XercesHelper.getNodeValue(elmRealm, "jndiName");
                    realm.setJndiName(jndiName);
                    String statementUser = XercesHelper.getNodeValue(elmRealm, "statementUser");
                    realm.setStatementUser(statementUser);
                    String statementRolePerUser = XercesHelper.getNodeValue(elmRealm, "statementRolePerUser");
                    realm.setStatementRolePerUser(statementRolePerUser);
                    realm.setSite(site);
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("creating RealmJdbc: " + id);
                    realm = super.getRealmJdbcHbmDao().create(elmRealm, false);
                    realm.setSite(site);
                }
            }
            String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
            if (loginPageId != null && loginPageId.length() > 0)
                loginPagesRealmsJdbc.put(id, new Integer(loginPageId));
        }
        itRealms = XercesHelper.findNodes(doc, "//realmJaas");
        while (itRealms.hasNext()) {
            if (log.isDebugEnabled())
                log.debug("Found RealmJaas to import...");
            Element elmRealm = (Element) itRealms.next();
            Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "jaasRealmId"));
            RealmJaasHbm realm = null;
            if (useNewIDs) {
                realm = super.getRealmJaasHbmDao().create(elmRealm, true);
                realm.setSite(site);
                mappingRealmsJaas.put(id, realm.getJaasRealmId()); // mapping OLD-ID to NEW-ID
            } else {
                try {
                    if (log.isDebugEnabled())
                        log.debug("searching RealmJaas: " + id);
                    realm = super.getRealmJaasHbmDao().load(id);
                    String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                    if (realmName != null && realmName.length() > 0) {
                        realm.setRealmName(realmName);
                    } else {
                        realm.setRealmName(null);
                    }
                    String jaasPolicyName = XercesHelper.getNodeValue(elmRealm, "jaasPolicyName");
                    realm.setJaasPolicyName(jaasPolicyName);
                    realm.setSite(site);
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("creating RealmJaas: " + id);
                    realm = super.getRealmJaasHbmDao().create(elmRealm, false);
                    realm.setSite(site);
                }
            }
            String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
            if (loginPageId != null && loginPageId.length() > 0)
                loginPagesRealmsJaas.put(id, new Integer(loginPageId));
        }

    } catch (Exception exe) {
        log.error("Error occured importRealms: " + exe.getMessage(), exe);
    }

}

From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java

void runChannel(HFClient client, Channel channel, final int workerId, final int runId, SampleOrg sampleOrg,
        final int delta, final int start) {
    int ret = -1;

    class ChaincodeEventCapture { //A test class to capture chaincode events
        final String handle;
        final BlockEvent blockEvent;
        final ChaincodeEvent chaincodeEvent;

        ChaincodeEventCapture(String handle, BlockEvent blockEvent, ChaincodeEvent chaincodeEvent) {
            this.handle = handle;
            this.blockEvent = blockEvent;
            this.chaincodeEvent = chaincodeEvent;
        }/*from w  w w .  j  av a  2 s .c o  m*/
    }
    Vector<ChaincodeEventCapture> chaincodeEvents = new Vector<>(); // Test list to capture chaincode events.

    try {

        final String channelName = channel.getName();
        boolean isFooChain = FOO_CHANNEL_NAME.equals(channelName);
        out("Running channel %s", channelName);

        Collection<Orderer> orderers = channel.getOrderers();
        final ChaincodeID chaincodeID;
        Collection<ProposalResponse> responses;
        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();

        // Register a chaincode event listener that will trigger for any chaincode id and only for EXPECTED_EVENT_NAME event.

        //            String chaincodeEventListenerHandle = channel.registerChaincodeEventListener(Pattern.compile(".*"),
        //                    Pattern.compile(Pattern.quote(EXPECTED_EVENT_NAME)),
        //                    (handle, blockEvent, chaincodeEvent) -> {
        //
        //                        chaincodeEvents.add(new ChaincodeEventCapture(handle, blockEvent, chaincodeEvent));
        //
        //                        String es = blockEvent.getPeer() != null ? blockEvent.getPeer().getName() : blockEvent.getEventHub().getName();
        //                        out("RECEIVED Chaincode event with handle: %s, chaincode Id: %s, chaincode event name: %s, "
        //                                        + "transaction id: %s, event payload: \"%s\", from eventhub: %s",
        //                                handle, chaincodeEvent.getChaincodeId(),
        //                                chaincodeEvent.getEventName(),
        //                                chaincodeEvent.getTxId(),
        //                                new String(chaincodeEvent.getPayload()), es);
        //
        //                    });

        //For non foo channel unregister event listener to test events are not called.
        //            if (!isFooChain) {
        //                channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
        //                chaincodeEventListenerHandle = null;
        //
        //            }

        ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
                .setVersion(CHAIN_CODE_VERSION);
        if (null != CHAIN_CODE_PATH) {
            chaincodeIDBuilder.setPath(CHAIN_CODE_PATH);

        }
        chaincodeID = chaincodeIDBuilder.build();

        successful.clear();
        failed.clear();

        final User user = sampleOrg.getUser(TESTUSER_1_NAME);

        ///////////////
        /// Send transaction proposal to all peers
        TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
        transactionProposalRequest.setChaincodeID(chaincodeID);
        transactionProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
        transactionProposalRequest.setUserContext(user);
        //transactionProposalRequest.setFcn("invoke");
        transactionProposalRequest.setFcn("move");
        transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
        transactionProposalRequest.setArgs("a" + workerId, "b" + workerId, delta + "");

        Map<String, byte[]> tm2 = new HashMap<>();
        tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); //Just some extra junk in transient map
        tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); // ditto
        tm2.put("result", ":)".getBytes(UTF_8)); // This should be returned see chaincode why.
        tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); //This should trigger an event see chaincode why.

        transactionProposalRequest.setTransientMap(tm2);

        out("Sending transactionProposal to all peers with arguments: move(a%d,b%d,%d) with b at %d", workerId,
                workerId, delta, start);

        Collection<ProposalResponse> transactionPropResp = channel
                .sendTransactionProposal(transactionProposalRequest, channel.getPeers());
        for (ProposalResponse response : transactionPropResp) {
            if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                out("Successful channel%s worker id %d transaction proposal response Txid: %s from peer %s",
                        channelName, workerId, response.getTransactionID(), response.getPeer().getName());
                successful.add(response);
            } else {
                failed.add(response);
            }
        }

        // Check that all the proposals are consistent with each other. We should have only one set
        // where all the proposals above are consistent. Note the when sending to Orderer this is done automatically.
        //  Shown here as an example that applications can invoke and select.
        // See org.hyperledger.fabric.sdk.proposal.consistency_validation config property.
        Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils
                .getProposalConsistencySets(transactionPropResp);
        if (proposalConsistencySets.size() != 1) {
            fail(format("Expected only one set of consistent proposal responses but got %d",
                    proposalConsistencySets.size()));
        }

        out("Channel %s worker id %d, received %d transaction proposal responses. Successful+verified: %d . Failed: %d",
                channelName, workerId, transactionPropResp.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
            fail("Not enough endorsers for invoke(move a,b,100):" + failed.size() + " endorser error: "
                    + firstTransactionProposalResponse.getMessage() + ". Was verified: "
                    + firstTransactionProposalResponse.isVerified());
        }
        out("Channel %s, worker id %d successfully received transaction proposal responses.", channelName,
                workerId);

        ProposalResponse resp = successful.iterator().next();
        byte[] x = resp.getChaincodeActionResponsePayload(); // This is the data returned by the chaincode.
        String resultAsString = null;
        if (x != null) {
            resultAsString = new String(x, "UTF-8");
        }
        assertEquals(":)", resultAsString);

        assertEquals(200, resp.getChaincodeActionResponseStatus()); //Chaincode's status.

        TxReadWriteSetInfo readWriteSetInfo = resp.getChaincodeActionResponseReadWriteSetInfo();
        //See blockwalker below how to transverse this
        assertNotNull(readWriteSetInfo);
        assertTrue(readWriteSetInfo.getNsRwsetCount() > 0);

        ChaincodeID cid = resp.getChaincodeID();
        assertNotNull(cid);
        final String path = cid.getPath();
        if (null == CHAIN_CODE_PATH) {
            assertTrue(path == null || "".equals(path));

        } else {

            assertEquals(CHAIN_CODE_PATH, path);

        }

        assertEquals(CHAIN_CODE_NAME, cid.getName());
        assertEquals(CHAIN_CODE_VERSION, cid.getVersion());

        ////////////////////////////
        // Send Transaction Transaction to orderer
        out("Sending chaincode transaction(move a%d,b%d,%d) to orderer. with b value %d", workerId, workerId,
                delta, start);

        channel.sendTransaction(successful, user).thenApply(transactionEvent -> {
            try {

                waitOnFabric(0);

                assertTrue(transactionEvent.isValid()); // must be valid to be here.
                out("Channel %s worker id %d Finished transaction with transaction id %s", channelName,
                        workerId, transactionEvent.getTransactionID());
                testTxID = transactionEvent.getTransactionID(); // used in the channel queries later

                ////////////////////////////
                // Send Query Proposal to all peers
                //
                String expect = start + delta + "";
                out("Channel %s Now query chaincode for the value of b%d.", channelName, workerId);
                QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
                queryByChaincodeRequest.setArgs(new String[] { "b" + workerId });
                queryByChaincodeRequest.setFcn("query");
                queryByChaincodeRequest.setChaincodeID(chaincodeID);

                tm2.clear();
                tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
                tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
                queryByChaincodeRequest.setTransientMap(tm2);

                Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest,
                        channel.getPeers());
                for (ProposalResponse proposalResponse : queryProposals) {
                    if (!proposalResponse.isVerified()
                            || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
                        fail("Failed query proposal from peer " + proposalResponse.getPeer().getName()
                                + " status: " + proposalResponse.getStatus() + ". Messages: "
                                + proposalResponse.getMessage() + ". Was verified : "
                                + proposalResponse.isVerified());
                    } else {
                        String payload = proposalResponse.getProposalResponse().getResponse().getPayload()
                                .toStringUtf8();
                        out("Channel %s worker id %d, query payload of b%d from peer %s returned %s and was expecting: %d",
                                channelName, workerId, workerId, proposalResponse.getPeer().getName(), payload,
                                delta + start);
                        assertEquals(expect, payload);
                    }
                }

                return null;
            } catch (Exception e) {
                out("Caught exception while running query");
                e.printStackTrace();
                fail("Failed during chaincode query with error : " + e.getMessage());
            }

            return null;
        }).exceptionally(e -> {
            if (e instanceof TransactionEventException) {
                BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
                if (te != null) {
                    throw new AssertionError(format("Transaction with txid %s failed. %s",
                            te.getTransactionID(), e.getMessage()), e);
                }
            }

            throw new AssertionError(
                    format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()), e);

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

        // Channel queries

        // We can only send channel queries to peers that are in the same org as the SDK user context
        // Get the peers from the current org being used and pick one randomly to send the queries to.
        //  Set<Peer> peerSet = sampleOrg.getPeers();
        //  Peer queryPeer = peerSet.iterator().next();
        //   out("Using peer %s for channel queries", queryPeer.getName());

        final AtomicLong atomicHeight = new AtomicLong(Long.MAX_VALUE);
        final BlockchainInfo[] bcInfoA = new BlockchainInfo[1];

        channel.getPeers().forEach(peer -> {

            try {
                BlockchainInfo channelInfo2 = channel.queryBlockchainInfo(peer, user);
                final long height = channelInfo2.getHeight();
                if (height < atomicHeight.longValue()) {
                    atomicHeight.set(height);
                    bcInfoA[0] = channelInfo2;

                }

            } catch (Exception e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        });

        BlockchainInfo channelInfo = bcInfoA[0];
        out("Channel info for : " + channelName);
        out("Channel height: " + channelInfo.getHeight());
        String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash());
        String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash());
        out("Chain current block hash: " + chainCurrentHash);
        out("Chainl previous block hash: " + chainPreviousHash);
        final long getBlockNumber = atomicHeight.longValue() - 1L;

        // Query by block number. Should return latest block, i.e. block number 2
        BlockInfo returnedBlock = channel.queryBlockByNumber(getBlockNumber, user);
        String previousHash = Hex.encodeHexString(returnedBlock.getPreviousHash());
        out("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber()
                + " \n previous_hash " + previousHash);
        assertEquals(getBlockNumber, returnedBlock.getBlockNumber());
        assertEquals(chainPreviousHash, previousHash);

        returnedBlock.getEnvelopeCount();
        out("Worker: %d, run: %d, channel: %s block transaction count: %d", workerId, runId, channelName,
                returnedBlock.getEnvelopeCount());

        // Query by block hash. Using latest block's previous hash so should return block number 1
        byte[] hashQuery = returnedBlock.getPreviousHash();
        returnedBlock = channel.queryBlockByHash(hashQuery, user);
        out("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber());
        assertEquals(format("query by hash expected block number %d but was %d ", getBlockNumber - 1L,
                returnedBlock.getBlockNumber()), getBlockNumber - 1L, returnedBlock.getBlockNumber());

        // Query block by TxID. Since it's the last TxID, should be block 2
        //TODO RICK         returnedBlock = channel.queryBlockByTransactionID(testTxID);
        //          out("queryBlockByTxID returned block with blockNumber " + returnedBlock.getBlockNumber());
        //         assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber());

        // query transaction by ID
        //         TransactionInfo txInfo = channel.queryTransactionByID(testTxID);
        //            out("QueryTransactionByID returned TransactionInfo: txID " + txInfo.getTransactionID()
        //                    + "\n     validation code " + txInfo.getValidationCode().getNumber());

        //            if (chaincodeEventListenerHandle != null) {
        //
        //                channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
        //                //Should be two. One event in chaincode and two notification for each of the two event hubs
        //
        //                final int numberEventsExpected = channel.getEventHubs().size() +
        //                        channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).size();
        //                //just make sure we get the notifications.
        //                for (int i = 15; i > 0; --i) {
        //                    if (chaincodeEvents.size() == numberEventsExpected) {
        //                        break;
        //                    } else {
        //                        Thread.sleep(90); // wait for the events.
        //                    }
        //
        //                }
        //                assertEquals(numberEventsExpected, chaincodeEvents.size());
        //
        //                for (ChaincodeEventCapture chaincodeEventCapture : chaincodeEvents) {
        //                    assertEquals(chaincodeEventListenerHandle, chaincodeEventCapture.handle);
        //                    assertEquals(testTxID, chaincodeEventCapture.chaincodeEvent.getTxId());
        //                    assertEquals(EXPECTED_EVENT_NAME, chaincodeEventCapture.chaincodeEvent.getEventName());
        //                    assertTrue(Arrays.equals(EXPECTED_EVENT_DATA, chaincodeEventCapture.chaincodeEvent.getPayload()));
        //                    assertEquals(CHAIN_CODE_NAME, chaincodeEventCapture.chaincodeEvent.getChaincodeId());
        //
        //                    BlockEvent blockEvent = chaincodeEventCapture.blockEvent;
        //                    assertEquals(channelName, blockEvent.getChannelId());
        //                    //   assertTrue(channel.getEventHubs().contains(blockEvent.getEventHub()));
        //
        //                }
        //
        //            } else {
        //                assertTrue(chaincodeEvents.isEmpty());
        //            }

        out("Running for Channel %s done", channelName);

    } catch (Exception e) {
        out("Caught an exception running channel %s", channel.getName());
        e.printStackTrace();
        fail("Test failed with error : " + e.getMessage());
    }
}

From source file:org.ms123.common.data.JdoLayerImpl.java

public void populate(SessionContext sessionContext, Map from, Object to, Map hintsMap) {
    PersistenceManager pm = sessionContext.getPM();
    if (hintsMap == null) {
        hintsMap = new HashMap();
    }//w  ww  . j  a  v  a2 s.  com
    Map<String, String> expressions = (Map) hintsMap.get("__expressions");
    if (expressions == null)
        expressions = new HashMap();
    BeanMap beanMap = new BeanMap(to);
    String entityName = m_inflector.getEntityName(to.getClass().getSimpleName());
    debug("populate.from:" + from + ",to:" + to + ",BeanMap:" + beanMap + "/hintsMap:" + hintsMap
            + "/entityName:" + entityName);
    if (from == null) {
        return;
    }
    Map permittedFields = sessionContext.getPermittedFields(entityName, "write");
    Iterator<String> it = from.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        Object oldValue = beanMap.get(key);
        boolean permitted = m_permissionService.hasAdminRole() || "team".equals(entityName)
                || sessionContext.isFieldPermitted(key, entityName, "write");
        if (!key.startsWith("_") && !permitted) {
            debug("---->populate:field(" + key + ") no write permission");
            continue;
        } else {
            debug("++++>populate:field(" + key + ") write permitted");
        }
        String datatype = null;
        String edittype = null;
        if (!key.startsWith("_")) {
            Map config = (Map) permittedFields.get(key);
            if (config != null) {
                datatype = (String) config.get("datatype");
                edittype = (String) config.get("edittype");
            }
        }

        if (key.equals(STATE_FIELD) && !m_permissionService.hasAdminRole()) {
            continue;
        }
        if ("auto".equals(edittype))
            continue;
        String mode = null;
        Map hm = (Map) hintsMap.get(key);
        if (hm != null) {
            Object m = hm.get("mode");
            if (m != null && m instanceof String) {
                mode = (String) m;
            }
            if (mode == null) {
                m = hm.get("useit");
                if (m != null && m instanceof String) {
                    mode = (String) m;
                }
            }
        }
        if (mode == null) {
            mode = "replace";
        }
        Class clazz = beanMap.getType(key);
        debug("\ttype:" + clazz + "(" + key + "=" + from.get(key) + ")");
        if ("_ignore_".equals(from.get(key))) {
            continue;
        }
        if (clazz == null) {
            debug("\t--- Warning property not found:" + key);
        } else if (clazz.equals(java.util.Date.class)) {
            String value = Utils.getString(from.get(key), beanMap.get(key), mode);
            debug("\tDate found:" + key + "=>" + value);
            Date date = null;
            if (value != null) {
                try {
                    Long val = Long.valueOf(value);
                    date = (Date) ConvertUtils.convert(val, Date.class);
                    debug("\tdate1:" + date);
                } catch (Exception e) {
                    try {
                        DateTime dt = new DateTime(value);
                        date = new Date(dt.getMillis());
                        debug("\tdate2:" + date);
                    } catch (Exception e1) {
                        try {
                            int space = value.indexOf(" ");
                            if (space != -1) {
                                value = value.substring(0, space) + "T" + value.substring(space + 1);
                                DateTime dt = new DateTime(value);
                                date = new Date(dt.getMillis());
                            }
                            debug("\tdate3:" + date);
                        } catch (Exception e2) {
                            debug("\terror setting date:" + e);
                        }
                    }
                }
            }
            debug("\tsetting date:" + date);
            beanMap.put(key, date);
        } else if (clazz.equals(java.util.Map.class)) {
            info("!!!!!!!!!!!!!!!!!!!Map not implemented");
        } else if (clazz.equals(java.util.List.class) || clazz.equals(java.util.Set.class)) {
            boolean isList = clazz.equals(java.util.List.class);
            boolean isSimple = false;
            if (datatype != null && datatype.startsWith("list_")) {
                isSimple = true;
            }
            try {
                Class type = TypeUtils.getTypeForField(to, key);
                debug("type:" + type + " fill with: " + from.get(key) + ",list:" + beanMap.get(key) + "/mode:"
                        + mode);
                Collection valList = isList ? new ArrayList() : new HashSet();
                Object fromVal = from.get(key);
                if (fromVal instanceof String && ((String) fromVal).length() > 0) {
                    info("FromVal is StringSchrott, ignore");
                    continue;
                }
                if (from.get(key) instanceof Collection) {
                    valList = (Collection) from.get(key);
                }
                if (valList == null) {
                    valList = isList ? new ArrayList() : new HashSet();
                }
                Collection toList = (Collection) PropertyUtils.getProperty(to, key);
                debug("toList:" + toList);
                debug("valList:" + valList);
                if (toList == null) {
                    toList = isList ? new ArrayList() : new HashSet();
                    PropertyUtils.setProperty(to, key, toList);
                }
                if ("replace".equals(mode)) {
                    boolean isEqual = false;
                    if (isSimple) {
                        isEqual = Utils.isCollectionEqual(toList, valList);
                        if (!isEqual) {
                            toList.clear();
                        }
                        debug("\tisEqual:" + isEqual);
                    } else {
                        List deleteList = new ArrayList();
                        String namespace = sessionContext.getStoreDesc().getNamespace();
                        for (Object o : toList) {
                            if (type.getName().endsWith(".Team")) {
                                int status = m_teamService.getTeamStatus(namespace, new BeanMap(o), null,
                                        sessionContext.getUserName());
                                debug("populate.replace.teamStatus:" + status + "/"
                                        + new HashMap(new BeanMap(o)));
                                if (status != -1) {
                                    pm.deletePersistent(o);
                                    deleteList.add(o);
                                }
                            } else {
                                pm.deletePersistent(o);
                                deleteList.add(o);
                            }
                        }
                        for (Object o : deleteList) {
                            toList.remove(o);
                        }
                    }
                    debug("populate.replace.toList:" + toList + "/" + type.getName());
                    if (isSimple) {
                        if (!isEqual) {
                            for (Object o : valList) {
                                toList.add(o);
                            }
                        }
                    } else {
                        for (Object o : valList) {
                            Map valMap = (Map) o;
                            Object n = type.newInstance();
                            if (type.getName().endsWith(".Team")) {
                                valMap.remove("id");
                                Object desc = valMap.get("description");
                                Object name = valMap.get("name");
                                Object dis = valMap.get("disabled");
                                String teamid = (String) valMap.get("teamid");
                                Object ti = Utils.getTeamintern(sessionContext, teamid);
                                if (desc == null) {
                                    valMap.put("description", PropertyUtils.getProperty(ti, "description"));
                                }
                                if (name == null) {
                                    valMap.put("name", PropertyUtils.getProperty(ti, "name"));
                                }
                                if (dis == null) {
                                    valMap.put("disabled", false);
                                }
                                pm.makePersistent(n);
                                populate(sessionContext, valMap, n, null);
                                PropertyUtils.setProperty(n, "teamintern", ti);
                            } else {
                                pm.makePersistent(n);
                                populate(sessionContext, valMap, n, null);
                            }
                            debug("populated.add:" + new HashMap(new BeanMap(n)));
                            toList.add(n);
                        }
                    }
                } else if ("remove".equals(mode)) {
                    if (isSimple) {
                        for (Object o : valList) {
                            if (toList.contains(o)) {
                                toList.remove(o);
                            }
                        }
                    } else {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map, "teamid");
                            if (o != null) {
                                toList.remove(o);
                                pm.deletePersistent(o);
                            }
                        }
                    }
                } else if ("add".equals(mode)) {
                    if (isSimple) {
                        for (Object o : valList) {
                            toList.add(o);
                        }
                    } else {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map, "teamid");
                            if (o != null) {
                                populate(sessionContext, map, o, null);
                            } else {
                                o = type.newInstance();
                                if (type.getName().endsWith(".Team")) {
                                    Object desc = map.get("description");
                                    Object name = map.get("name");
                                    Object dis = map.get("disabled");
                                    String teamid = (String) map.get("teamid");
                                    Object ti = Utils.getTeamintern(sessionContext, teamid);
                                    if (desc == null) {
                                        map.put("description", PropertyUtils.getProperty(ti, "description"));
                                    }
                                    if (name == null) {
                                        map.put("name", PropertyUtils.getProperty(ti, "name"));
                                    }
                                    if (dis == null) {
                                        map.put("disabled", false);
                                    }

                                    pm.makePersistent(o);
                                    populate(sessionContext, map, o, null);
                                    PropertyUtils.setProperty(o, "teamintern", ti);
                                } else {
                                    pm.makePersistent(o);
                                    populate(sessionContext, map, o, null);
                                }
                                toList.add(o);
                            }
                        }
                    }
                } else if ("assign".equals(mode)) {
                    if (!isSimple) {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map);
                            if (o != null) {
                                debug("id:" + map + " already assigned");
                            } else {
                                Object id = map.get("id");
                                Boolean assign = Utils.getBoolean(map.get("assign"));
                                Object obj = pm.getObjectById(type, id);
                                if (assign) {
                                    toList.add(obj);
                                } else {
                                    toList.remove(obj);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.list.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Boolean.class)) {
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Boolean.class));
            } catch (Exception e) {
                debug("populate.boolean.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Double.class)) {
            String value = Utils.getString(from.get(key), beanMap.get(key), mode);
            try {
                beanMap.put(key, Double.valueOf(value));
            } catch (Exception e) {
                debug("populate.double.failed:" + key + "=>" + value + ";" + e);
            }
        } else if (clazz.equals(java.lang.Long.class)) {
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Long.class));
            } catch (Exception e) {
                debug("populate.long.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Integer.class)) {
            debug("Integer:" + ConvertUtils.convert(from.get(key), Integer.class));
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Integer.class));
            } catch (Exception e) {
                debug("populate.integer.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if ("binary".equals(datatype) || clazz.equals(byte[].class)) {
            InputStream is = null;
            InputStream is2 = null;

            try {
                if (from.get(key) instanceof FileItem) {
                    FileItem fi = (FileItem) from.get(key);
                    String name = fi.getName();
                    byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                    if (bytes != null) {
                        debug("bytes:" + bytes.length);
                    }
                    beanMap.put(key, bytes);
                    is = fi.getInputStream();
                    is2 = fi.getInputStream();
                } else if (from.get(key) instanceof Map) {
                    Map map = (Map) from.get(key);
                    String storeLocation = (String) map.get("storeLocation");
                    is = new FileInputStream(new File(storeLocation));
                    is2 = new FileInputStream(new File(storeLocation));
                    byte[] bytes = IOUtils.toByteArray(is);
                    if (bytes != null) {
                        debug("bytes2:" + bytes.length);
                    }
                    is.close();
                    beanMap.put(key, bytes);
                    is = new FileInputStream(new File(storeLocation));
                } else if (from.get(key) instanceof String) {
                    String value = (String) from.get(key);
                    if ("ignore".equals(value)) {
                        debug("ignore:");
                        return;
                    }
                    if (value.startsWith("data:")) {
                        int ind = value.indexOf(";base64,");
                        byte b[] = Base64.decode(value.substring(ind + 8));
                        beanMap.put(key, b);
                        is = new ByteArrayInputStream(b);
                        is2 = new ByteArrayInputStream(b);
                    } else {
                        byte b[] = value.getBytes();
                        beanMap.put(key, b);
                        is = new ByteArrayInputStream(b);
                        is2 = new ByteArrayInputStream(b);
                    }
                } else {
                    debug("populate.byte[].no a FileItem:" + key + "=>" + from.get(key));
                    continue;
                }
                Tika tika = new Tika();
                TikaInputStream stream = TikaInputStream.get(is);
                TikaInputStream stream2 = TikaInputStream.get(is2);
                String text = tika.parseToString(is);
                debug("Text:" + text);
                try {
                    beanMap.put("text", text);
                } catch (Exception e) {
                    beanMap.put("text", text.getBytes());
                }
                //@@@MS Hardcoded 
                try {
                    Detector detector = new DefaultDetector();
                    MediaType mime = detector.detect(stream2, new Metadata());
                    debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString());
                    beanMap.put("type", mime.toString());
                    from.put("type", mime.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.byte[].failed:" + key + "=>" + from.get(key) + ";" + e);
            } finally {
                try {
                    is.close();
                    is2.close();
                } catch (Exception e) {
                }
            }
        } else {
            boolean ok = false;
            try {
                Class type = TypeUtils.getTypeForField(to, key);
                if (type != null) {
                    Object o = type.newInstance();
                    boolean hasAnn = type.isAnnotationPresent(PersistenceCapable.class);
                    debug("hasAnnotation:" + hasAnn);
                    if (o instanceof javax.jdo.spi.PersistenceCapable || hasAnn) {
                        Object id = null;
                        try {
                            Object _id = from.get(key);
                            if (_id != null) {
                                if (_id instanceof Map) {
                                    id = ((Map) _id).get("id");
                                } else {
                                    String s = String.valueOf(_id);
                                    if (s.indexOf("/") >= 0) {
                                        _id = Utils.extractId(s);
                                    }
                                    Class idClass = PropertyUtils.getPropertyType(o, "id");
                                    id = (idClass.equals(Long.class)) ? Long.valueOf(_id + "") : _id;
                                }
                            }
                        } catch (Exception e) {
                        }
                        if (id != null && !"".equals(id) && !"null".equals(id)) {
                            debug("\tId2:" + id);
                            Object relatedObject = pm.getObjectById(type, id);
                            List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null);
                            if (candidates.size() == 1) {
                                Collection l = candidates.get(0);
                                debug("list.contains:" + l.contains(to));
                                if (!l.contains(to)) {
                                    l.add(to);
                                }
                            }
                            beanMap.put(key, relatedObject);
                        } else {
                            Object relatedObject = beanMap.get(key);
                            debug("\trelatedObject:" + relatedObject);
                            if (relatedObject != null) {
                                List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to,
                                        null);
                                if (candidates.size() == 1) {
                                    Collection l = candidates.get(0);
                                    debug("list.contains:" + l.contains(to));
                                    if (l.contains(to)) {
                                        l.remove(to);
                                    }
                                }
                            }
                            beanMap.put(key, null);
                        }
                        ok = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!ok) {
                String value = Utils.getString(from.get(key), beanMap.get(key), mode);
                // debug("populate:" + key + "=>" + value); 
                // debug("String:" + ConvertUtils.convert(from.get(key), String.class)); 
                try {
                    beanMap.put(key, value);
                } catch (Exception e) {
                    debug("populate.failed:" + key + "=>" + value + ";" + e);
                }
            }
        }
        String expression = expressions.get(key);
        if (!isEmpty(expression)) {
            beanMap.put(key, oldValue);
            Map scriptCache = (Map) sessionContext.getProperty("scriptCache");
            if (scriptCache == null) {
                scriptCache = new HashMap();
                sessionContext.setProperty("scriptCache", scriptCache);
            }
            Object result = Utils.eval(expression, beanMap, scriptCache);
            try {
                if ("string".equals(datatype) && !(result instanceof String)) {
                    beanMap.put(key, ConvertUtils.convert(result, String.class));
                } else {
                    beanMap.put(key, result);
                }
            } catch (Exception e) {
                info("Cannot set value for(" + key + "):" + result + "/" + e.getMessage());
            }
        }
    }
}

From source file:ubic.gemma.loader.expression.arrayDesign.ArrayDesignSequenceProcessingServiceImpl.java

@Override
public Collection<BioSequence> processArrayDesign(ArrayDesign arrayDesign, InputStream sequenceIdentifierFile,
        String[] databaseNames, String blastDbHome, Taxon taxon, boolean force) throws IOException {
    checkForCompositeSequences(arrayDesign);

    Map<String, String> probe2acc = parseAccessionFile(sequenceIdentifierFile);
    Collection<BioSequence> finalResult = new HashSet<BioSequence>();
    Collection<String> notFound = new HashSet<String>();

    // values that were enot found
    notFound.addAll(probe2acc.values());

    // the actual thing values to search for (with version numbers)
    Collection<String> accessionsToFetch = new HashSet<String>();
    accessionsToFetch.addAll(probe2acc.values());

    // only 1 taxon should be on array design if taxon not supplied on command line
    taxon = validateTaxon(taxon, arrayDesign);

    /*//from  w  w  w.  j ava2s  .c o  m
     * Fill in sequences from BLAST databases.
     */
    int versionNumber = 1;
    int numSwitched = 0;
    while (versionNumber < MAX_VERSION_NUMBER) {
        Collection<BioSequence> retrievedSequences = searchBlastDbs(databaseNames, blastDbHome, notFound);

        // map of accessions to sequence.
        Map<String, BioSequence> found = findOrUpdateSequences(accessionsToFetch, retrievedSequences, taxon,
                force);

        finalResult.addAll(retrievedSequences);

        // replace the sequences.
        for (CompositeSequence cs : arrayDesign.getCompositeSequences()) {
            String probeName = cs.getName();
            String acc = probe2acc.get(probeName);
            if (found.containsKey(acc)) {
                numSwitched++;
                log.debug("Setting seq. for " + cs + " to " + found.get(acc));
                cs.setBiologicalCharacteristic(found.get(acc));
            }
        }

        notFound = getUnFound(notFound, found);

        if (notFound.isEmpty()) {
            break; // we're done!
        }

        // bump up the version numbers for ones we haven't found yet.

        for (String accession : notFound) {
            if (log.isTraceEnabled())
                log.trace(accession + " not found, increasing version number to " + versionNumber);
            accessionsToFetch.remove(accession);

            // add or increase the version number.
            accession = accession.replaceFirst("\\.\\d+$", "");
            accession = accession + "." + Integer.toString(versionNumber);
            accessionsToFetch.add(accession);
        }
        notFound = accessionsToFetch;

        ++versionNumber;

    }

    if (!notFound.isEmpty() && taxon != null) {

        Collection<String> stillLooking = new HashSet<String>();
        stillLooking.addAll(notFound);
        notFound.clear();

        /*
         * clear the version number.
         */
        for (String accession : stillLooking) {
            notFound.remove(accession);
            accession = accession.replaceFirst("\\.\\d+$", "");
            notFound.add(accession);
        }
        assert notFound.size() > 0;
        /*
         * See if they're already in Gemma. This is good for sequences that are not in genbank but have been loaded
         * previously.
         */
        Map<String, BioSequence> found = findLocalSequences(notFound, taxon);
        finalResult.addAll(found.values());

        for (CompositeSequence cs : arrayDesign.getCompositeSequences()) {
            String probeName = cs.getName();
            String acc = probe2acc.get(probeName);
            if (found.containsKey(acc)) {
                numSwitched++;
                log.debug("Setting seq. for " + cs + " to " + found.get(acc));
                cs.setBiologicalCharacteristic(found.get(acc));
            }
        }
        notFound = getUnFound(notFound, found);
    }

    if (!notFound.isEmpty()) {
        logMissingSequences(arrayDesign, notFound);
    }

    log.info(numSwitched + " composite sequences had their biologicalCharacteristics changed");

    arrayDesignService.update(arrayDesign);

    arrayDesignReportService.generateArrayDesignReport(arrayDesign.getId());
    return finalResult;

}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.Map.values()'.
 *
 * @see java.util.Map#values()//from   ww  w .  j a v  a 2s  .  c  o m
 */
public void testValues() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();

    map.put(keys[0], values[0]);

    Collection<V> mapValues = map.values();
    assertNotNull(mapValues);
    assertEquals(1, mapValues.size());

    Iterator<V> valueIter = mapValues.iterator();
    assertEquals(values[0], valueIter.next());

    _assertEquals(mapValues, map.values());

    mapValues.clear();
    _assertEmpty(map);

    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    mapValues.iterator();
    assertEquals(map.size(), mapValues.size());
    for (V value : values) {
        assertTrue(mapValues.contains(value));
    }
    assertEquals(values.length, mapValues.size());
    int size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length, size);

    mapValues = map.descendingMap().values();
    mapValues.iterator();
    assertEquals(map.size(), mapValues.size());
    for (V value : values) {
        assertTrue(mapValues.contains(value));
    }
    assertEquals(values.length, mapValues.size());
    size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length, size);

    mapValues = map.values();
    mapValues.remove(values[0]);
    assertTrue(!map.containsValue(values[0]));
    assertEquals(values.length - 1, mapValues.size());
    size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length - 1, size);
}

From source file:ucar.unidata.idv.control.chart.MyXYPlot.java

/**
 * Clears the (foreground and background) range markers for a particular
 * renderer./* w  ww  .  ja va2  s .c om*/
 *
 * @param index  the renderer index.
 */
public void clearRangeMarkers(int index) {
    Integer key = new Integer(index);
    if (this.backgroundRangeMarkers != null) {
        Collection markers = (Collection) this.backgroundRangeMarkers.get(key);
        if (markers != null) {
            markers.clear();
        }
    }
    if (this.foregroundRangeMarkers != null) {
        Collection markers = (Collection) this.foregroundRangeMarkers.get(key);
        if (markers != null) {
            markers.clear();
        }
    }
    notifyListeners(new PlotChangeEvent(this));
}

From source file:ucar.unidata.idv.control.chart.MyXYPlot.java

/**
 * Clears the (foreground and background) domain markers for a particular
 * renderer./*from   w  w  w. j av a2s.co m*/
 *
 * @param index  the renderer index.
 */
public void clearDomainMarkers(int index) {
    Integer key = new Integer(index);
    if (this.backgroundDomainMarkers != null) {
        Collection markers = (Collection) this.backgroundDomainMarkers.get(key);
        if (markers != null) {
            markers.clear();
        }
    }
    if (this.foregroundRangeMarkers != null) {
        Collection markers = (Collection) this.foregroundDomainMarkers.get(key);
        if (markers != null) {
            markers.clear();
        }
    }
    notifyListeners(new PlotChangeEvent(this));
}

From source file:org.castor.cpa.test.test88.TestLazyLoading.java

public void testIterWithAdd() throws PersistenceException {
    LOG.info("Running testIterWithAdd...");

    // Tests iterating over a lazy-loaded Collection that has
    // had data added

    ArrayList<LazyAddress> masterData = new ArrayList<LazyAddress>();
    Identity fullname = new Identity("First", "Person");
    LazyPerson loadPerson;//from   ww  w .  j a va2  s  .  com

    // test java.util.Collection.clear() for lazy loading (bug 801)
    _db.begin();
    loadPerson = _db.load(LazyEmployee.class, fullname);

    Collection<LazyAddress> addresses = loadPerson.getAddress();
    // Store the list in the database at the start of the transaction,
    // for comparison purposes
    Iterator<LazyAddress> it = addresses.iterator();
    while (it.hasNext()) {
        masterData.add(it.next());
    }

    _db.rollback();

    // Now start over, and add something to the collection. Then try
    // iterating and clearing the collection
    _db.begin();
    loadPerson = _db.load(LazyEmployee.class, fullname);
    addresses = loadPerson.getAddress();
    LazyAddress la = new LazyAddress();
    la.setId(999);
    la.setStreet("Rogue Street");
    la.setCity("Rogue City");
    la.setState("RS");
    la.setZip("10666");
    la.setPerson(loadPerson);
    addresses.add(la);

    LOG.debug("masterData size: " + masterData.size());
    LOG.debug("addresses size: " + addresses.size());
    if (addresses.size() != (masterData.size() + 1)) {
        fail("Lazy collection size is different from what is expected");
    }

    boolean matchNewElement = false;
    int matchCount = 0;
    it = addresses.iterator();

    /*
     * The problem with the following block is that the second loop is
     * entered but never exited.
     */

    bigloop: while (it.hasNext()) {
        LazyAddress addr1 = it.next();

        Iterator<LazyAddress> it2 = masterData.iterator();
        while (it2.hasNext()) {
            LazyAddress addr2 = it2.next();

            LOG.debug("addr1: " + addr1);
            LOG.debug("addr2: " + addr2);

            if (addr2.equals(addr1)) {
                LOG.debug("matched");
                matchCount++;
                continue bigloop;
            } else if (addr1 == la) {
                LOG.debug("matched lazy");
                matchNewElement = true;
                matchCount++;
                continue bigloop;
            } else {
                LOG.debug("no match");
            }
        }
        LOG.debug("newly added:" + la + "@" + System.identityHashCode(la));
        LOG.debug("matchNewElement " + matchNewElement);
        LOG.debug("matchCount " + matchCount);

        LOG.error("Error: found unexpected address in the new lazy collection");
        fail("found unexpected address in the new lazy collection:" + addr1 + "@"
                + System.identityHashCode(la));
    }

    if (!matchNewElement) {
        LOG.error("Error: Newly added element is missing");
        fail("Newly added element is missing");
    }

    if (matchCount != (masterData.size() + 1)) {
        LOG.error("Error: Lazy collection contains unexpected number of elements");
        fail("Lazy collection contains unexpected number of elements. expected: " + (masterData.size() + 1)
                + " found: " + matchCount);
    }

    addresses.clear();
    if (!addresses.isEmpty()) {
        LOG.error("Error: clear failed in testIterWithAdd");
        fail("Error: clear failed in testIterWithAdd");
    }

    _db.rollback();
}

From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java

CompletableFuture<BlockEvent.TransactionEvent> installInstantiate(Channel channel, HFClient client,
        SampleOrg sampleOrg) throws Exception {

    client.setUserContext(sampleOrg.getPeerAdmin());

    out("Creating install proposal");

    ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
            .setVersion(CHAIN_CODE_VERSION);
    if (null != CHAIN_CODE_PATH) {
        chaincodeIDBuilder.setPath(CHAIN_CODE_PATH);

    }/*w w w.j av a2 s .  c  o m*/
    ChaincodeID chaincodeID = chaincodeIDBuilder.build();

    InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
    installProposalRequest.setChaincodeID(chaincodeID);

    ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
    installProposalRequest
            .setChaincodeSourceLocation(Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile());

    installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION);
    installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);

    out("Sending install proposal");

    ////////////////////////////
    // only a client from the same org as the peer can issue an install request
    int numInstallProposal = 0;
    //    Set<String> orgs = orgPeers.keySet();
    //   for (SampleOrg org : testSampleOrgs) {

    Collection<Peer> peers = channel.getPeers();
    numInstallProposal = numInstallProposal + peers.size();
    Collection<ProposalResponse> responses = client.sendInstallProposal(installProposalRequest, peers);

    Collection<ProposalResponse> successful = new LinkedList<>();
    Collection<ProposalResponse> failed = new LinkedList<>();

    for (ProposalResponse response : responses) {
        if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
            out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(),
                    response.getPeer().getName());
            successful.add(response);
        } else {
            failed.add(response);
        }
    }

    //   }
    out("Received %d install proposal responses. Successful+verified: %d . Failed: %d", numInstallProposal,
            successful.size(), failed.size());

    if (failed.size() > 0) {
        ProposalResponse first = failed.iterator().next();
        fail("Not enough endorsers for install :" + successful.size() + ".  " + first.getMessage());
    }

    //   client.setUserContext(sampleOrg.getUser(TEST_ADMIN_NAME));
    //  final ChaincodeID chaincodeID = firstInstallProposalResponse.getChaincodeID();
    // Note installing chaincode does not require transaction no need to
    // send to Orderers

    ///////////////
    //// Instantiate chaincode.
    InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
    instantiateProposalRequest.setProposalWaitTime(DEPLOYWAITTIME);
    instantiateProposalRequest.setChaincodeID(chaincodeID);
    instantiateProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
    instantiateProposalRequest.setFcn("init");
    instantiateProposalRequest.setArgs(new String[] { "a", "500000000", "b", "" + 200 });
    Map<String, byte[]> tm = new HashMap<>();
    tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
    tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
    instantiateProposalRequest.setTransientMap(tm);

    /*
      policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2
      See README.md Chaincode endorsement policies section for more details.
    */
    ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
    chaincodeEndorsementPolicy
            .fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
    instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);

    out("Sending instantiateProposalRequest to all peers with arguments: a and b set to 100 and %s respectively",
            "" + 200);
    successful.clear();
    failed.clear();

    responses = channel.sendInstantiationProposal(instantiateProposalRequest);

    for (ProposalResponse response : responses) {
        if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
            successful.add(response);
            out("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(),
                    response.getPeer().getName());
        } else {
            failed.add(response);
        }
    }
    out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(),
            successful.size(), failed.size());
    if (failed.size() > 0) {
        for (ProposalResponse fail : failed) {

            out("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with "
                    + fail.getMessage() + ", on peer" + fail.getPeer());

        }
        ProposalResponse first = failed.iterator().next();
        fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with "
                + first.getMessage() + ". Was verified:" + first.isVerified());
    }

    ///////////////
    /// Send instantiate transaction to orderer
    out("Sending instantiateTransaction to orderer with a and b set to 100 and %s respectively", "" + 200);

    //Specify what events should complete the interest in this transaction. This is the default
    // for all to complete. It's possible to specify many different combinations like
    //any from a group, all from one group and just one from another or even None(NOfEvents.createNoEvents).
    // See. Channel.NOfEvents
    Channel.NOfEvents nOfEvents = createNofEvents();
    if (!channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).isEmpty()) {
        nOfEvents.addPeers(channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)));
    }
    if (!channel.getEventHubs().isEmpty()) {
        nOfEvents.addEventHubs(channel.getEventHubs());
    }

    return channel.sendTransaction(successful, createTransactionOptions() //Basically the default options but shows it's usage.
            .userContext(client.getUserContext()) //could be a different user context. this is the default.
            .shuffleOrders(false) // don't shuffle any orderers the default is true.
            .orderers(channel.getOrderers()) // specify the orderers we want to try this transaction. Fails once all Orderers are tried.
            .nOfEvents(nOfEvents) // The events to signal the completion of the interest in the transaction
    );
}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

private void importRealms(org.w3c.dom.Document doc, Integer siteId, boolean useNewIDs) {
    if (log.isDebugEnabled())
        log.debug("start importRealms with useNewIDs=" + useNewIDs);
    mappingRealmsSimplePw = new Hashtable<Integer, Integer>();
    mappingRealmsJdbc = new Hashtable<Integer, Integer>();
    mappingRealmsLdap = new Hashtable<Integer, Integer>();
    mappingRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealmsSimplePw = new Hashtable<Integer, Integer>();
    loginPagesRealmsJdbc = new Hashtable<Integer, Integer>();
    loginPagesRealmsLdap = new Hashtable<Integer, Integer>();
    loginPagesRealmsJaas = new Hashtable<Integer, Integer>();
    loginPagesRealm2vc = new Hashtable<Integer, Integer>();
    try {/*  w w w  .  java2  s .  co m*/
        if (XercesHelper.findNode(doc, "/edition/realms") != null) {
            SiteHbm site = getSiteHbmDao().load(siteId);
            Iterator itRealms = XercesHelper.findNodes(doc, "/edition/realms/realmsSimplePw/realmSimplePw");
            while (itRealms.hasNext()) {
                if (log.isDebugEnabled())
                    log.debug("Found RealmSimplePw to import...");
                Element elmRealm = (Element) itRealms.next();
                Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "simplePwRealmId"));
                RealmSimplePwHbm realm = null;
                if (useNewIDs) {
                    realm = getRealmSimplePwHbmDao().create(elmRealm, true);
                    realm.setSite(site);
                    mappingRealmsSimplePw.put(id, realm.getSimplePwRealmId()); // mapping OLD-ID to NEW-ID
                } else {
                    try {
                        if (log.isDebugEnabled())
                            log.debug("searching RealmSimplePw: " + id);
                        realm = getRealmSimplePwHbmDao().load(id);
                        String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                        if (realmName != null && realmName.length() > 0) {
                            realm.setRealmName(realmName);
                        } else {
                            realm.setRealmName(null);
                        }
                        realm.setSite(site);
                        {
                            // import users, first delete all existing ones for this realm
                            Collection toDelete = new ArrayList();
                            toDelete.addAll(realm.getSimplePwRealmUsers());
                            Iterator it = toDelete.iterator();
                            while (it.hasNext()) {
                                getRealmSimplePwUserHbmDao().remove(((RealmSimplePwUserHbm) it.next()));
                            }
                            toDelete.clear();
                            realm.getSimplePwRealmUsers().clear();
                            Iterator itUsers = XercesHelper.findNodes(elmRealm,
                                    "simplePwRealmUsers/realmSimplePwUser");
                            while (itUsers.hasNext()) {
                                Element elmUser = (Element) itUsers.next();
                                RealmSimplePwUserHbm user = ((RealmSimplePwUserHbmDaoImpl) getRealmSimplePwUserHbmDao())
                                        .create(elmUser, false);
                                user.setSimplePwRealm(realm);
                                realm.getSimplePwRealmUsers().add(user);
                            }
                        }
                    } catch (Exception exe) {
                        if (log.isDebugEnabled())
                            log.debug("creating RealmSimplePw: " + id);
                        realm = getRealmSimplePwHbmDao().create(elmRealm, false);
                        realm.setSite(site);
                    }
                }
                String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
                if (loginPageId != null && loginPageId.length() > 0)
                    loginPagesRealmsSimplePw.put(id, new Integer(loginPageId));
            }
            itRealms = XercesHelper.findNodes(doc, "/edition/realms/realmsLdap/realmLdap");
            while (itRealms.hasNext()) {
                if (log.isDebugEnabled())
                    log.debug("Found RealmLdap to import...");
                Element elmRealm = (Element) itRealms.next();
                Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "ldapRealmId"));
                RealmLdapHbm realm = null;
                if (useNewIDs) {
                    realm = getRealmLdapHbmDao().create(elmRealm, true);
                    realm.setSite(site);
                    mappingRealmsLdap.put(id, realm.getLdapRealmId()); // mapping OLD-ID to NEW-ID
                } else {
                    try {
                        if (log.isDebugEnabled())
                            log.debug("searching RealmLdap: " + id);
                        realm = getRealmLdapHbmDao().load(id);
                        String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                        if (realmName != null && realmName.length() > 0) {
                            realm.setRealmName(realmName);
                        } else {
                            realm.setRealmName(null);
                        }
                        String ldapPrefix = XercesHelper.getNodeValue(elmRealm, "ldapPrefix");
                        realm.setLdapPrefix(ldapPrefix);
                        String ldapSuffix = XercesHelper.getNodeValue(elmRealm, "ldapSuffix");
                        realm.setLdapSuffix(ldapSuffix);
                        String ldapUrl = XercesHelper.getNodeValue(elmRealm, "ldapUrl");
                        realm.setLdapUrl(ldapUrl);
                        String ldapAuthenticationType = XercesHelper.getNodeValue(elmRealm,
                                "ldapAuthenticationType");
                        realm.setLdapAuthenticationType(ldapAuthenticationType);
                        realm.setSite(site);
                    } catch (Exception exe) {
                        if (log.isDebugEnabled())
                            log.debug("creating RealmLdap: " + id);
                        realm = getRealmLdapHbmDao().create(elmRealm, false);
                        realm.setSite(site);
                    }
                }
                String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
                if (loginPageId != null && loginPageId.length() > 0)
                    loginPagesRealmsLdap.put(id, new Integer(loginPageId));
            }
            itRealms = XercesHelper.findNodes(doc, "/edition/realms/realmsJdbc/realmJdbc");
            while (itRealms.hasNext()) {
                if (log.isDebugEnabled())
                    log.debug("Found RealmJdbc to import...");
                Element elmRealm = (Element) itRealms.next();
                Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "jdbcRealmId"));
                RealmJdbcHbm realm = null;
                if (useNewIDs) {
                    realm = getRealmJdbcHbmDao().create(elmRealm, true);
                    realm.setSite(site);
                    mappingRealmsJdbc.put(id, realm.getJdbcRealmId()); // mapping OLD-ID to NEW-ID
                } else {
                    try {
                        if (log.isDebugEnabled())
                            log.debug("searching RealmJdbc: " + id);
                        realm = getRealmJdbcHbmDao().load(id);
                        String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                        if (realmName != null && realmName.length() > 0) {
                            realm.setRealmName(realmName);
                        } else {
                            realm.setRealmName(null);
                        }
                        String jndiName = XercesHelper.getNodeValue(elmRealm, "jndiName");
                        realm.setJndiName(jndiName);
                        String statementUser = XercesHelper.getNodeValue(elmRealm, "statementUser");
                        realm.setStatementUser(statementUser);
                        String statementRolePerUser = XercesHelper.getNodeValue(elmRealm,
                                "statementRolePerUser");
                        realm.setStatementRolePerUser(statementRolePerUser);
                        realm.setSite(site);
                    } catch (Exception exe) {
                        if (log.isDebugEnabled())
                            log.debug("creating RealmJdbc: " + id);
                        realm = getRealmJdbcHbmDao().create(elmRealm, false);
                        realm.setSite(site);
                    }
                }
                String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
                if (loginPageId != null && loginPageId.length() > 0)
                    loginPagesRealmsJdbc.put(id, new Integer(loginPageId));
            }
            itRealms = XercesHelper.findNodes(doc, "/edition/realms/realmsJaas/realmJaas");
            while (itRealms.hasNext()) {
                if (log.isDebugEnabled())
                    log.debug("Found RealmJaas to import...");
                Element elmRealm = (Element) itRealms.next();
                Integer id = new Integer(XercesHelper.getNodeValue(elmRealm, "jaasRealmId"));
                RealmJaasHbm realm = null;
                if (useNewIDs) {
                    realm = getRealmJaasHbmDao().create(elmRealm, true);
                    realm.setSite(site);
                    mappingRealmsJaas.put(id, realm.getJaasRealmId()); // mapping OLD-ID to NEW-ID
                } else {
                    try {
                        if (log.isDebugEnabled())
                            log.debug("searching RealmJaas: " + id);
                        realm = getRealmJaasHbmDao().load(id);
                        String realmName = XercesHelper.getNodeValue(elmRealm, "realmName");
                        if (realmName != null && realmName.length() > 0) {
                            realm.setRealmName(realmName);
                        } else {
                            realm.setRealmName(null);
                        }
                        String jaasPolicyName = XercesHelper.getNodeValue(elmRealm, "jaasPolicyName");
                        realm.setJaasPolicyName(jaasPolicyName);
                        realm.setSite(site);
                    } catch (Exception exe) {
                        if (log.isDebugEnabled())
                            log.debug("creating RealmJaas: " + id);
                        realm = getRealmJaasHbmDao().create(elmRealm, false);
                        realm.setSite(site);
                    }
                }
                String loginPageId = XercesHelper.getNodeValue(elmRealm, "loginPageId");
                if (loginPageId != null && loginPageId.length() > 0)
                    loginPagesRealmsJaas.put(id, new Integer(loginPageId));
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("importRealms reports: There are no /edition/realms nodes, so nothing to do");
        }
    } catch (Exception exe) {
        log.error("Error occured importRealms: " + exe.getMessage(), exe);
    }
}