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:io.gravitee.repository.redis.management.RedisMembershipRepository.java

@Override
public Set<Membership> findByReferencesAndMembershipType(MembershipReferenceType referenceType,
        List<String> referenceIds, String membershipType) throws TechnicalException {
    Set<RedisMembership> memberships = membershipRedisRepository.findByReferences(referenceType.name(),
            referenceIds);// www.j a va2  s.  co  m
    if (membershipType == null) {
        return memberships.stream().map(this::convert).collect(Collectors.toSet());
    } else {
        return memberships.stream().filter(membership -> membershipType.equals(membership.getType()))
                .map(this::convert).collect(Collectors.toSet());
    }
}

From source file:se.uu.it.cs.recsys.service.resource.CourseResource.java

@Path("/{code}")
@GET//from   w  ww.j a v a 2  s. com
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Query by course code", response = Course.class, responseContainer = "Set")
public Set<Course> getCourse(@ApiParam(name = "code", required = true) @PathParam("code") String code) {

    return this.courseRepository.findByCode(code).stream().map(entity -> CourseConverter.convert(entity))
            .collect(Collectors.toSet());

}

From source file:io.gravitee.gateway.services.sync.SyncManager.java

public void refresh() {
    logger.debug("Refreshing gateway state...");

    try {/* w ww .jav  a 2s .  c o  m*/
        Set<io.gravitee.repository.management.model.Api> apis = apiRepository.findAll();

        // Determine deployed APIs store into events payload
        Set<Api> deployedApis = getDeployedApis(apis);

        Map<String, Api> apisMap = deployedApis.stream().filter(api -> api != null && hasMatchingTags(api))
                .collect(Collectors.toMap(Api::getId, api -> api));

        // Determine APIs to undeploy
        Set<String> apiToRemove = apiManager.apis().stream()
                .filter(api -> !apisMap.containsKey(api.getId()) || !hasMatchingTags(api)).map(Api::getId)
                .collect(Collectors.toSet());

        apiToRemove.forEach(apiManager::undeploy);

        // Determine APIs to update
        apisMap.keySet().stream().filter(apiId -> apiManager.get(apiId) != null).forEach(apiId -> {
            // Get local cached API
            Api deployedApi = apiManager.get(apiId);

            // Get API from store
            Api remoteApi = apisMap.get(apiId);

            if (deployedApi.getDeployedAt().before(remoteApi.getDeployedAt())) {
                apiManager.update(remoteApi);
            }
        });

        // Determine APIs to deploy
        apisMap.keySet().stream().filter(api -> apiManager.get(api) == null).forEach(api -> {
            Api newApi = apisMap.get(api);
            apiManager.deploy(newApi);
        });
    } catch (TechnicalException te) {
        logger.error("Unable to sync instance", te);
    }
}

From source file:com.vsct.dt.hesperides.templating.modules.event.ModuleContainer.java

/**
 * Return list of template.// www . j av a 2  s .  co  m
 *
 * @return set of template
 */
@Override
public Set<Template> loadAllTemplate() {
    Set<Template> tpl;

    if (this.module == null) {
        tpl = ImmutableSet.of();
    } else {
        tpl = this.template.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toSet());
    }

    return tpl;
}

From source file:delfos.dataset.generated.modifieddatasets.pseudouser.PseudoUserRatingsDataset.java

@Override
public Set<Integer> allUsers() {
    Set<Integer> allUsers = new TreeSet<>();

    allUsers.addAll(originalDatasetLoader.getRatingsDataset().allUsers());
    allUsers.addAll(pseudoUsersRatings.keySet().stream().map(user -> user.getId()).collect(Collectors.toSet()));
    return allUsers;
}

From source file:io.syndesis.jsondb.dao.JsonDbDao.java

@Override
public Set<String> fetchIdsByPropertyValue(final String property, final String propertyValue) {
    return jsondb.fetchIdsByPropertyValue(getCollectionPath(), property.replace('.', '/'), propertyValue)
            .stream().map(path -> path.substring(path.indexOf(':') + 1)).collect(Collectors.toSet());
}

From source file:com.orange.cepheus.broker.controller.NgsiController.java

