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.NotificationUnsubscribeRequestHandler.java

@Override
public Response handle(Request request) {
    NotificationUnsubscribeRequest body = (NotificationUnsubscribeRequest) request.getBody();
    validate(body);//from w ww .  j a v  a2s  .  c o  m

    if (body.getSubscriptionId() != null) {
        Subscriber subscriber = new Subscriber(body.getSubscriptionId(), request.getReplyTo(),
                request.getCorrelationId());
        eventBus.unsubscribe(subscriber);

        NotificationUnsubscribeResponse unsubscribeResponse = new NotificationUnsubscribeResponse(
                body.getSubscriptionId(), null);

        return Response.newBuilder().withBody(unsubscribeResponse).withLast(false)
                .withCorrelationId(request.getCorrelationId()).buildSuccess();
    } else if (body.getDeviceGuids() != null) {
        Set<Subscription> subscriptions = new HashSet<>();
        Set<Subscriber> subscribers = new HashSet<>();

        for (String name : body.getDeviceGuids()) {
            Subscription subscription = new Subscription(Action.NOTIFICATION_EVENT.name(), name);
            subscriptions.add(subscription);
        }

        subscriptions.forEach(subscription -> subscribers.addAll(eventBus.getSubscribers(subscription)));
        subscribers.forEach(subscriber -> eventBus.unsubscribe(subscriber));

        NotificationUnsubscribeResponse unsubscribeResponse = new NotificationUnsubscribeResponse(null,
                body.getDeviceGuids());
        return Response.newBuilder().withBody(unsubscribeResponse).withLast(false)
                .withCorrelationId(request.getCorrelationId()).buildSuccess();
    } else {
        throw new IllegalArgumentException("Both subscription id and device guids are null");
    }
}

From source file:org.eclipse.smarthome.core.thing.internal.CommunicationManager.java

protected void removeProfileFactory(ProfileFactory profileFactory) {
    Set<ChannelUID> channelUIDs = this.profileFactories.remove(profileFactory);
    synchronized (profiles) {
        channelUIDs.forEach(channelUID -> profiles.remove(channelUID));
    }/*  ww  w. ja  v  a2s.  c  o m*/
}

From source file:org.onosproject.net.resource.impl.LabelAllocator.java

/**
 * Allocates labels and associates them to links.
 *
 * @param links the links where labels will be allocated
 * @param id the intent Id//from   w w  w .j a va2s. c  om
 * @param type the encapsulation type
 * @return the list of links and associated labels
 */
public Map<LinkKey, Identifier<?>> assignLabelToLinks(Set<Link> links, IntentId id, EncapsulationType type) {

    Set<LinkKey> linkRequest = Sets.newHashSet();

    links.forEach(link -> {
        linkRequest.add(LinkKey.linkKey(link));
    });

    Map<LinkKey, Identifier<?>> availableIds = findAvailableIDs(linkRequest, type);
    if (availableIds.isEmpty()) {
        return Collections.emptyMap();
    }

    Set<Resource> resources = availableIds.entrySet().stream().flatMap(x -> Stream.of(
            Resources.discrete(x.getKey().src().deviceId(), x.getKey().src().port(), x.getValue()).resource(),
            Resources.discrete(x.getKey().dst().deviceId(), x.getKey().dst().port(), x.getValue()).resource()))
            .collect(Collectors.toSet());

    List<ResourceAllocation> allocations = resourceService.allocate(id, ImmutableList.copyOf(resources));

    if (allocations.isEmpty()) {
        return Collections.emptyMap();
    }

    return ImmutableMap.copyOf(availableIds);
}

From source file:org.codice.ddf.catalog.ui.query.monitor.impl.SubscriptionsPersistentStoreImpl.java

