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:pl.edu.icm.comac.vis.server.service.AtomicGraphServiceImpl.java

@Override
public Graph constructGraphs(String[] ids) throws OpenRDFException {
    List<NodeCacheEntry> favCacheNodes = fetchNodes(ids);
    //build link map
    Map<String, Set<String>> links = favCacheNodes.parallelStream().filter(x -> !x.isOverflow())
            .map(x -> x.getRelations()).flatMap(x -> x.stream())
            .flatMap(x -> Arrays.stream(
                    new String[][] { { x.getSubject(), x.getObject() }, { x.getObject(), x.getSubject() } }))
            .collect(Collectors.groupingBy(x -> x[0], Collectors.mapping(x -> x[1], Collectors.toSet())));
    Set<String> large = favCacheNodes.stream().filter(x -> x.isOverflow()).map(x -> x.getId())
            .collect(Collectors.toSet());
    Set<String> normal = favCacheNodes.stream().filter(x -> !x.isOverflow()).map(x -> x.getId())
            .collect(Collectors.toSet());
    Set<String> unfav = graphToolkit.calculateAdditions(normal, large, links, MAX_RETURNED_RELATIONS);
    //now fetch the unfavs:
    List<NodeCacheEntry> unfavCacheNodes = fetchNodes(unfav.toArray(new String[unfav.size()]));
    List<NodeCacheEntry> allNodes = new ArrayList<NodeCacheEntry>();
    allNodes.addAll(favCacheNodes);/*from w w w .ja v a 2  s.co  m*/
    allNodes.addAll(unfavCacheNodes);
    List<NodeCacheEntry> largeNodes = allNodes.stream().filter(x -> x.isOverflow())
            .collect(Collectors.toList());
    List<RelationCacheEntry> largeRelations = calculateRelations(largeNodes);
    //now build the graph:

    List<Node> nodes = new ArrayList<>();

    List<Node> fnodes = favCacheNodes.stream().map(cached -> {
        Node res = new Node(cached.getId(), cached.getType(), cached.getName(), 1.0);
        res.setFavourite(true);
        return res;
    }).collect(Collectors.toList());
    nodes.addAll(fnodes);
    List<Node> ufnodes = unfavCacheNodes.stream().map(cached -> {
        Node res = new Node(cached.getId(), cached.getType(), cached.getName(), 1.0);
        res.setFavourite(false);
        return res;
    }).collect(Collectors.toList());
    nodes.addAll(ufnodes);
    Set<String> nodeIdSet = nodes.stream().map(x -> x.getId()).collect(Collectors.toSet());

    Set<Link> graphRelations = allNodes.parallelStream().filter(x -> !x.isOverflow())
            .flatMap(x -> x.getRelations().stream())
            .filter(x -> nodeIdSet.contains(x.subject) && nodeIdSet.contains(x.object))
            .map(x -> new Link(x.getPredicate(), x.getSubject(), x.getObject())).collect(Collectors.toSet());
    Graph res = new Graph();

    res.setNodes(nodes);
    res.setLinks(new ArrayList<Link>(graphRelations));
    return res;
}

From source file:com.migo.shiro.UserRealm.java

/**
 * ?(???)/*from  w w  w  . ja  v a 2  s. c om*/
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SysUserEntity user = (SysUserEntity) principalCollection.getPrimaryPrincipal();
    Long userId = user.getUserId();

    List<String> permsList;

    //???
    if (userId == 1) {
        List<SysMenuEntity> menuList = sysMenuService.queryList(new HashMap<>());
        permsList = menuList.stream().parallel().map(SysMenuEntity::getPerms).collect(Collectors.toList());
        /*permsList = new ArrayList<>(menuList.size());
        for(SysMenuEntity menu : menuList){
        permsList.add(menu.getPerms());
        }*/
    } else {
        permsList = sysUserService.queryAllPerms(userId);
    }

    //??
    /* Set<String> permsSet = new HashSet<>();
     for(String perms : permsList){
    if(StringUtils.isBlank(perms)){
        continue;
    }
    permsSet.addAll(Arrays.asList(perms.trim().split(",")));
     }*/
    Set<String> permsSet = permsList.stream().parallel().filter(StringUtils::isNotBlank).map(String::trim)
            .map(s -> s.split(",")).map(Arrays::asList).flatMap(Collection::stream).collect(Collectors.toSet());
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setStringPermissions(permsSet);
    return info;
}

From source file:org.apache.nifi.minifi.c2.security.authorization.GrantedAuthorityAuthorizer.java

