Example usage for java.util.stream Collectors toSet

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

Introduction

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

Prototype

public static <T> Collector<T, ?, Set<T>> toSet() 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Set .

Usage

From source file:ru.trett.cis.services.InventoryServiceImpl.java

@Override
@Transactional(readOnly = true)//from  w w w. j  a va  2  s.c  om
public Set<Invoice> getInvoicesForEmployee(Employee employee) {
    List<Invoice> invoices = list(Invoice.class);
    return invoices.stream().filter(x -> x.getEmployee().equals(employee)).collect(Collectors.toSet());
}

From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalWriter.java

/**
 * Adds xmlns='...common-3' if needed./*from  ww w.  ja va2 s.co m*/
 * In fact, this is VERY ugly hack to avoid putting common-3 declarations all over the elements in bulk actions response.
 * e.getNamespaceURI returns something only if it was present during node creation.
 * So, in fact, this code is more than fragile. Seems to work with the current XNode->DOM serialization, though.
 */
private void addDefaultNamespaceDeclaration(Element top) {
    List<Element> prefixless = DOMUtil.getElementsWithoutNamespacePrefix(top);
    if (prefixless.size() < 2) {
        return; // nothing to do here
    }
    Set<String> namespaces = prefixless.stream().map(e -> emptyIfNull(e.getNamespaceURI()))
            .collect(Collectors.toSet());
    if (namespaces.size() != 1 || StringUtils.isEmpty(namespaces.iterator().next())) {
        return;
    }
    DOMUtil.setNamespaceDeclaration(top, "", namespaces.iterator().next());
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions.java

@Override
public boolean disable(Principal principal, AllowedActions actions) {
    return disable(principal, actions.getAvailableActions().stream().flatMap(avail -> avail.stream())
            .collect(Collectors.toSet()));
}

From source file:com.netflix.genie.web.services.loadbalancers.script.ScriptLoadBalancer.java

/**
 * {@inheritDoc}/*from   www  .j  a  v  a2 s .co  m*/
 */
@Override
public Cluster selectCluster(@Nonnull @NonNull @NotEmpty final Set<Cluster> clusters,
        @Nonnull @NonNull final JobRequest jobRequest) throws GenieException {
    final long selectStart = System.nanoTime();
    log.debug("Called");
    final Set<Tag> tags = Sets.newHashSet();
    try {
        if (this.isConfigured.get() && this.script.get() != null) {
            log.debug("Evaluating script for job {}", jobRequest.getId().orElse("without id"));
            final Bindings bindings = new SimpleBindings();
            // TODO: For now for backwards compatibility with balancer scripts continue writing Clusters out in
            //       V3 format. Change to V4 once stabalize a bit more
            bindings.put(CLUSTERS_BINDING, this.mapper.writeValueAsString(
                    clusters.stream().map(DtoConverters::toV3Cluster).collect(Collectors.toSet())));
            bindings.put(JOB_REQUEST_BINDING, this.mapper.writeValueAsString(jobRequest));

            // Run as callable and timeout after the configured timeout length
            final String clusterId = this.asyncTaskExecutor
                    .submit(() -> (String) this.script.get().eval(bindings))
                    .get(this.timeoutLength.get(), TimeUnit.MILLISECONDS);

            // Find the cluster if not null
            if (clusterId != null) {
                for (final Cluster cluster : clusters) {
                    if (clusterId.equals(cluster.getId())) {
                        tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FOUND));
                        return cluster;
                    }
                }
            }
            log.warn("Script returned a cluster not in the input list: {}", clusterId);
        } else {
            log.debug("Script returned null");
            tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_NOT_CONFIGURED));
            return null;
        }

        tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_NOT_FOUND));
        // Defer to any subsequent load balancer in the chain
        return null;
    } catch (final Exception e) {
        tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FAILED));
        tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, e.getClass().getCanonicalName()));
        log.error("Unable to execute script due to {}", e.getMessage(), e);
        return null;
    } finally {
        this.registry.timer(SELECT_TIMER_NAME, tags).record(System.nanoTime() - selectStart,
                TimeUnit.NANOSECONDS);
    }
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

