Example usage for java.util.stream Collectors toCollection

List of usage examples for java.util.stream Collectors toCollection

Introduction

In this page you can find the example usage for java.util.stream Collectors toCollection.

Prototype

public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Collection , in encounter order.

Usage

From source file:com.sastix.cms.server.services.content.impl.hazelcast.HazelcastResourceServiceImpl.java

@Override
public List<ResourceDTO> getCurrentResources() {
    List<Resource> currentResources = resourceRepository.findCurrent();
    return currentResources.stream().map(crs::convertToDTO).collect(Collectors.toCollection(ArrayList::new));
}

From source file:com.sastix.cms.server.services.content.impl.hazelcast.HazelcastResourceServiceImpl.java

@Override
public List<RevisionDTO> getResourceRevisions(String resourceUID) {
    List<Revision> revisions = revisionRepository.findRevisions(resourceUID);
    return revisions.stream().map(crs::convertToDTO).collect(Collectors.toCollection(ArrayList::new));
}

From source file:org.starnub.starnubserver.resources.connections.Players.java

/**
 * This represents a higher level method for StarNubs API.
 * <p>/*from   www  . j  a va 2s  .  co  m*/
 * Recommended: For Plugin Developers & Anyone else.
 * <p>
 * Uses: This will return a string of all the online players, optionally with Starbound and Starnub IDs.
 * This method is temporary and highly unofficial. This will later be refined.
 * <p>
 * @param showStarboundId boolean to show Starbound Ids
 * @param showStarNubId boolean to show Starnub Ids
 * @return String with all of the online players
 */
public String getOnlinePlayersNameList(Object sender, boolean showStarboundId, boolean showStarNubId) {
    boolean canSee = false;
    if (sender instanceof PlayerSession) {
        canSee = ((PlayerSession) sender).hasPermission("starnub.bypass.appear_offline", true);
    }

    String built = "";
    HashSet<String> playersOnline;

    final boolean finalCanSee = canSee;
    playersOnline = this.values().stream()
            .sorted((p1, p2) -> p1.getCleanNickName().compareTo(p2.getCleanNickName()))
            .map(p1 -> p1.getNickName() + "( "
                    + (showStarboundId && showStarNubId && (p1.getPlayerCharacter().getAccount() != null)
                            ? p1.getStarboundClientId() + "/"
                                    + p1.getPlayerCharacter().getAccount().getStarnubId()
                            : showStarboundId ? p1.getStarboundClientId()
                                    : showStarNubId && (p1.getPlayerCharacter().getAccount() != null)
                                            ? p1.getPlayerCharacter().getAccount().getStarnubId()
                                            : "")
                    + ((p1.getPlayerCharacter().getAccount() != null
                            && p1.getPlayerCharacter().getAccount().getAccountSettings().isAppearOffline())
                                    ? " )(H)"
                                    : ")"))

            .collect(Collectors.toCollection(LinkedHashSet::new));

    //        .filter(p -> !finalCanSee ? (p.getPlayerCharacter().getAccount() != null && !p.getPlayerCharacter().getAccount().getAccountSettings().isAppearOffline()) : null)

    //        //
    //        List<String> sortedPlayers = new ArrayList<String>();
    //        String tokenBaseShowStarboundId = "";
    //        String tokenBaseShowStarNubId = "";
    //        if (showStarboundId) {
    //            tokenBaseShowStarboundId = "StarboundID";
    //        }
    //        if (showStarNubId) {
    //            tokenBaseShowStarNubId = "StarNubID";
    //        }
    //        String combinedToken;
    //        if (!tokenBaseShowStarboundId.isEmpty() && !tokenBaseShowStarNubId.isEmpty()) {
    //            combinedToken = tokenBaseShowStarboundId+"/"+tokenBaseShowStarNubId;
    //        } else {
    //            combinedToken = tokenBaseShowStarboundId+tokenBaseShowStarNubId;
    //        }
    //        combinedToken = "("+combinedToken+")";
    //        String playersOnline = "Players Online: "+ this.size() +". NickName "+combinedToken+": ";
    //        String token;
    //        String tokenShowStarboundId = "";
    //        String tokenShowStarNubId = "";
    //        for (PlayerSession playerSessionSession : this.values()) {
    //            ArrayList<Boolean> appearance = canSeePlayerIsHiddenCanSee(sender, playerSessionSession);
    //            String hiddenToken = "";
    //            if (appearance.get(0)) {
    //                hiddenToken = " (H)";
    //            }
    //
    //            if (appearance.get(1)) {
    //                if (showStarboundId) {
    //                    tokenShowStarboundId = Long.toString(playerSessionSession.getStarboundClientId());
    //                }
    //                if (showStarNubId) {
    //                    if (playerSessionSession.getPlayerCharacter().getAccount().getStarnubId() > 0) {
    //                        tokenShowStarNubId = Integer.toString(playerSessionSession.getPlayerCharacter().getAccount().getStarnubId()) + "S";
    //                    } else {
    //                        tokenShowStarNubId = "NA";
    //                    }
    //                }
    //
    //                if (!tokenShowStarboundId.isEmpty() && !tokenShowStarNubId.isEmpty()) {
    //                    token = tokenShowStarboundId + "/" + tokenShowStarNubId;
    //                } else {
    //                    token = tokenShowStarboundId + tokenShowStarNubId;
    //                }
    //                token = "(" + token + ")";
    //                sortedPlayers.add(playerSessionSession.getCleanNickName() + hiddenToken + " " + token);
    //            }
    //        }
    //        Collections.sort(sortedPlayers);
    //        for (String player : sortedPlayers) {
    //            playersOnline = playersOnline + player+", ";
    //        }
    //        try {
    //            playersOnline = playersOnline.substring(0, playersOnline.lastIndexOf(",")) + ".";
    //        } catch (StringIndexOutOfBoundsException e) {
    //            /* Do nothing no players are online */
    //        }
    return String.valueOf(playersOnline);
}

