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:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

private void updateStocksAndQuotesFromYahoo(Set<StockProduct> askedContent) {
    if (askedContent.isEmpty()) {
        return;/*from   w w  w .  ja  v a 2s  . co m*/
    }

    Set<StockProduct> recentlyUpdated = askedContent.stream()
            .filter(t -> t.getLastUpdate() != null && DateUtil.isRecent(t.getLastUpdate(), 1))
            .collect(Collectors.toSet());

    if (askedContent.size() != recentlyUpdated.size()) {

        String guid = AuthenticationUtil.getPrincipal().getUsername();

        String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
        ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
        Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

        if (connection != null) {
            askedContent.removeAll(recentlyUpdated);

            Map<String, StockProduct> updatableTickers = askedContent.stream()
                    .collect(Collectors.toMap(StockProduct::getId, Function.identity()));

            List<YahooQuote> yahooQuotes = connection.getApi().financialOperations()
                    .getYahooQuotes(new ArrayList<String>(updatableTickers.keySet()), token);

            Set<StockProduct> updatableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isNotBlank(yq.getExchange()))
                    .filter(yq -> updatableTickers.get(yq.getId()) != null).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!updatableProducts.isEmpty()) {
                stockProductRepository.save(updatableProducts);
            }

            //This job below should decrease with the time
            Set<StockProduct> removableProducts = yahooQuotes.stream()
                    .filter(yq -> StringUtils.isBlank(yq.getExchange())).map(yq -> {
                        StockQuote sq = new StockQuote(yq, updatableTickers.get((yq.getId())));
                        return syncProduct(updatableTickers.get((yq.getId())), sq);
                    }).collect(Collectors.toSet());

            if (!removableProducts.isEmpty()) {
                stockProductRepository.delete(removableProducts);
            }
        }
    }
}

From source file:com.netflix.spinnaker.front50.model.SwiftStorageService.java