@Override
public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException {
    if (authentication == null) {
        throw new AuthorizationException("null authentication object provided.");
    }// w  ww .  j av a2s  .  c om

    if (!authentication.isAuthenticated()) {
        throw new AuthorizationException(authentication + " not authenticated.");
    }

    Set<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .collect(Collectors.toSet());

    String defaultAction = as(String.class, grantedAuthorityMap.getOrDefault(DEFAULT_ACTION, DENY));
    String path = uriInfo.getAbsolutePath().getPath();
    Map<String, Object> pathAuthorizations = as(Map.class, grantedAuthorityMap.get("Paths"));
    if (pathAuthorizations == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is "
                + defaultAction + " instead of allow");
    }

    Map<String, Object> pathAuthorization = as(Map.class, pathAuthorizations.get(path));
    if (pathAuthorization == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is "
                + defaultAction + " instead of allow");
    }
    defaultAction = as(String.class, pathAuthorization.getOrDefault(DEFAULT_ACTION, defaultAction));
    List<Map<String, Object>> actions = as(List.class, pathAuthorization.get("Actions"));
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    for (Map<String, Object> action : actions) {
        String ruleAction = as(String.class, action.get("Action"));
        if (ruleAction == null || !(ALLOW.equalsIgnoreCase(ruleAction) || DENY.equalsIgnoreCase(ruleAction))) {
            throw new AuthorizationException("Expected Action key of allow or deny for " + action);
        }
        String authorization = as(String.class, action.get("Authorization"));
        if (authorization != null && !authorities.contains(authorization)) {
            continue;
        }
        Map<String, Object> parameters = as(Map.class, action.get("Query Parameters"));
        if (parameters != null) {
            boolean foundParameterMismatch = false;
            for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
                Object value = parameter.getValue();
                if (value instanceof String) {
                    value = Arrays.asList((String) value);
                }
                if (!Objects.equals(queryParameters.get(parameter.getKey()), value)) {
                    foundParameterMismatch = true;
                    break;
                }
            }
            if (foundParameterMismatch) {
                continue;
            }
        }
        if (ALLOW.equalsIgnoreCase(ruleAction)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Action " + action + "matched which resulted in " + ruleAction);
            }
            return;
        } else {
            throw new AuthorizationException("Action " + action + " matched which resulted in " + ruleAction);
        }
    }
    if (ALLOW.equalsIgnoreCase(defaultAction)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found no matching actions so falling back to default action " + defaultAction);
        }
    } else {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is "
                + defaultAction + " instead of allow");
    }
}

From source file:se.uu.it.cs.recsys.semantic.ComputingDomainReasonerTest.java

/**
 * Test of getNarrowerDomainIds method, of class ComputingDomainReasoner.
 *///from  ww w  .j av a2  s . c o m
@Test
public void testGetNarrowerDomainIds() throws Exception {

    final Set<String> expResult = Stream
            .of("10003218", "10003269", "10003443", "10003444", "10003445", "10003446")
            .collect(Collectors.toSet());

    final String dataMiningId = "10003351";

    Set<String> result = this.reasoner.getNarrowerDomainIds(dataMiningId);
    assertEquals(expResult, result);
}

From source file:org.shredzone.cilla.core.repository.impl.CategoryDaoHibImpl.java

@Transactional(readOnly = true)
@Override/*from w ww  .  j  av a2  s. c  o  m*/
public Collection<Category> fetchRootCategoriesOfPage(Page page) {
    return page.getCategories().stream().map(this::fetchRootCategory).collect(Collectors.toSet());
}

From source file:io.gravitee.repository.redis.management.internal.impl.ApiKeyRedisRepositoryImpl.java

@Override
public Set<RedisApiKey> findByPlan(String plan) {
    Set<Object> keys = redisTemplate.opsForSet().members(REDIS_KEY + ":plan:" + plan);
    List<Object> apiKeyObjects = redisTemplate.opsForHash().multiGet(REDIS_KEY, keys);

    return apiKeyObjects.stream().map(apiKey -> convert(apiKey, RedisApiKey.class)).collect(Collectors.toSet());
}

From source file:com.athina.queue.manager.entity.JobQueueManager.java

public Set<JobKey> getJobKeysByGroup(String group) {
    try {//from  w w  w  . jav a  2s .  co m
        return quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(group)).stream()
                .map(JobKey::fromQuartzJobKey).collect(Collectors.toSet());
    } catch (SchedulerException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.trustedanalytics.serviceexposer.checker.CheckerJob.java

public void updateDeletedServiceInstances(String serviceType, Set<CcExtendedServiceInstance> serviceInstances) {
    Set<String> servicesGuids = serviceInstances.stream()
            .map(instance -> instance.getMetadata().getGuid().toString()).collect(Collectors.toSet());

    for (String serviceInstanceGuid : store.getSurplusServicesGuids(serviceType, servicesGuids)) {
        credentialsRetriver.deleteServiceInstance(serviceType, UUID.fromString(serviceInstanceGuid));
    }/*from   w  w w .j a v a 2  s.c om*/
}

From source file:fi.helsinki.opintoni.service.converter.SessionConverter.java

private Set<String> convertAuthoritiesToText(AppUser appUser) {
    return appUser.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
}

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

@GET
@Path("/find")
@Produces(MediaType.APPLICATION_JSON)/* w w w .java  2  s .co  m*/
@ApiOperation(value = "find", notes = "list all frequent patterns", responseContainer = "Map")
public Response listAllFrequentPatterns(@QueryParam("codes") Set<String> codes,
        @QueryParam("minSupport") Integer minSupport) {

    if (codes == null || codes.isEmpty()) {
        return Response.ok().build();
    }

    Set<Integer> courseIds = new HashSet<>();

    codes.forEach(code -> {
        Set<se.uu.it.cs.recsys.persistence.entity.Course> courses = this.courseRepository.findByCode(code);
        Set<Integer> ids = courses.stream().map(entry -> entry.getAutoGenId()).collect(Collectors.toSet());

        courseIds.addAll(ids);
    });

    Map<Set<Integer>, Integer> patterns = this.ruleMiner.getPatterns(courseIds, minSupport);

    Map<Set<Course>, Integer> output = convertToCourse(patterns);

    return Response.ok(output, MediaType.APPLICATION_JSON).build();

}