From source file:sx.blah.discord.handle.impl.obj.Guild.java

public void loadWebhooks() {
    try {//www  .j a v  a  2 s  .  co  m
        PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.MANAGE_WEBHOOKS);
    } catch (MissingPermissionsException ignored) {
        return;
    }

    RequestBuffer.request(() -> {
        try {
            List<IWebhook> oldList = getWebhooks().stream().map(IWebhook::copy)
                    .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

            WebhookObject[] response = ((DiscordClientImpl) client).REQUESTS.GET
                    .makeRequest(DiscordEndpoints.GUILDS + getStringID() + "/webhooks", WebhookObject[].class);

            if (response != null) {
                for (WebhookObject webhookObject : response) {
                    Channel channel = (Channel) getChannelByID(
                            Long.parseUnsignedLong(webhookObject.channel_id));
                    long webhookId = Long.parseUnsignedLong(webhookObject.id);
                    if (getWebhookByID(webhookId) == null) {
                        IWebhook newWebhook = DiscordUtils.getWebhookFromJSON(channel, webhookObject);
                        client.getDispatcher().dispatch(new WebhookCreateEvent(newWebhook));
                        channel.webhooks.put(newWebhook);
                    } else {
                        IWebhook toUpdate = channel.getWebhookByID(webhookId);
                        IWebhook oldWebhook = toUpdate.copy();
                        toUpdate = DiscordUtils.getWebhookFromJSON(channel, webhookObject);
                        if (!oldWebhook.getDefaultName().equals(toUpdate.getDefaultName())
                                || !String.valueOf(oldWebhook.getDefaultAvatar())
                                        .equals(String.valueOf(toUpdate.getDefaultAvatar())))
                            client.getDispatcher().dispatch(new WebhookUpdateEvent(oldWebhook, toUpdate));

                        oldList.remove(oldWebhook);
                    }
                }
            }

            oldList.forEach(webhook -> {
                ((Channel) webhook.getChannel()).webhooks.remove(webhook);
                client.getDispatcher().dispatch(new WebhookDeleteEvent(webhook));
            });
        } catch (Exception e) {
            Discord4J.LOGGER.warn(LogMarkers.HANDLE, "Discord4J Internal Exception", e);
        }
    });
}