@SuppressWarnings("unchecked")
@Override/* w  w  w .  j a v  a 2  s .c  om*/
public void addEmails(String id, Set<String> emails) {
    notBlank(id, "id must be non-blank");
    notNull(emails, "emails must be non-null");
    emails.forEach(email -> notBlank(email, "emails in set must be non-blank"));

    LOCK.lock();
    try {
        List<Map<String, Object>> results = get(id);

        if (!results.isEmpty()) {
            PersistentItem item = convert(results.get(0));

            if (item.containsKey(EMAIL_PROPERTY + PersistentItem.TEXT_SUFFIX)) {
                Set<String> newValue = new HashSet<>(emails);
                Object value = item.get(EMAIL_PROPERTY + PersistentItem.TEXT_SUFFIX);
                if (value instanceof String) {
                    newValue.add((String) value);
                } else if (value instanceof Set) {
                    ((Set) value).stream().filter(String.class::isInstance)
                            .forEach(obj -> newValue.add((String) obj));
                }
                item.addProperty(EMAIL_PROPERTY, newValue);
            } else {
                item.addProperty(EMAIL_PROPERTY, emails);
            }
            persistentStore.add(SUBSCRIPTIONS_TYPE, item);
        } else {
            PersistentItem persistentItem = new PersistentItem();
            persistentItem.addIdProperty(id);
            persistentItem.addProperty(EMAIL_PROPERTY, emails);
            persistentStore.add(SUBSCRIPTIONS_TYPE, persistentItem);
        }

    } catch (PersistenceException e) {
        LOGGER.warn("unable to add emails to workspace: workspaceId={} emails={}", id, emails, e);
    } finally {
        LOCK.unlock();
    }
}

From source file:io.gravitee.management.service.impl.ApplicationServiceImpl.java

@Override
public void delete(String applicationId) {
    try {//from   w ww  .j a v  a  2  s.  c  om
        LOGGER.debug("Delete application {}", applicationId);
        Set<ApiKey> keys = apiKeyRepository.findByApplication(applicationId);
        keys.forEach(apiKey -> {
            try {
                apiKeyRepository.delete(apiKey.getKey());
            } catch (TechnicalException e) {
                LOGGER.error("An error occurs while deleting API Key {}", apiKey.getKey(), e);
            }
        });

        applicationRepository.delete(applicationId);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to delete application {}", applicationId, ex);
        throw new TechnicalManagementException(
                "An error occurs while trying to delete application " + applicationId, ex);
    }
}

From source file:org.fenixedu.academic.thesis.ui.service.StudentCandidaciesService.java

public Map<ThesisProposalsConfiguration, List<StudentThesisCandidacy>> getCandidaciesByConfig(Student student) {

    Set<ThesisProposalsConfiguration> configs = getStudentConfigurations(student);

    HashMap<ThesisProposalsConfiguration, List<StudentThesisCandidacy>> candidaciesByConfig = new HashMap<ThesisProposalsConfiguration, List<StudentThesisCandidacy>>();

    configs.forEach(config -> {
        List<StudentThesisCandidacy> studentCandidacies = config.getThesisProposalSet().stream()
                .flatMap(proposal -> proposal.getStudentThesisCandidacySet().stream())
                .filter(candidacy -> candidacy.getRegistration().getStudent().equals(student)).distinct()
                .sorted(StudentThesisCandidacy.COMPARATOR_BY_PREFERENCE_NUMBER).collect(Collectors.toList());
        candidaciesByConfig.put(config, studentCandidacies);
    });/*from w w w .  jav  a  2s .  c om*/

    return candidaciesByConfig;
}

From source file:com.uber.hoodie.common.table.view.HoodieTableFileSystemView.java

/**
 * Adds the provided statuses into the file system view, and also caches it inside this object.
 *
 * @param statuses//from  w w w  .  ja v a 2s. co m
 * @return
 */
