Example usage for java.util Collection forEach

List of usage examples for java.util Collection forEach

Introduction

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

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:com.wasteofplastic.askyblock.commands.IslandCmd.java

/**
 * Removes a player from a team run by teamleader
 * /*from w  ww  .  ja v a  2s .  c om*/
 * @param playerUUID
 * @param teamLeader
 */
public void removePlayerFromTeam(final UUID playerUUID, final UUID teamLeader) {
    // Remove player from the team
    plugin.getPlayers().removeMember(teamLeader, playerUUID);
    // If player is online
    // If player is not the leader of their own team
    if (!playerUUID.equals(teamLeader)) {
        plugin.getPlayers().setLeaveTeam(playerUUID);
        //plugin.getPlayers().setHomeLocation(player, null);
        plugin.getPlayers().clearHomeLocations(playerUUID);
        plugin.getPlayers().setIslandLocation(playerUUID, null);
        plugin.getPlayers().setTeamIslandLocation(playerUUID, null);
        OfflinePlayer offlinePlayer = plugin.getServer().getOfflinePlayer(playerUUID);
        if (offlinePlayer.isOnline()) {
            // Check perms
            if (!((Player) offlinePlayer).hasPermission(Settings.PERMPREFIX + "command.leaveexempt")) {
                runCommands(Settings.leaveCommands, offlinePlayer);
            }
        } else {
            // If offline, all commands are run, sorry
            runCommands(Settings.leaveCommands, offlinePlayer);
        }
        // Fire event
        final Collection<Island> islands = plugin.getGrid().getOwnedIslands().get(offlinePlayer.getUniqueId());
        islands.forEach((island) -> {
            final IslandLeaveEvent event = new IslandLeaveEvent(playerUUID, island);
            plugin.getServer().getPluginManager().callEvent(event);
        });
    } else {
        // Ex-Leaders keeps their island, but the rest of the team items are
        // removed
        plugin.getPlayers().setLeaveTeam(playerUUID);
    }

}

From source file:com.confighub.core.store.Store.java