From source file:org.flowable.engine.impl.dynamic.AbstractDynamicStateManager.java

protected void safeDeleteSubProcessInstance(String processInstanceId, List<ExecutionEntity> executionsPool,
        String deleteReason, CommandContext commandContext) {
    ExecutionEntityManager executionEntityManager = CommandContextUtil
            .getExecutionEntityManager(commandContext);

    //Confirm that all the subProcessExecutions are in the executionsPool
    List<ExecutionEntity> subProcessExecutions = executionEntityManager
            .findChildExecutionsByProcessInstanceId(processInstanceId);
    HashSet<String> executionIdsToMove = executionsPool.stream().map(ExecutionEntity::getId)
            .collect(Collectors.toCollection(HashSet::new));
    Optional<ExecutionEntity> notIncludedExecution = subProcessExecutions.stream()
            .filter(e -> !executionIdsToMove.contains(e.getId())).findAny();
    if (notIncludedExecution.isPresent()) {
        throw new FlowableException(
                "Execution of sub process instance is not moved " + notIncludedExecution.get().getId());
    }/*from w w w .j a  v a 2s .co  m*/

    // delete the sub process instance
    executionEntityManager.deleteProcessInstance(processInstanceId, deleteReason, true);
}

From source file:com.evolveum.midpoint.model.impl.lens.projector.focus.InboundProcessor.java

