Example usage for java.util Set forEach

List of usage examples for java.util Set forEach

Introduction

In this page you can find the example usage for java.util Set forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:com.devicehive.handler.notification.NotificationSubscribeRequestHandler.java

@Override
public Response handle(Request request) {
    NotificationSubscribeRequest body = (NotificationSubscribeRequest) request.getBody();
    validate(body);/*w w  w .ja v a2  s  .  com*/

    Subscriber subscriber = new Subscriber(body.getSubscriptionId(), request.getReplyTo(),
            request.getCorrelationId());

    Set<Subscription> subscriptions = new HashSet<>();
    if (CollectionUtils.isEmpty(body.getNames())) {
        Subscription subscription = new Subscription(Action.NOTIFICATION_EVENT.name(), body.getDevice());
        subscriptions.add(subscription);
    } else {
        for (String name : body.getNames()) {
            Subscription subscription = new Subscription(Action.NOTIFICATION_EVENT.name(), body.getDevice(),
                    name);
            subscriptions.add(subscription);
        }
    }

    subscriptions.forEach(subscription -> eventBus.subscribe(subscriber, subscription));

    Collection<DeviceNotification> notifications = findNotifications(body.getDevice(), body.getNames(),
            body.getTimestamp());
    NotificationSubscribeResponse subscribeResponse = new NotificationSubscribeResponse(
            body.getSubscriptionId(), notifications);

    return Response.newBuilder().withBody(subscribeResponse).withLast(false)
            .withCorrelationId(request.getCorrelationId()).buildSuccess();
}

From source file:org.matonto.platform.config.impl.state.SimpleStateManager.java

@Override
public Map<Resource, Model> getStates(String username, String applicationId, Set<Resource> subjects)
        throws MatOntoException {
    User user = engineManager.retrieveUser(RdfEngine.COMPONENT_NAME, username)
            .orElseThrow(() -> new MatOntoException("User not found"));
    Optional<Application> app = applicationManager.getApplication(applicationId);
    Map<Resource, Model> states = new HashMap<>();
    try (RepositoryConnection conn = repository.getConnection()) {
        TupleQuery statesQuery = app.isPresent() ? conn.prepareTupleQuery(GET_APPLICATION_STATES_QUERY)
                : conn.prepareTupleQuery(GET_STATES_QUERY);
        app.ifPresent(application -> statesQuery.setBinding(APPLICATION_BINDING, application.getResource()));
        statesQuery.setBinding(USER_BINDING, user.getResource());
        TupleQueryResult results = statesQuery.evaluate();

        BindingSet bindings;/*w  ww .  ja  v a2  s. c  o  m*/
        while (results.hasNext() && (bindings = results.next()).getBindingNames().contains(STATE_ID_BINDING)) {
            Resource stateId = Bindings.requiredResource(bindings, STATE_ID_BINDING);
            bindings.getBinding(RESOURCES_BINDING).ifPresent(binding -> {
                Set<Resource> resources = Arrays
                        .stream(StringUtils.split(binding.getValue().stringValue(), ","))
                        .map(factory::createIRI).collect(Collectors.toSet());

                if (subjects.isEmpty() || resources.containsAll(subjects)) {
                    Model stateModel = modelFactory.createModel();
                    resources.forEach(
                            resource -> conn.getStatements(resource, null, null).forEach(stateModel::add));
                    states.put(stateId, stateModel);
                }
            });
        }
    }
    return states;
}

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:org.loklak.susi.SusiMind.java

/**
 * This is the core principle of creativity: being able to match a given input
 * with problem-solving knowledge.//from w w w . j  av  a2s  .c o  m
 * This method finds ideas (with a query instantiated rules) for a given query.
 * The rules are selected using a scoring system and pattern matching with the query.
 * Not only the most recent user query is considered for rule selection but also
 * previously requested queries and their answers to be able to set new rule selections
 * in the context of the previous conversation.
 * @param query the user input
 * @param previous_argument the latest conversation with the same user
 * @param maxcount the maximum number of ideas to return
 * @return an ordered list of ideas, first idea should be considered first.
 */