public List<PropertyKey> getKeys(final UserAccount user, final Repository repository,
        final Collection<String> keys, final Date time) throws ConfigException {
    if (Utils.anyNull(repository, keys)) {
        throw new ConfigException(Error.Code.MISSING_PARAMS);
    }/*from www  .  j a  v  a  2 s.c  om*/

    if (!repository.hasReadAccess(user)) {
        throw new ConfigException(Error.Code.USER_ACCESS_DENIED);
    }

    if (null == time) {
        Collection<String> upperKeys = new ArrayList<>();
        keys.forEach(k -> upperKeys.add(k.toUpperCase()));

        try {
            return em.createNamedQuery("Key.getKeys").setLockMode(LockModeType.NONE)
                    .setParameter("repository", repository).setParameter("keys", upperKeys).getResultList();
        } catch (NoResultException e) {
            return Collections.EMPTY_LIST;
        } catch (Exception e) {
            handleException(e);
            return Collections.EMPTY_LIST;
        }
    }

    AuditReader reader = AuditReaderFactory.get(em);
    Number rev = reader.getRevisionNumberForDate(time);

    AuditQuery query = reader.createQuery().forEntitiesAtRevision(PropertyKey.class, rev);
    query.add(AuditEntity.property("repository").eq(repository));
    query.add(AuditEntity.property("key").in(keys));

    try {
        return query.getResultList();
    } catch (NoResultException e) {
        return null;
    } catch (Exception e) {
        handleException(e);
        return null;
    }
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

private List<User> getSelectedGroupUsers(String allOrOneGroup, String contextString, Assignment a,
        List allowAddSubmissionUsers) {
    Collection<String> authzRefs = new ArrayList<>();

    List<User> selectedGroupUsers = new ArrayList<>();
    if (StringUtils.isNotBlank(allOrOneGroup)) {
        // now are we view all sections/groups or just specific one?
        if (allOrOneGroup.equals(AssignmentConstants.ALL)) {
            if (allowAllGroups(contextString)) {
                // site range
                try {
                    Site site = siteService.getSite(contextString);
                    authzRefs.add(site.getReference());
                } catch (IdUnusedException e) {
                    log.warn("Cannot find site {} {}", contextString, e.getMessage());
                }/*from w  ww  . j  a v  a  2  s . c  o  m*/
            } else {
                // get all those groups that user is allowed to grade
                Collection<Group> groups = getGroupsAllowGradeAssignment(
                        AssignmentReferenceReckoner.reckoner().assignment(a).reckon().getReference());
                groups.forEach(g -> authzRefs.add(g.getReference()));
            }
        } else {
            // filter out only those submissions from the selected-group members
            try {
                Group group = siteService.getSite(contextString).getGroup(allOrOneGroup);
                authzRefs.add(group.getReference());
            } catch (IdUnusedException e) {
                log.warn("Cannot add groupId = {}, {}", allOrOneGroup, e.getMessage());
            }
        }

        for (String ref : authzRefs) {
            try {
                AuthzGroup group = authzGroupService.getAuthzGroup(ref);
                for (String userId : group.getUsers()) {
                    // don't show user multiple times
                    try {
                        User u = userDirectoryService.getUser(userId);
                        if (u != null && allowAddSubmissionUsers.contains(u)) {
                            if (!selectedGroupUsers.contains(u)) {
                                selectedGroupUsers.add(u);
                            }
                        }
                    } catch (UserNotDefinedException uException) {
                        log.warn("User not found with id = {}, {}", userId, uException.getMessage());
                    }
                }
            } catch (GroupNotDefinedException gException) {
                log.warn("Group not found with reference = {}, {}", ref, gException.getMessage());
            }
        }
    }
    return selectedGroupUsers;
}

From source file:org.diorite.impl.inventory.recipe.craft.ShapelessCraftingRecipeImpl.java

@Override
public CraftingRecipeCheckResult isMatching(final GridInventory inventory) {
    final Player player = (inventory.getHolder() instanceof Player) ? (Player) inventory.getHolder() : null;
    final Short2ObjectMap<ItemStack> onCraft = new Short2ObjectOpenHashMap<>(2, .5F);

    final int maxInvRow = inventory.getRows(), maxInvCol = inventory.getColumns();
    final LinkedList<CraftingRecipeItem> ingredients = new LinkedList<>(this.getIngredients());
    final Collection<CraftingRepeatableRecipeItem> repeatableIngredients = new LinkedList<>(
            this.getRepeatableIngredients());
    final Collection<BiConsumer<Player, CraftingGrid>> reps = new ArrayList<>(maxInvCol * maxInvRow);
    final CraftingGrid items = new CraftingGridImpl(maxInvRow, maxInvCol);
    int col = -1, row = 0;
    ItemStack result;//from   w  ww . jav a2  s  .c  o  m
    if (this.repeatableIngredients.isEmpty()) {
        for (short i = 1, size = (short) inventory.size(); i < size; i++) {
            if (++col >= maxInvCol) {
                col = 0;
                if (++row > maxInvRow) {
                    throw new IllegalStateException("Inventory is larger than excepted.");
                }
            }
            final ItemStack item = inventory.getItem(i);
            if (item == null) {
                continue;
            }
            boolean matching = false;
            //noinspection Duplicates
            for (final Iterator<CraftingRecipeItem> iterator = ingredients.iterator(); iterator.hasNext();) {
                final CraftingRecipeItem ingredient = iterator.next();
                final ItemStack valid = ingredient.isValid(player, item);
                if (valid != null) {
                    final short icpy = i;
                    reps.add((p, c) -> {
                        final ItemStack repl = ingredient.getReplacement(p, c);
                        if (repl != null) {
                            onCraft.put(icpy, repl);
                        }
                    });
                    items.setItem(row, col, valid);
                    iterator.remove();
                    matching = true;
                    break;
                }
            }
            if (!matching) {
                return null;
            }
        }
        result = (this.resultFunc == null) ? this.result : this.resultFunc.apply(player, items.clone());
    } else {
        final Map<CraftingRepeatableRecipeItem, List<ItemStack>> repeatableItems = new IdentityHashMap<>(
                this.repeatableIngredients.size());
        for (short i = 1, size = (short) inventory.size(); i < size; i++) {
            if (++col >= maxInvCol) {
                col = 0;
                if (++row > maxInvRow) {
                    throw new IllegalStateException("Inventory is larger than excepted.");
                }
            }
            final ItemStack item = inventory.getItem(i);
            if (item == null) {
                continue;
            }
            boolean matching = false;
            if (!ingredients.isEmpty()) {
                //noinspection Duplicates
                for (final Iterator<CraftingRecipeItem> iterator = ingredients.iterator(); iterator
                        .hasNext();) {
                    final CraftingRecipeItem ingredient = iterator.next();
                    final ItemStack valid = ingredient.isValid(player, item);
                    if (valid != null) {
                        final short icpy = i;
                        reps.add((p, c) -> {
                            final ItemStack repl = ingredient.getReplacement(p, c);
                            if (repl != null) {
                                onCraft.put(icpy, repl);
                            }
                        });
                        items.setItem(row, col, valid);
                        iterator.remove();
                        matching = true;
                        break;
                    }
                }
            }
            if (!matching) {
                for (final CraftingRepeatableRecipeItem ingredient : this.repeatableIngredients) {
                    final ItemStack valid = ingredient.isValid(player, item);
                    if (valid != null) {
                        final short icpy = i;
                        reps.add((p, c) -> {
                            final ItemStack repl = ingredient.getReplacement(p, c);
                            if (repl != null) {
                                onCraft.put(icpy, repl);
                            }
                        });
                        List<ItemStack> repItems = repeatableItems.get(ingredient);
                        if (repItems == null) {
                            repeatableIngredients.remove(ingredient);
                            repItems = new ArrayList<>(10);
                            repeatableItems.put(ingredient, repItems);
                        }
                        repItems.add(valid);
                        items.setItem(row, col, valid);
                        matching = true;
                        break;
                    }
                }
            }
            if (!matching) {
                return null;
            }
        }
        if (!repeatableIngredients.isEmpty()) {
            return null;
        }
        result = (this.resultFunc == null) ? this.result : this.resultFunc.apply(player, items.clone());
        for (final Entry<CraftingRepeatableRecipeItem, List<ItemStack>> entry : repeatableItems.entrySet()) {
            result = entry.getKey().transform(result, entry.getValue());
            result = entry.getKey().transform(result, items);
        }
    }
    reps.forEach(c -> c.accept(player, items));
    return ingredients.isEmpty() ? new CraftingRecipeCheckResultImpl(this, result, items, onCraft) : null;
}

From source file:org.hyperledger.fabric.sdk.Channel.java

/**
 * Send a transaction  proposal./*ww  w .  j av  a2 s . com*/
 *
 * @param transactionProposalRequest The transaction proposal to be sent to all the required peers needed for endorsing.
 * @param discoveryOptions
 * @return responses from peers.
 * @throws InvalidArgumentException
 * @throws ProposalException
 */
public Collection<ProposalResponse> sendTransactionProposalToEndorsers(
        TransactionProposalRequest transactionProposalRequest, DiscoveryOptions discoveryOptions)
        throws ProposalException, InvalidArgumentException, ServiceDiscoveryException {
    final String chaincodeName = transactionProposalRequest.getChaincodeID().getName();
    checkChannelState();
    if (null == transactionProposalRequest) {
        throw new InvalidArgumentException("The proposalRequest is null");
    }
    if (isNullOrEmpty(transactionProposalRequest.getFcn())) {
        throw new InvalidArgumentException("The proposalRequest's fcn is null or empty.");
    }
    if (transactionProposalRequest.getChaincodeID() == null) {
        throw new InvalidArgumentException("The proposalRequest's chaincode ID is null");
    }
    logger.debug(
            format("Channel %s sendTransactionProposalToEndorsers chaincode name: %s", name, chaincodeName));

    TransactionContext transactionContext = getTransactionContext(transactionProposalRequest.getUserContext());
    transactionContext.verify(transactionProposalRequest.doVerify());
    transactionContext.setProposalWaitTime(transactionProposalRequest.getProposalWaitTime());

    // Protobuf message builder
    ProposalBuilder proposalBuilder = ProposalBuilder.newBuilder();
    proposalBuilder.context(transactionContext);
    proposalBuilder.request(transactionProposalRequest);

    SignedProposal invokeProposal = null;
    try {
        invokeProposal = getSignedProposal(transactionContext, proposalBuilder.build());
    } catch (CryptoException e) {
        throw new InvalidArgumentException(e);
    }
    SDChaindcode sdChaindcode;
    final List<ServiceDiscoveryChaincodeCalls> serviceDiscoveryChaincodeInterests = discoveryOptions
            .getServiceDiscoveryChaincodeInterests();

    if (null != serviceDiscoveryChaincodeInterests && !serviceDiscoveryChaincodeInterests.isEmpty()) {
        final String firstname = serviceDiscoveryChaincodeInterests.get(0).getName();
        if (!firstname.equals(chaincodeName)) {
            serviceDiscoveryChaincodeInterests.add(0, new ServiceDiscoveryChaincodeCalls(chaincodeName));
        }
        List<List<ServiceDiscoveryChaincodeCalls>> ccl = new LinkedList<>();
        ccl.add(serviceDiscoveryChaincodeInterests);
        final Map<String, SDChaindcode> sdChaindcodeMap = serviceDiscovery
                .discoverEndorserEndpoints(transactionContext, ccl);
        if (sdChaindcodeMap == null) {
            throw new ServiceDiscoveryException(
                    format("Channel %s failed doing service discovery for chaincode %s ", name, chaincodeName));
        }
        sdChaindcode = sdChaindcodeMap.get(chaincodeName);

    } else {
        if (discoveryOptions.forceDiscovery) {
            logger.trace("Forcing discovery.");
            serviceDiscovery.networkDiscovery(transactionContext, true);
        }
        sdChaindcode = serviceDiscovery.discoverEndorserEndpoint(transactionContext, chaincodeName);
    }
    logger.trace(format("Channel %s chaincode %s discovered: %s", name, chaincodeName, "" + sdChaindcode));

    if (null == sdChaindcode) {
        throw new ServiceDiscoveryException(
                format("Channel %s failed to find and endorsers for chaincode %s", name, chaincodeName));
    }

    if (sdChaindcode.getLayouts() == null || sdChaindcode.getLayouts().isEmpty()) {
        throw new ServiceDiscoveryException(
                format("Channel %s failed to find and endorsers for chaincode %s no layouts found.", name,
                        chaincodeName));
    }

    SDChaindcode sdChaindcodeEndorsementCopy = new SDChaindcode(sdChaindcode); //copy. no ignored.

    final boolean inspectResults = discoveryOptions.inspectResults;

    if (sdChaindcodeEndorsementCopy.ignoreList(discoveryOptions.getIgnoreList()) < 1) { // apply ignore list
        throw new ServiceDiscoveryException("Applying ignore list reduced to no available endorser options.");
    }

    if (IS_TRACE_LEVEL && null != discoveryOptions.getIgnoreList()
            && !discoveryOptions.getIgnoreList().isEmpty()) {
        logger.trace(format("SDchaincode after ignore list: %s", sdChaindcodeEndorsementCopy));
    }
    final ServiceDiscovery.EndorsementSelector lendorsementSelector = discoveryOptions.endorsementSelector != null
            ? discoveryOptions.endorsementSelector
            : this.endorsementSelector;
    try {

        final Map<SDEndorser, ProposalResponse> goodResponses = new HashMap<>(); // all good endorsements by endpoint
        final Map<SDEndorser, ProposalResponse> allTried = new HashMap<>(); // all tried by endpoint

        boolean done = false;
        int attempts = 1; //safety valve

        do {
            if (IS_TRACE_LEVEL) {
                logger.trace(format("Attempts: %d,  chaincode discovery state: %s", attempts,
                        sdChaindcodeEndorsementCopy));
            }
            final SDEndorserState sdEndorserState = lendorsementSelector
                    .endorserSelector(sdChaindcodeEndorsementCopy);

            if (IS_TRACE_LEVEL) {

                StringBuilder sb = new StringBuilder(1000);
                String sep = "";
                for (SDEndorser sdEndorser : sdEndorserState.getSdEndorsers()) {
                    sb.append(sep).append(sdEndorser);
                    sep = ", ";
                }

                logger.trace(format(
                        "Attempts: %d,  chaincode discovery state: %s. Endorser selector picked: %s. With selected endorsers: %s",
                        attempts, sdChaindcodeEndorsementCopy.name, sdEndorserState.getPickedLayout(),
                        sb.toString()));

            }

            Collection<SDEndorser> ep = sdEndorserState.getSdEndorsers();
            ep = new ArrayList<>(ep); // just in case it's not already a copy

            if (IS_TRACE_LEVEL) {

                StringBuilder sb = new StringBuilder(1000);
                String sep = "";
                for (SDEndorser sdEndorser : ep) {
                    sb.append(sep).append(sdEndorser);
                }
                logger.trace(format("Channel %s, chaincode %s attempts: %d requested endorsements: %s", name,
                        chaincodeName, attempts, sb.toString()));
            }

            //Safety check make sure the selector isn't giving back endpoints to retry
            ep.removeIf(sdEndorser -> goodResponses.keySet().contains(sdEndorser));

            if (ep.isEmpty()) { // this would be odd but lets go with it.
                logger.debug(format(
                        "Channel %s, chaincode %s attempts: %d endorser selector returned no additional endorements needed.",
                        name, chaincodeName, attempts));

                Collection<SDEndorser> needed = sdChaindcode.meetsEndorsmentPolicy(goodResponses.keySet());
                if (needed != null) { // means endorsment meet with those in the needed.
                    ArrayList<ProposalResponse> ret = new ArrayList<>(needed.size());
                    needed.forEach(s -> ret.add(goodResponses.get(s)));

                    if (IS_DEBUG_LEVEL) {

                        StringBuilder sb = new StringBuilder(1000);
                        String sep = "";
                        for (ProposalResponse proposalResponse : ret) {
                            sb.append(sep).append(proposalResponse.getPeer());
                            sep = ", ";
                        }
                        logger.debug(
                                format("Channel %s, chaincode %s attempts: %d got all needed endorsements: %s",
                                        name, chaincodeName, attempts, sb.toString()));
                    }

                    return ret; // the happy path :)!

                } else { //still don't have the needed endorsements.

                    logger.debug(format("Channel %s, chaincode %s attempts: %d missing needed endorsements",
                            name, chaincodeName, attempts));

                    if (inspectResults) {
                        return allTried.values();
                    } else {
                        throw new ServiceDiscoveryException(
                                format("Could not meet endorsement policy for chaincode %s", chaincodeName));
                    }
                }
            }

            Map<String, Peer> lpeerEndpointMap = new HashMap<>(peerEndpointMap);
            Map<SDEndorser, Peer> endorsers = new HashMap<>(ep.size());
            Map<PeerExactMatch, SDEndorser> peer2sdEndorser = new HashMap<>(ep.size());
            for (SDEndorser sdEndorser : ep) {

                Peer epeer = lpeerEndpointMap.get(sdEndorser.getEndpoint());
                if (epeer != null && !epeer.hasConnected()) {
                    // mostly because gossip may have malicious data so if we've not connected update TLS props from chaincode discovery.
                    final Properties properties = epeer.getProperties();

                    final byte[] bytes = combineCerts(sdEndorser.getTLSCerts(),
                            sdEndorser.getTLSIntermediateCerts());
                    properties.put("pemBytes", bytes);
                    epeer.setProperties(properties);

                } else if (null == epeer) {
                    epeer = sdPeerAddition.addPeer(new SDPeerAdditionInfo() {

                        @Override
                        public String getMspId() {
                            return sdEndorser.getMspid();
                        }

                        @Override
                        public String getEndpoint() {
                            return sdEndorser.getEndpoint();
                        }

                        @Override
                        public Channel getChannel() {
                            return Channel.this;
                        }

                        @Override
                        public HFClient getClient() {
                            return Channel.this.client;
                        }

                        @Override
                        public byte[][] getTLSCerts() {

                            return sdEndorser.getTLSCerts()
                                    .toArray(new byte[sdEndorser.getTLSCerts().size()][]);
                        }

                        @Override
                        public byte[][] getTLSIntermediateCerts() {
                            return sdEndorser.getTLSIntermediateCerts()
                                    .toArray(new byte[sdEndorser.getTLSIntermediateCerts().size()][]);
                        }

                        @Override
                        public Map<String, Peer> getEndpointMap() {
                            return Collections.unmodifiableMap(Channel.this.peerEndpointMap);
                        }
                    });
                }
                endorsers.put(sdEndorser, epeer);
                peer2sdEndorser.put(new PeerExactMatch(epeer), sdEndorser); // reverse
            }

            final Collection<ProposalResponse> proposalResponses = sendProposalToPeers(endorsers.values(),
                    invokeProposal, transactionContext);
            HashSet<SDEndorser> loopGood = new HashSet<>();
            HashSet<SDEndorser> loopBad = new HashSet<>();

            for (ProposalResponse proposalResponse : proposalResponses) {
                final SDEndorser sdEndorser = peer2sdEndorser
                        .get(new PeerExactMatch(proposalResponse.getPeer()));
                allTried.put(sdEndorser, proposalResponse);

                final ChaincodeResponse.Status status = proposalResponse.getStatus();

                if (ChaincodeResponse.Status.SUCCESS.equals(status)) {

                    goodResponses.put(sdEndorser, proposalResponse);
                    logger.trace(format("Channel %s, chaincode %s attempts %d good endorsements: %s", name,
                            chaincodeName, attempts, sdEndorser));
                    loopGood.add(sdEndorser);

                } else {
                    logger.debug(format("Channel %s, chaincode %s attempts %d bad endorsements: %s", name,
                            chaincodeName, attempts, sdEndorser));
                    loopBad.add(sdEndorser);
                }
            }

            //Always check on original
            Collection<SDEndorser> required = sdChaindcode.meetsEndorsmentPolicy(goodResponses.keySet());
            if (required != null) {
                ArrayList<ProposalResponse> ret = new ArrayList<>(required.size());
                required.forEach(s -> ret.add(goodResponses.get(s)));

                if (IS_DEBUG_LEVEL) {

                    StringBuilder sb = new StringBuilder(1000);
                    String sep = "";
                    for (ProposalResponse proposalResponse : ret) {
                        sb.append(sep).append(proposalResponse.getPeer());
                        sep = ", ";
                    }
                    logger.debug(format("Channel %s, chaincode %s got all needed endorsements: %s", name,
                            chaincodeName, sb.toString()));
                }
                return ret; // the happy path :)!

            } else { //still don't have the needed endorsements.

                sdChaindcodeEndorsementCopy.endorsedList(loopGood); // mark the good ones in the working copy.

                if (sdChaindcodeEndorsementCopy.ignoreListSDEndorser(loopBad) < 1) { // apply ignore list
                    done = true; // no more layouts
                }
            }

        } while (!done && ++attempts <= 5);
        logger.debug(format("Endorsements not achieved chaincode: %s, done: %b, attempts: %d", chaincodeName,
                done, attempts));
        if (inspectResults) {
            return allTried.values();
        } else {
            throw new ServiceDiscoveryException(
                    format("Could not meet endorsement policy for chaincode %s", chaincodeName));
        }
    } catch (ProposalException e) {
        throw e;

    } catch (Exception e) {
        ProposalException exp = new ProposalException(e);
        logger.error(exp.getMessage(), exp);
        throw exp;
    }
}