private <V extends PrismValue, D extends ItemDefinition, F extends FocusType> boolean processAssociationInbound(
        QName accountAttributeName, ObjectDelta<ShadowType> aPrioriProjectionDelta,
        final LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition,
        final LensContext<F> context, XMLGregorianCalendar now,
        Map<ItemDefinition, List<MappingImpl<?, ?>>> mappingsToTarget, Task task, OperationResult result)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException,
        SecurityViolationException, CommunicationException {

    PrismObject<ShadowType> projCurrent = projContext.getObjectCurrent();
    PrismObject<ShadowType> projNew = projContext.getObjectNew();

    final ItemDelta<V, D> attributeAPrioriDelta;
    if (aPrioriProjectionDelta != null) {
        attributeAPrioriDelta = aPrioriProjectionDelta.findItemDelta(new ItemPath(ShadowType.F_ASSOCIATION));
        if (attributeAPrioriDelta == null && !projContext.isFullShadow()
                && !LensUtil.hasDependentContext(context, projContext)) {
            LOGGER.trace(// w  w  w  . j  a  v a 2 s.c o  m
                    "Skipping inbound for {} in {}: Not a full shadow and account a priori delta exists, but doesn't have change for processed property.",
                    accountAttributeName, projContext.getResourceShadowDiscriminator());
            return true;
        }
    } else {
        attributeAPrioriDelta = null;
    }

    RefinedAssociationDefinition associationDef = projectionDefinition
            .findAssociationDefinition(accountAttributeName);

    //TODO:
    if (associationDef.isIgnored(LayerType.MODEL)) {
        LOGGER.trace("Skipping inbound for association {} in {} because the association is ignored",
                PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator());
        return true;
    }

    List<MappingType> inboundMappingTypes = associationDef.getInboundMappingTypes();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Processing inbound for {} in {}; ({} mappings)",
                PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator(),
                inboundMappingTypes.size());
    }

    PropertyLimitations limitations = associationDef.getLimitations(LayerType.MODEL);
    if (limitations != null) {
        PropertyAccessType access = limitations.getAccess();
        if (access != null) {
            if (access.isRead() == null || !access.isRead()) {
                LOGGER.warn("Inbound mapping for non-readable association {} in {}, skipping",
                        accountAttributeName, projContext.getHumanReadableName());
                return true;
            }
        }
    }

    if (inboundMappingTypes.isEmpty()) {
        return true;
    }

    for (MappingType inboundMappingType : inboundMappingTypes) {

        // There are two processing options:
        //
        //  * If we have a delta as an input we will proceed in relative mode, applying mappings on the delta.
        //    This usually happens when a delta comes from a sync notification or if there is a primary projection delta.
        //
        //  * if we do NOT have a delta then we will proceed in absolute mode. In that mode we will apply the
        //    mappings to the absolute projection state that we got from provisioning. This is a kind of "inbound reconciliation".
        //
        // TODO what if there is a priori delta for a given attribute (e.g. ADD one) and
        // we want to reconcile also the existing attribute value? This probably would not work.
        if (inboundMappingType.getStrength() == MappingStrengthType.STRONG) {
            LOGGER.trace(
                    "There is an association inbound mapping with strength == STRONG, trying to load full account now.");
            if (!projContext.isFullShadow() && !projContext.isDelete()) {
                projCurrent = loadProjection(context, projContext, task, result, projCurrent);
                if (projContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
                    return false;
                }
            }
        }

        if (attributeAPrioriDelta == null && !projContext.isFullShadow()
                && !LensUtil.hasDependentContext(context, projContext)) {
            LOGGER.trace(
                    "Skipping association inbound for {} in {}: Not a full shadow and account a priori delta exists, but doesn't have change for processed property.",
                    accountAttributeName, projContext.getResourceShadowDiscriminator());
            continue;
        }

        PrismObject<F> focus;
        if (context.getFocusContext().getObjectCurrent() != null) {
            focus = context.getFocusContext().getObjectCurrent();
        } else {
            focus = context.getFocusContext().getObjectNew();
        }

        ItemDelta focusItemDelta = null;
        if (attributeAPrioriDelta != null) {
            LOGGER.trace("Processing association inbound from a priori delta: {}", attributeAPrioriDelta);

            PrismContainer<ShadowAssociationType> oldShadowAssociation = projCurrent
                    .findContainer(ShadowType.F_ASSOCIATION);

            PrismContainer<ShadowAssociationType> filteredAssociations = null;
            if (oldShadowAssociation != null) {
                filteredAssociations = oldShadowAssociation.getDefinition().instantiate();
                Collection<PrismContainerValue<ShadowAssociationType>> filteredAssociationValues = oldShadowAssociation
                        .getValues().stream()
                        .filter(rVal -> accountAttributeName.equals(rVal.asContainerable().getName()))
                        .map(val -> val.clone()).collect(Collectors.toCollection(ArrayList::new));
                prismContext.adopt(filteredAssociations);
                filteredAssociations.addAll(filteredAssociationValues);
            }

            resolveEntitlementsIfNeeded((ContainerDelta<ShadowAssociationType>) attributeAPrioriDelta,
                    filteredAssociations, projContext, task, result);

            VariableProducer<PrismContainerValue<ShadowAssociationType>> entitlementVariable = (value,
                    variables) -> resolveEntitlement(value, projContext, variables);
            collectMappingsForTargets(context, projContext, inboundMappingType, accountAttributeName,
                    (Item) oldShadowAssociation, attributeAPrioriDelta, focus,
                    (VariableProducer) entitlementVariable, mappingsToTarget, task, result);

        } else if (projCurrent != null) {

            projCurrent = loadFullShadowIfNeeded(projContext, projCurrent, context, now, task, result);
            if (projCurrent == null) {
                LOGGER.trace("Loading of full shadow failed");
                return false;
            }

            PrismContainer<ShadowAssociationType> oldShadowAssociation = projCurrent
                    .findContainer(ShadowType.F_ASSOCIATION);

            if (oldShadowAssociation == null) {
                LOGGER.trace("No shadow association value");
                return true;
            }

            PrismContainer<ShadowAssociationType> filteredAssociations = oldShadowAssociation.getDefinition()
                    .instantiate();
            Collection<PrismContainerValue<ShadowAssociationType>> filteredAssociationValues = oldShadowAssociation
                    .getValues().stream()
                    .filter(rVal -> accountAttributeName.equals(rVal.asContainerable().getName()))
                    .map(val -> val.clone()).collect(Collectors.toCollection(ArrayList::new));
            prismContext.adopt(filteredAssociations);
            filteredAssociations.addAll(filteredAssociationValues);

            resolveEntitlementsIfNeeded((ContainerDelta<ShadowAssociationType>) attributeAPrioriDelta,
                    filteredAssociations, projContext, task, result);

            VariableProducer<PrismContainerValue<ShadowAssociationType>> entitlementVariable = (value,
                    variables) -> resolveEntitlement(value, projContext, variables);
            ;

            LOGGER.trace("Processing association inbound from account sync absolute state (currentAccount): {}",
                    filteredAssociations);
            collectMappingsForTargets(context, projContext, inboundMappingType, accountAttributeName,
                    filteredAssociations, null, focus, entitlementVariable, mappingsToTarget, task, result);

        }
    }

    return true;
}