private List<HoodieFileGroup> addFilesToView(FileStatus[] statuses) {
    Map<Pair<String, String>, List<HoodieDataFile>> dataFiles = convertFileStatusesToDataFiles(statuses)
            .collect(Collectors.groupingBy((dataFile) -> {
                String partitionPathStr = FSUtils.getRelativePartitionPath(new Path(metaClient.getBasePath()),
                        dataFile.getFileStatus().getPath().getParent());
                return Pair.of(partitionPathStr, dataFile.getFileId());
            }));
    Map<Pair<String, String>, List<HoodieLogFile>> logFiles = convertFileStatusesToLogFiles(statuses)
            .collect(Collectors.groupingBy((logFile) -> {
                String partitionPathStr = FSUtils.getRelativePartitionPath(new Path(metaClient.getBasePath()),
                        logFile.getPath().getParent());
                return Pair.of(partitionPathStr, logFile.getFileId());
            }));

    Set<Pair<String, String>> fileIdSet = new HashSet<>(dataFiles.keySet());
    fileIdSet.addAll(logFiles.keySet());

    List<HoodieFileGroup> fileGroups = new ArrayList<>();
    fileIdSet.forEach(pair -> {
        HoodieFileGroup group = new HoodieFileGroup(pair.getKey(), pair.getValue(), visibleActiveTimeline);
        if (dataFiles.containsKey(pair)) {
            dataFiles.get(pair).forEach(dataFile -> group.addDataFile(dataFile));
        }
        if (logFiles.containsKey(pair)) {
            logFiles.get(pair).forEach(logFile -> group.addLogFile(logFile));
        }
        fileGroups.add(group);
    });

    // add to the cache.
    fileGroups.forEach(group -> {
        fileGroupMap.put(group.getId(), group);
        if (!partitionToFileGroupsMap.containsKey(group.getPartitionPath())) {
            partitionToFileGroupsMap.put(group.getPartitionPath(), new ArrayList<>());
        }
        partitionToFileGroupsMap.get(group.getPartitionPath()).add(group);
    });

    return fileGroups;
}

From source file:fi.vm.kapa.identification.service.ServiceProvider.java

/** The identifier type must be explicitly informed to Proxy since it can't know it without
 * excessive checks, note that this relies on the Shibboleth SP's configuration which must be
 * identical to what the shared API is using. This method returns true once first matching
 * identifier type has been found//from w  w  w .  j av a 2 s  . c om
 */
private boolean checkAndParseIdentifierAndData(final MultivaluedMap<String, String> headers,
        Map<String, String> sessionData) {
    for (int i = 0; i < identifierTypes.length; i++) {
        if (StringUtils.isNotBlank(headers.getFirst(identifierTypes[i]))) {
            Set<String> headerNames = headers.keySet();

            logger.debug("--" + Identifier.typeKey + " <--> " + Identifier.Types.values()[i]);

            sessionData.put(Identifier.typeKey, "" + Identifier.Types.values()[i]);

            headerNames.forEach(headerName -> {
                String headerValue = headers.getFirst(headerName);
                /* All session data what the actual IdP has sent
                 * must be delivered to Proxy since the SP doesn't
                 * do anything with the data, it just delivers them
                 */
                if (StringUtils.isNotBlank(headerValue)) {
                    sessionData.put(headerName, headerValue);
                }
            });
            return true;
        }
    }

    return false;
}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.AbstractHandler.java

public Observable<T> getBySet(Set<K> keys) {

    return Observable.create(observer -> {

        try {/*w  ww  .j a  va  2  s  .  c om*/

            keys.forEach(

                    key -> {

                        T item = getDatastoreCache().get(key);

                        if (Objects.nonNull(item))
                            observer.onNext(item);

                    });

            observer.onCompleted();

        } catch (Exception e) {
            observer.onError(e);
        }

    });

}

From source file:ddf.catalog.metacard.duplication.DuplicationValidator.java

private Optional<MetacardValidationReport> getReport(final Set<ValidationViolation> violations) {
    if (CollectionUtils.isNotEmpty(violations)) {
        final MetacardValidationReportImpl report = new MetacardValidationReportImpl();
        violations.forEach(report::addMetacardViolation);
        return Optional.of(report);
    }/*from  w  w  w  .  j  av a  2 s.  c  o  m*/

    return Optional.empty();
}