public List<SusiIdea> creativity(String query, SusiThought latest_thought, int maxcount) {
    // tokenize query to have hint for idea collection
    final List<SusiIdea> ideas = new ArrayList<>();
    this.reader.tokenizeSentence(query).forEach(token -> {
        Set<SusiRule> rule_for_category = this.ruletrigger.get(token.categorized);
        Set<SusiRule> rule_for_original = token.original.equals(token.categorized) ? null
                : this.ruletrigger.get(token.original);
        Set<SusiRule> r = new HashSet<>();
        if (rule_for_category != null)
            r.addAll(rule_for_category);
        if (rule_for_original != null)
            r.addAll(rule_for_original);
        r.forEach(rule -> ideas.add(new SusiIdea(rule).setIntent(token)));
    });

    //for (SusiIdea idea: ideas) System.out.println("idea.phrase-1:" + idea.getRule().getPhrases().toString());

    // add catchall rules always (those are the 'bad ideas')
    Collection<SusiRule> ca = this.ruletrigger.get(SusiRule.CATCHALL_KEY);
    if (ca != null)
        ca.forEach(rule -> ideas.add(new SusiIdea(rule)));

    // create list of all ideas that might apply
    TreeMap<Long, List<SusiIdea>> scored = new TreeMap<>();
    AtomicLong count = new AtomicLong(0);
    ideas.forEach(idea -> {
        int score = idea.getRule().getScore();
        long orderkey = Long.MAX_VALUE - ((long) score) * 1000L + count.incrementAndGet();
        List<SusiIdea> r = scored.get(orderkey);
        if (r == null) {
            r = new ArrayList<>();
            scored.put(orderkey, r);
        }
        r.add(idea);
    });

    // make a sorted list of all ideas
    ideas.clear();
    scored.values().forEach(r -> ideas.addAll(r));

    //for (SusiIdea idea: ideas) System.out.println("idea.phrase-2: score=" + idea.getRule().getScore() + " : " + idea.getRule().getPhrases().toString());

    // test ideas and collect those which match up to maxcount
    List<SusiIdea> plausibleIdeas = new ArrayList<>(Math.min(10, maxcount));
    for (SusiIdea idea : ideas) {
        SusiRule rule = idea.getRule();
        Collection<Matcher> m = rule.matcher(query);
        if (m.isEmpty())
            continue;
        // TODO: evaluate leading SEE flow commands right here as well
        plausibleIdeas.add(idea);
        if (plausibleIdeas.size() >= maxcount)
            break;
    }

    for (SusiIdea idea : plausibleIdeas)
        System.out.println("idea.phrase-3: score=" + idea.getRule().getScore() + " : "
                + idea.getRule().getPhrases().toString());

    return plausibleIdeas;
}

From source file:se.uu.it.cs.recsys.service.preference.ConstraintSolverPreferenceBuilder.java

private Set<Integer> getInterestedCourseIdCollection(Set<CourseSchedule> scheduleInfo) {

    Set<String> codes = this.apiPref.getInterestedCourseCodeCollection();

    final Set<Integer> totalIdSet = new HashSet<>();

    if (codes == null || codes.isEmpty()) {

        totalIdSet.addAll(this.courseRepository.findAll().stream().filter(inPlanYearPredicate(scheduleInfo))
                .map(c -> c.getAutoGenId()).collect(Collectors.toSet()));

    } else {/*from  w  w  w .  j  ava  2  s  .  co  m*/
        codes.forEach(code -> {
            Set<Integer> partIds = this.courseRepository.findByCode(code).stream()
                    .filter(inPlanYearPredicate(scheduleInfo)).map(c -> c.getAutoGenId())
                    .collect(Collectors.toSet());

            if (!partIds.isEmpty()) {
                totalIdSet.addAll(partIds);
            }
        });
    }

    return totalIdSet;
}

From source file:org.onosproject.ecord.carrierethernet.app.CarrierEthernetPacketNodeManager.java

private FlowRule addMetersToFlowRule(FlowRule flowRule, Set<DeviceMeterId> deviceMeterIdSet) {

    // FIXME: Refactor to use only single meter

    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder(flowRule.treatment());

    deviceMeterIdSet.forEach(deviceMeterId -> {
        tBuilder.meter(deviceMeterId.meterId()).transition(flowRule.treatment().tableTransition().tableId());
    });//from  w  w w .j ava2s  . c o  m

    return createFlowRule(flowRule.deviceId(), flowRule.priority(), flowRule.selector(), tBuilder.build(),
            flowRule.tableId());
}

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