From source file:sx.blah.discord.handle.impl.obj.Channel.java

/**
 * Forcibly loads and caches all webhooks for the channel.
 *///www  .j av  a 2 s  .com
public void loadWebhooks() {
    try {
        PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.MANAGE_WEBHOOKS);
    } catch (MissingPermissionsException ignored) {
        return;
    }

    RequestBuffer.request(() -> {
        try {
            List<IWebhook> oldList = getWebhooks().stream().map(IWebhook::copy)
                    .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

            WebhookObject[] response = ((DiscordClientImpl) client).REQUESTS.GET.makeRequest(
                    DiscordEndpoints.CHANNELS + getStringID() + "/webhooks", WebhookObject[].class);

            if (response != null) {
                for (WebhookObject webhookObject : response) {
                    long webhookId = Long.parseUnsignedLong(webhookObject.id);
                    if (getWebhookByID(webhookId) == null) {
                        IWebhook newWebhook = DiscordUtils.getWebhookFromJSON(this, webhookObject);
                        client.getDispatcher().dispatch(new WebhookCreateEvent(newWebhook));
                        webhooks.put(newWebhook);
                    } else {
                        IWebhook toUpdate = getWebhookByID(webhookId);
                        IWebhook oldWebhook = toUpdate.copy();
                        toUpdate = DiscordUtils.getWebhookFromJSON(this, webhookObject);
                        if (!oldWebhook.getDefaultName().equals(toUpdate.getDefaultName())
                                || !String.valueOf(oldWebhook.getDefaultAvatar())
                                        .equals(String.valueOf(toUpdate.getDefaultAvatar())))
                            client.getDispatcher().dispatch(new WebhookUpdateEvent(oldWebhook, toUpdate));

                        oldList.remove(oldWebhook);
                    }
                }
            }

            oldList.forEach(webhook -> {
                webhooks.remove(webhook);
                client.getDispatcher().dispatch(new WebhookDeleteEvent(webhook));
            });
        } catch (Exception e) {
            Discord4J.LOGGER.warn(LogMarkers.HANDLE, "Discord4J Internal Exception", e);
        }
    });
}

From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java