@Override
public <T extends Timestamped> Collection<T> loadObjectsWithPrefix(ObjectType objectType, String prefix,
        int maxResults) {
    List<? extends SwiftObject> objects = getSwift().objects().list(containerName,
            ObjectListOptions.create().path(objectType.group).startsWith(prefix).limit(maxResults));
    return objects.stream().map(obj -> {
        T item = deserialize(obj, (Class<T>) objectType.clazz);
        item.setLastModified(obj.getLastModified().getTime());
        return item;
    }).collect(Collectors.toSet());
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.JCloudsProvider.java

@Override
public Set<Image> getAllImages(Infrastructure infrastructure) {
    return getComputeServiceFromInfastructure(infrastructure).listImages().stream()
            .map(it -> Image.builder().id(it.getId()).name(it.getName()).build()).collect(Collectors.toSet());

}

From source file:org.ow2.proactive.connector.iaas.service.InstanceService.java

public Set<Instance> getInstanceByTag(String infrastructureId, String instanceTag) {
    return getAllInstances(infrastructureId).stream().filter(instance -> instance.getTag().equals(instanceTag))
            .collect(Collectors.toSet());
}

From source file:com.haulmont.cuba.security.app.EntityLog.java

protected void computeChanges(EntityLogItem itemToSave, List<EntityLogItem> sameEntityList) {
    Set<String> allAttributes = sameEntityList.stream()
            .flatMap(entityLogItem -> entityLogItem.getAttributes().stream().map(EntityLogAttr::getName))
            .collect(Collectors.toSet());

    for (String attributeName : allAttributes) {
        // old value from the first item
        sameEntityList.get(0).getAttributes().stream()
                .filter(entityLogAttr -> entityLogAttr.getName().equals(attributeName)).findFirst()
                .ifPresent(entityLogAttr -> setAttributeOldValue(entityLogAttr, itemToSave));
        // new value from the last item
        sameEntityList.get(sameEntityList.size() - 1).getAttributes().stream()
                .filter(entityLogAttr -> entityLogAttr.getName().equals(attributeName)).findFirst()
                .ifPresent(entityLogAttr -> setAttributeNewValue(entityLogAttr, itemToSave));
    }/*  w w  w . j a  v a 2 s . co m*/

    Properties properties = new Properties();

    for (EntityLogAttr attr : itemToSave.getAttributes()) {
        properties.setProperty(attr.getName(), attr.getValue());
        if (attr.getValueId() != null) {
            properties.setProperty(attr.getName() + EntityLogAttr.VALUE_ID_SUFFIX, attr.getValueId());
        }
        if (attr.getOldValue() != null) {
            properties.setProperty(attr.getName() + EntityLogAttr.OLD_VALUE_SUFFIX, attr.getOldValue());
        }
        if (attr.getOldValueId() != null) {
            properties.setProperty(attr.getName() + EntityLogAttr.OLD_VALUE_ID_SUFFIX, attr.getOldValueId());
        }
        if (attr.getMessagesPack() != null) {
            properties.setProperty(attr.getName() + EntityLogAttr.MP_SUFFIX, attr.getMessagesPack());
        }
    }

    if (itemToSave.getType() == EntityLogItem.Type.MODIFY) {
        sameEntityList.stream().filter(entityLogItem -> entityLogItem.getType() == EntityLogItem.Type.CREATE)
                .findFirst().ifPresent(entityLogItem -> itemToSave.setType(EntityLogItem.Type.CREATE));
    }
    itemToSave.setChanges(getChanges(properties));
}

From source file:com.bekioui.jaxrs.server.core.NettyServer.java

private void resources(ResteasyDeployment deployment) {
    Collection<Object> resources = applicationContext.getBeansWithAnnotation(Path.class).values();

    if (swaggerEnabled) {
        List<? extends ResourceDescriptor> resourceDescriptors = swaggerResourceDescriptors != null
                ? swaggerResourceDescriptors
                : deploymentResourceDescriptors;
        Set<Class<?>> classes = resources.stream().filter(resourceFilter.apply(resourceDescriptors))
                .map(Object::getClass).collect(Collectors.toSet());
        SwaggerResource swaggerRessource = new SwaggerResource(swaggerSupplier.get(), classes);
        deployment.getResources().add(swaggerRessource);
        deployment.getProviders().add(new SwaggerSerializers());
    }/*from  w ww. j av  a  2  s.  c  o m*/

    List<Object> deploymentResources = resources.stream()
            .filter(resourceFilter.apply(deploymentResourceDescriptors)).collect(Collectors.toList());
    deployment.getResources().addAll(deploymentResources);
}

From source file:org.fenixedu.academic.thesis.ui.controller.StudentCandidaciesController.java

@RequestMapping(value = "", method = RequestMethod.GET)
public String listProposals(Model model) {

    Student student = Authenticate.getUser().getPerson().getStudent();

    Set<ThesisProposalsConfiguration> suggestedConfigs = service.getSuggestedConfigs(student);

    HashMap<Registration, Set<ThesisProposal>> proposalsByReg = service.getOpenProposalsByReg(student);

    Map<ThesisProposalsConfiguration, List<StudentThesisCandidacy>> candidaciesByConfig = service
            .getCandidaciesByConfig(student);

    int proposalsSize = proposalsByReg.values().stream().map(Set::size).reduce(0, (a, b) -> a + b);
    int candidaciesSize = candidaciesByConfig.values().stream().map(List::size).reduce(0, (a, b) -> a + b);

    if (participantLabelService != null) {
        model.addAttribute("participantLabelService", participantLabelService);
    }/*www . j a  va2  s .c  o m*/

    model.addAttribute("suggestedConfigs", suggestedConfigs);
    model.addAttribute("proposalsSize", proposalsSize);
    model.addAttribute("candidaciesSize", candidaciesSize);
    model.addAttribute("candidaciesByConfig", candidaciesByConfig);
    model.addAttribute("proposalsByReg", proposalsByReg);

    Map<ThesisProposal, Integer> applicationCountByProposalConfig = candidaciesByConfig.values().stream()
            .flatMap(List::stream).collect(Collectors.toMap(StudentThesisCandidacy::getThesisProposal,
                    c -> c.getThesisProposal().getStudentThesisCandidacySet().size()));
    model.addAttribute("applicationCountByProposalConfig", applicationCountByProposalConfig);

    Map<ThesisProposal, Integer> applicationCountByProposalReg = proposalsByReg.values().stream()
            .flatMap(Set::stream)
            .collect(Collectors.toMap(tp -> tp, tp -> tp.getStudentThesisCandidacySet().size()));
    model.addAttribute("applicationCountByProposalReg", applicationCountByProposalReg);

    Set<ThesisProposal> acceptedProposals = proposalsByReg.values().stream().flatMap(Set::stream)
            .flatMap(tp -> tp.getStudentThesisCandidacySet().stream())
            .filter(candidacy -> candidacy.getAcceptedByAdvisor())
            .map(candidacy -> candidacy.getThesisProposal()).collect(Collectors.toSet());
    model.addAttribute("acceptedProposals", acceptedProposals);

    return "studentCandidacies/list";
}

From source file:com.thinkbiganalytics.security.rest.controller.AccessControlController.java

@GET
@Path("{name}/allowed")
@Produces(MediaType.APPLICATION_JSON)//ww w  . j  av a2 s .  co m
@ApiOperation("Gets the list of allowed actions for a principal.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class),
        @ApiResponse(code = 404, message = "The given name was not found.", response = RestResponseStatus.class) })