private Set<Integer> getInterestCourseIdFromDomainIds() {

    Set<String> interestedDomainIdSet = this.userPref.getInterestedComputingDomainCollection();

    if (interestedDomainIdSet == null || interestedDomainIdSet.isEmpty()) {
        return Collections.emptySet();
    }//from ww w .  j a  v a  2s.  c o m

    LOGGER.debug("Interested domain id set {}", interestedDomainIdSet);

    Set<String> totalInterestedDomaindIdSet = new HashSet<>(interestedDomainIdSet);

    interestedDomainIdSet.forEach(domainId -> {
        try {
            Set<String> subDomains = this.computingDomainReasoner.getNarrowerDomainIds(domainId);

            if (!subDomains.isEmpty()) {
                totalInterestedDomaindIdSet.addAll(subDomains);
            }

            Set<String> relatedDomains = this.computingDomainReasoner.getRelatedDomainIds(domainId);

            if (!relatedDomains.isEmpty()) {
                totalInterestedDomaindIdSet.addAll(relatedDomains);
            }

        } catch (IOException ex) {
            LOGGER.error("Failed on domain reasoning for domain id {}", domainId, ex);
        }
    });

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

    totalInterestedDomaindIdSet.forEach(domainId -> {
        Set<CourseDomainRelevance> relevance = this.courseDomainRelevanceRepository.findByDomainId(domainId);

        relevance.forEach(entityRel -> {
            Integer courseId = entityRel.getCourseDomainRelevancePK().getCourseId();
            interestedCourseIdCollection.add(courseId);
        });
    });

    LOGGER.debug("Interested course id generated from computing domain id set {}",
            interestedCourseIdCollection);

    return interestedCourseIdCollection;
}

From source file:org.onosproject.imr.IntentMonitorAndRerouteManager.java

private Set<ElementId> connectedElements(Set<FilteredConnectPoint> cpSet) {
    Set<ElementId> connectedElem = new HashSet<>();
    cpSet.forEach(fcp -> {
        Set<Host> connectedHosts = hostService.getConnectedHosts(fcp.connectPoint());
        if (connectedHosts.size() == 0) {
            // In this case the end point is an ELEMENT without host connected
            connectedElem.add(fcp.connectPoint().elementId());
        } else {/* www .  ja va 2s.c  om*/
            // In this case we can have a set of hosts connected to that endpoint
            connectedElem.addAll(connectedHosts.stream().map(Host::id).collect(Collectors.toSet()));
        }
    });
    return connectedElem;
}

From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogResource.java

private Response addRoleUsers(Long roleId, Set<Long> userIds) {
    List<UserRole> userRoles = new ArrayList<>();
    userIds.forEach(userId -> {
        userRoles.add(catalogService.addUserRole(userId, roleId));
    });/*from w w w.  j a va2s.c om*/
    return WSUtils.respondEntities(userRoles, OK);
}

From source file:org.codice.ddf.catalog.ui.security.accesscontrol.AccessControlPreQueryPlugin.java

private Filter createSecurityPolicySubset(String identifier, Set<String> groups) {
    final ImmutableList.Builder<Filter> policyBranch = ImmutableList.builder();
    policyBranch.add(isEqualToText(Core.METACARD_OWNER, identifier));
    policyBranch.add(isEqualToText(Core.METACARD_TAGS, SYSTEM_TEMPLATE));

    policyBranch.add(isEqualToText(Security.ACCESS_INDIVIDUALS, identifier));
    policyBranch.add(isEqualToText(Security.ACCESS_INDIVIDUALS_READ, identifier));
    policyBranch.add(isEqualToText(Security.ACCESS_ADMINISTRATORS, identifier));

    groups.forEach(group -> policyBranch.add(isEqualToText(Security.ACCESS_GROUPS, group)));
    groups.forEach(group -> policyBranch.add(isEqualToText(Security.ACCESS_GROUPS_READ, group)));

    return filterBuilder.anyOf(policyBranch.build());
}