@Override
@SuppressWarnings("unchecked")
public final IExperiment get(final IFactory p_factory, final String p_datamodel, final long p_simulationsteps,
        final boolean p_parallel, final String p_timemodel,
        final Supplier<RealDistribution> p_platformchangedurationdistributionsupplier,
        final int p_numberofpassengers, final double p_lightbarrierminfreetime, final double p_delayseconds) {
    try (final FileInputStream l_stream = new FileInputStream(p_datamodel)) {
        final Asimov l_model = (Asimov) m_context.createUnmarshaller().unmarshal(l_stream);

        // time definition

        final Instant l_starttime = ZonedDateTime.now(ZoneId.systemDefault())
                .with(ChronoField.CLOCK_HOUR_OF_DAY, 8).with(ChronoField.MINUTE_OF_HOUR, 45)
                .with(ChronoField.SECOND_OF_MINUTE, 0).with(ChronoField.NANO_OF_SECOND, 0)
                .with(ChronoField.DAY_OF_MONTH, 3).with(ChronoField.MONTH_OF_YEAR, 10)
                .with(ChronoField.YEAR, 2017).toInstant();

        final ITime l_time = "jump".equals(p_timemodel) ? new CJumpTime(l_starttime, p_simulationsteps)
                : new CStepTime(l_starttime, Duration.ofSeconds(1), p_simulationsteps);

        final CMessenger l_messenger = new CMessenger();

        final Set<IAction> l_actionsfrompackage = CCommon.actionsFromPackage().collect(Collectors.toSet());

        // asl agent definition
        final Map<String, String> l_agentdefs = agents(l_model.getAi());

        // macro (train-network) and microscopic model
        final Map<String, IPlatform<?>> l_platform = platform(l_model.getNetwork(), l_agentdefs, p_factory,
                l_time);/*  w  ww. j ava 2 s. c om*/
        final Map<String, IStation<?>> l_station = station(l_model.getNetwork(), l_agentdefs, p_factory, l_time,
                l_platform);
        final Pair<Map<String, ITrain<?>>, Map<String, IDoor<?>>> l_train = train(l_model.getNetwork(),
                l_agentdefs, p_factory, l_time, p_lightbarrierminfreetime);

        final Map<String, IElement<?>> l_agents = new HashMap<>();
        l_agents.putAll(l_platform);
        l_agents.putAll(l_station);
        l_agents.putAll(l_train.getLeft());
        l_agents.putAll(l_train.getRight());

        final CExperiment l_experiment = new CExperiment(p_simulationsteps, p_parallel, IStatistic.EMPTY,
                l_agents, l_time, l_messenger);

        // @todo create passengersources and their passenger generators according to scenario definition

        final IElement.IGenerator<IPassenger<?>> l_passengergenerator = passengergenerator(p_factory,
                "+!activate <-\n    state/transition\n.", l_actionsfrompackage, l_time);

        l_experiment.addAgent("passengersource_test",
                passengersourcegenerator(p_factory, "+!activate <-\n    state/transition\n.",
                        l_actionsfrompackage, l_time).generatesingle(new UniformRealDistribution(0.0, 1.0),
                                l_time.current().toEpochMilli(), p_numberofpassengers, l_passengergenerator,
                                l_experiment, l_agents.get("toy-node-1"),
                                p_platformchangedurationdistributionsupplier.get()));

        l_messenger.experiment(l_experiment);

        // experiment (executable model)
        return l_experiment;

    } catch (final Exception l_execption) {
        throw new CRuntimeException(l_execption);
    }
}

From source file:nu.yona.server.messaging.service.MessageService.java

private void deleteMessages(Collection<Message> messages) {
    Set<Message> messagesToBeDeleted = messages.stream()
            .flatMap(m -> m.getMessagesToBeCascadinglyDeleted().stream()).collect(Collectors.toSet());
    messagesToBeDeleted.addAll(messages);
    Set<MessageDestination> involvedMessageDestinations = messagesToBeDeleted.stream()
            .map(Message::getMessageDestination).collect(Collectors.toSet());

    messagesToBeDeleted.forEach(Message::prepareForDelete);
    involvedMessageDestinations.forEach(d -> MessageDestination.getRepository().saveAndFlush(d));

    messagesToBeDeleted.forEach(m -> m.getMessageDestination().remove(m));
    involvedMessageDestinations.forEach(d -> MessageDestination.getRepository().save(d));
}