public ActionGroup getAllowedActions(@PathParam("name") String moduleName,
        @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) {

    Set<? extends Principal> users = Arrays.stream(this.actionsTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.actionsTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());
    Principal[] principals = Stream.concat(users.stream(), groups.stream()).toArray(Principal[]::new);

    // Retrieve the allowed actions by executing the query as the specified user/groups 
    return metadata.read(() -> {
        return actionsProvider.getAllowedActions(moduleName)
                .map(this.actionsTransform.toActionGroup(AllowedActions.SERVICES))
                .orElseThrow(() -> new WebApplicationException("The available service actions were not found",
                        Status.NOT_FOUND));
    }, principals);
}

From source file:io.gravitee.repository.mongodb.management.MongoEventRepository.java

private Set<Event> mapEvents(Collection<EventMongo> events) {
    return events.stream().map(this::mapEvent).collect(Collectors.toSet());
}

From source file:com.livingobjects.wisdom.swagger.SwaggerDocController.java

/**
 * Notified when a bundle is loaded with a given Swagger-Doc header in its manifest. It must contains the header to be loaded by SwaggerDocController.
 * Read the swagger file contained in the header. Serves all the base routes defined in the documentation to display the documentation.
 *
 * @param bundle      The new loaded bundle.
 * @param swaggerFile The swaggerFile path in the manifest.
 *//*from  w  w w.j av a2s .  c  om*/
void onBundleArrival(Bundle bundle, String swaggerFile) {
    try {
        try (InputStream in = bundle.getResource(swaggerFile).openStream()) {
            if (in != null) {
                Wizard wizard = new Wizard();
                try {
                    ApiSpecification apiSpecification = wizard.generateSpecification(in);
                    Set<String> baseUris = apiSpecification.resources.stream().map(r -> {
                        String[] uris = r.uri.split("/");
                        if (uris.length > 2) {
                            return uris[1];
                        } else {
                            return null;
                        }
                    }).filter(s -> s != null).collect(Collectors.toSet());
                    ImmutableSet<String> immutableBaseUris = ImmutableSet.of();
                    BundleApiDoc apiDoc = new BundleApiDoc(immutableBaseUris, swaggerFile, apiSpecification,
                            bundle);
                    for (String baseUri : baseUris) {
                        baseUriMap.put(baseUri, apiDoc);
                    }
                    bundleBaseUris.put(bundle.getSymbolicName(), immutableBaseUris);
                } catch (SwaggerException e) {
                    logger().error("Swagger documentation '{}' for bundle '{}' is invalid.", swaggerFile,
                            bundle.getSymbolicName(), e);
                }
            } else {
                logger().error(
                        "Swagger documentation '{}' not found for bundle '{}'. Check Swagger-Doc attribute in manifest.",
                        swaggerFile, bundle.getSymbolicName());
            }
        } catch (IOException e) {
            logger().error(
                    "Swagger documentation '{}' not found for bundle '{}'. Check Swagger-Doc attribute in manifest.",
                    swaggerFile, bundle.getSymbolicName(), e);
        }
    } catch (IllegalArgumentException e) {
        logger().error(
                "The Swagger-Doc attribute in manifest of bundle '{}' is invalid. It must be of the form 'uri:yaml-resource-path'.",
                bundle.getSymbolicName());
    }
}