@Override
public UpdateContextResponse updateContext(final UpdateContext update)
        throws ExecutionException, InterruptedException, URISyntaxException {

    //TODO : search providingApplication for all contextElement of updateContext
    ContextElement contextElement = update.getContextElements().get(0);
    Set<String> attributesName = contextElement.getContextAttributeList().stream()
            .map(ContextAttribute::getName).collect(Collectors.toSet());

    logger.debug("<= updateContext with entityId: {} and attributes: {} ",
            contextElement.getEntityId().toString(), attributesName);

    /*//  w ww . java 2 s .  c  o  m
     * If a registration matches the updateContext, the updateContext is forwarded to the corresponding providingURL.
     * Else, the update is forwarded to the remote broker and the subscribers are notified.
     */

    // Search registrations to forward updateContext
    Iterator<URI> providingApplication = localRegistrations
            .findProvidingApplication(contextElement.getEntityId(), attributesName);
    if (providingApplication.hasNext()) {
        // Forward the update to the first providing Application (command)
        final String providerUrl = providingApplication.next().toString();
        HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(providerUrl);
        logger.debug("=> updateContext forwarded to {} with Content-Type {}", providerUrl,
                httpHeaders.getContentType());
        return ngsiClient.updateContext(providerUrl, httpHeaders, update).get();
    }

    // Forward the update to the remote broker
    if (configuration.isRemoteForwardUpdateContext()) {
        final String brokerUrl = configuration.getRemoteUrl();
        if (brokerUrl == null || brokerUrl.isEmpty()) {
            logger.warn("No remote.url parameter defined to forward updateContext");
        } else {
            HttpHeaders httpHeaders = getRemoteBrokerHeaders(brokerUrl);
            logger.debug("=> updateContext forwarded to remote broker {} with Content-Type {}", brokerUrl,
                    httpHeaders.getContentType());
            ngsiClient.updateContext(brokerUrl, httpHeaders, update).addCallback(
                    updateContextResponse -> logUpdateContextResponse(updateContextResponse, brokerUrl),
                    throwable -> logger.warn("UpdateContext failed for {}: {}", brokerUrl,
                            throwable.toString()));
        }
    }

    List<ContextElementResponse> contextElementResponseList = new ArrayList<>();
    StatusCode statusCode = new StatusCode(CodeEnum.CODE_200);
    for (ContextElement c : update.getContextElements()) {
        contextElementResponseList.add(new ContextElementResponse(c, statusCode));
    }

    String originator = configuration.getLocalUrl();
    if (originator == null || originator.isEmpty()) {
        logger.warn("No local.url parameter defined to use as originator for sending notifyContext");
    } else {
        // Send notifications to matching subscriptions
        Iterator<Subscription> matchingSubscriptions = subscriptions
                .findSubscriptions(contextElement.getEntityId(), attributesName);
        while (matchingSubscriptions.hasNext()) {
            Subscription subscription = matchingSubscriptions.next();
            NotifyContext notifyContext = new NotifyContext(subscription.getSubscriptionId(),
                    new URI(originator));
            notifyContext.setContextElementResponseList(contextElementResponseList);
            String providerUrl = subscription.getSubscribeContext().getReference().toString();

            HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(providerUrl);
            logger.debug("=> notifyContext to {} with Content-Type {}", providerUrl,
                    httpHeaders.getContentType());

            ngsiClient.notifyContext(providerUrl, httpHeaders, notifyContext).addCallback(
                    notifyContextResponse -> logNotifyContextResponse(notifyContextResponse, providerUrl),
                    throwable -> logger.warn("NotifyContext failed for {}: {}", providerUrl,
                            throwable.toString()));
        }
    }

    UpdateContextResponse updateContextResponse = new UpdateContextResponse();
    updateContextResponse.setContextElementResponses(contextElementResponseList);
    return updateContextResponse;
}

From source file:uk.dsxt.voting.client.ClientManager.java

public RequestResult getVotings(String clientId) {
    final Collection<Voting> votings = assetsHolder.getVotings().stream()
            .filter(v -> assetsHolder.getClientPacketSize(v.getId(), clientId) == null
                    || assetsHolder.getClientPacketSize(v.getId(), clientId).compareTo(BigDecimal.ZERO) > 0)
            .collect(Collectors.toSet());
    return new RequestResult<>(
            votings.stream().map(v -> new VotingWeb(v, assetsHolder.getClientVote(v.getId(), clientId) == null))
                    .collect(Collectors.toList()).toArray(new VotingWeb[votings.size()]),
            null);//from w w  w. j a  v a 2 s.  c o m
}

From source file:com.diversityarrays.kdxplore.trials.MyTrialExportHelper.java

MyTrialExportHelper(SampleGroupExportDialog sampleGroupExportDialog, KdxploreDatabase kdxdb,
        int targetDatabaseVersion, SampleGroup sampleGroup, boolean wantMediaFiles) {
    this.sampleGroupExportDialog = sampleGroupExportDialog;
    kdxploreDatabase = kdxdb;// w  w w.  jav  a 2s.  c  o  m
    kdsmartDatabase = kdxdb.getKDXploreKSmartDatabase();

    this.kdsmartVersionCode = kdxploreDatabase.getKDXploreKSmartDatabase().getKdsmartVersionCode();
    this.targetDatabaseVersion = targetDatabaseVersion;
    this.sampleGroupId = sampleGroup.getSampleGroupId();
    this.wantMediaFiles = wantMediaFiles;

    traitIds = sampleGroup.getSamples().stream().map(s -> s.getTraitId()).collect(Collectors.toSet());
}

From source file:com.adeptj.modules.jaxrs.core.jwt.filter.internal.AbstractJwtFilter.java

public void filter(ContainerRequestContext requestContext) {
    JwtService jwtService = this.getJwtService();
    if (jwtService == null) {
        requestContext.abortWith(Response.status(SERVICE_UNAVAILABLE).build());
        return;//from ww  w  .j  ava  2 s.c  om
    }
    String jwt = JwtExtractor.extract(requestContext);
    // Send Bad Request(400) if JWT is null/empty.
    if (StringUtils.isEmpty(jwt)) {
        requestContext.abortWith(Response.status(BAD_REQUEST).build());
        return;
    }
    JwtClaims claims = jwtService.verifyJwt(jwt);
    claims.put(REQ_PATH_ATTR, requestContext.getUriInfo().getPath());
    if (this.getClaimsIntrospector().introspect(claims)) {
        requestContext.setSecurityContext(JwtSecurityContext.newSecurityContext()
                .withSubject(claims.getSubject())
                .withRoles(Stream.of(((String) claims.getOrDefault("roles", "")).split(","))
                        .collect(Collectors.toSet()))
                .withSecure(requestContext.getSecurityContext().isSecure()).withAuthScheme(AUTH_SCHEME_TOKEN));
    } else {
        // Send Unauthorized if JwtService finds token to be malformed, expired etc.
        // 401 is better suited for token verification failure.
        requestContext.abortWith(Response.status(UNAUTHORIZED).build());
    }
}