From source file:com.ejisto.util.IOUtils.java

private static Collection<String> findAllClassNamesInDirectory(File directory) {
    int index = directory.getAbsolutePath().length();
    return getAllFiles(directory, classExtension).stream().filter(LambdaUtil.isDirectory().negate())
            .map(File::getPath).map(p -> translatePath(p.substring(index + 1, p.length() - 6)))
            .collect(Collectors.toSet());
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public Stream<MantaMultipartUpload> listInProgress() throws IOException {
    final String uploadsPath = uploadsPath();

    Stream<MantaMultipartUpload> stream = mantaClient.listObjects(uploadsPath).map(mantaObject -> {
        try {//  w  w w.  j a v a2  s . c o  m
            return mantaClient.listObjects(mantaObject.getPath()).map(item -> {
                final String objectName = FilenameUtils.getName(item.getPath());
                final UUID id = UUID.fromString(objectName);

                // We don't know the final object name. The server will implement
                // this as a feature in the future.

                return new ServerSideMultipartUpload(id, null, uuidPrefixedPath(id));
            }).collect(Collectors.toSet());
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }).flatMap(Collection::stream);

    danglingStreams.add(stream);

    return stream;
}

From source file:com.ethercamp.harmony.service.WalletService.java

private void checkForChangesInWallet(BlockSummary blockSummary, List<Transaction> transactions,
        Consumer<TransactionInfo> sendHandler, Consumer<TransactionInfo> receiveHandler) {
    final Set<ByteArrayWrapper> subscribed = addresses.keySet().stream().map(a -> cleanAddress(a))
            .flatMap(a -> {/*from   w w  w.  j a v a 2s .  c  o m*/
                try {
                    return Stream.of(new ByteArrayWrapper(Hex.decode(a)));
                } catch (Exception e) {
                    log.error("Problem getting bytes representation from " + a);
                    return Stream.empty();
                }
            }).collect(Collectors.toSet());

    final List<Transaction> confirmedTransactions = transactions.stream()
            .filter(transaction -> isSetContains(subscribed, transaction.getReceiveAddress())
                    || isSetContains(subscribed, transaction.getSender()))
            .collect(Collectors.toList());

    confirmedTransactions.forEach(transaction -> {
        final String hash = toHexString(transaction.getHash());
        final BigInteger amount = ByteUtil.bytesToBigInteger(transaction.getValue());
        final boolean hasSender = isSetContains(subscribed, transaction.getSender());
        final boolean hasReceiver = isSetContains(subscribed, transaction.getReceiveAddress());
        log.debug("Handle transaction hash:" + hash + ", hasSender:" + hasSender + ", amount:" + amount);

        if (hasSender) {
            sendHandler
                    .accept(new TransactionInfo(hash, amount, hasSender, toHexString(transaction.getSender())));
        }
        if (hasReceiver) {
            receiveHandler.accept(
                    new TransactionInfo(hash, amount, hasSender, toHexString(transaction.getReceiveAddress())));
        }
    });

    // check if balance changes due to block reward
    final Optional<ByteArrayWrapper> coinbase = Optional.ofNullable(blockSummary)
            .map(bs -> new ByteArrayWrapper(bs.getBlock().getCoinbase()));
    final Boolean matchCoinbase = coinbase.map(c -> subscribed.stream().anyMatch(a -> c.equals(a)))
            .orElse(false);

    final boolean needToSendUpdate = matchCoinbase || !confirmedTransactions.isEmpty();
    if (needToSendUpdate) {
        // update wallet if transactions are related to wallet addresses
        clientMessageService.sendToTopic("/topic/getWalletInfo", getWalletInfo());
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.user.JcrUserGroup.java

@Override
public GroupPrincipal getPrincial() {
    Set<Principal> members = StreamSupport.stream(getGroups().spliterator(), false).map(g -> g.getPrincial())
            .collect(Collectors.toSet());

    return new GroupPrincipal(getSystemName(), members);
}