protected Collection<FieldInfo> extractFieldInfos(TypeElement typeElement, VariableElementValidator validator) {
    Map<String, FieldInfo> allFields = new HashMap<>();
    typeElement.getEnclosedElements().forEach(element -> {
        if (element.getKind().equals(ElementKind.FIELD)) {
            VariableElement fieldElement = (VariableElement) element;

            if (validator != null && !validator.isValid(fieldElement)) {
                return;
            }/*  w  ww. ja  v  a2  s  .c  o  m*/

            FieldInfo fieldInfo = getInfoFromMap(fieldElement.getSimpleName().toString(), allFields);

            if (fieldInfo == null) {
                fieldInfo = new FieldInfo();
                allFields.put(fieldElement.getSimpleName().toString(), fieldInfo);
            }
            fieldInfo.fieldElement = fieldElement;
        } else if (element.getKind().equals(ElementKind.METHOD)) {
            ExecutableElement method = (ExecutableElement) element;

            String methodName = method.getSimpleName().toString();

            if (isGetter(method)) {
                String fieldName = extractFieldName(methodName, 3);
                FieldInfo info = getInfoFromMap(fieldName, allFields);
                info.getter = methodName;
            } else if (isBooleanGetter(method)) {
                String fieldName = extractFieldName(methodName, 2);
                FieldInfo info = getInfoFromMap(fieldName, allFields);
                info.getter = methodName;
            } else if (isSetter(method)) {
                String fieldName = extractFieldName(methodName, 3);
                FieldInfo info = getInfoFromMap(fieldName, allFields);
                info.setter = methodName;
            }
        }
    });

    return allFields.values().stream().filter(fieldInfo -> fieldInfo.fieldElement != null)
            .collect(Collectors.toCollection(() -> new ArrayList<>()));
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

private void ensureUniqueAndIndexingBlocking(String id, JsonObject data, Boolean isNew,
        AsyncResultHandler<String> resultHandler) {
    Async.waterfall().<String>task(t -> {
        RBatch batch = redissonOther.createBatch();
        ArrayList<String> pList = new ArrayList();
        try {/*  w w  w  . j a v a2 s.  co  m*/
            prepareEnsureUnique(id, data, batch, pList, null);
        } catch (RepositoryException ex) {
            t.handle(Future.failedFuture(ex));
            return;
        }
        if (pList.isEmpty()) {
            t.handle(Future.succeededFuture());
            return;
        }
        batch.executeAsync().addListener(future -> {
            if (future.isSuccess() && future.get() != null) {
                List<String> result = (List<String>) future.get();
                Stream<String> filter = pList.stream().filter(
                        p -> result.get(pList.indexOf(p)) != null && !result.get(pList.indexOf(p)).equals(id));//uniques are ensured by using putIfAbsent and all results should be null or itself to indicate no violation.
                Object[] filterArray = filter.toArray();
                if (filterArray.length != 0) {
                    t.handle(Future.succeededFuture(
                            new JsonObject().put("uniqueViolation", Json.encode(filterArray)).encode()));
                    //now undo these things.
                    ArrayList<String> undoList = pList.stream()
                            .filter(p -> result.get(pList.indexOf(p)) == null
                                    || result.get(pList.indexOf(p)).equals(id))
                            .collect(Collectors.toCollection(ArrayList::new));
                    Async.<Void>waterfall().<Void>task(task -> {
                        RBatch b = redissonOther.createBatch();
                        try {
                            prepareUndoUnique(id, data, b, undoList, null);
                        } catch (RepositoryException ex) {
                            task.handle(Future.failedFuture(ex));
                        }
                        b.executeAsync().addListener(fu -> {
                            task.handle(fu.isSuccess() ? Future.succeededFuture((Void) fu.get())
                                    : Future.failedFuture(fu.cause()));
                        });
                    }).run(run -> {
                        logger.debug("Parallel undo indexing [id: " + id + "] "
                                + (run.succeeded() ? "successed." : "failed."));
                    });
                } else {
                    t.handle(Future.succeededFuture());
                }
            } else {
                t.handle(Future.failedFuture(!future.isSuccess() ? future.cause().fillInStackTrace()
                        : new RepositoryException("No unique check result returned")));
            }
        });
    }).<String>task((violations, t) -> {
        if (violations != null) {
            t.handle(Future.failedFuture(violations));
            return;
        } else {
            t.handle(Future.succeededFuture());
        }
        //parallel indexing
        Async.<Void>waterfall().<T>task(task -> {
            if (!isNew) {
                fetch(id, Boolean.TRUE, task);
            } else {
                task.handle(Future.succeededFuture(null));
            }
        }).<Void>task((r, task) -> {
            reIndex(id, r, data, isNew, ri -> {
                task.handle(
                        ri.succeeded() ? Future.succeededFuture(ri.result()) : Future.failedFuture(ri.cause()));
            });
        }).run(run -> {
            logger.debug("Parallel Indexing [id: " + id + "] " + (run.succeeded() ? "successed." : "failed."),
                    run.cause());
        });
    }).run(resultHandler);

}