Example usage for java.util Collection forEach

List of usage examples for java.util Collection forEach

Introduction

In this page you can find the example usage for java.util Collection 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.hortonworks.streamline.streams.service.NamespaceCatalogResource.java

@POST
@Path("/namespaces/{id}/mapping/bulk")
@Timed// ww w. ja v  a 2 s  .co  m
public Response setServicesToClusterInNamespace(@PathParam("id") Long namespaceId,
        List<NamespaceServiceClusterMapping> mappings, @Context SecurityContext securityContext) {
    SecurityUtil.checkRoleOrPermissions(authorizer, securityContext, Roles.ROLE_ENVIRONMENT_SUPER_ADMIN,
            Namespace.NAMESPACE, namespaceId, WRITE);
    Namespace namespace = environmentService.getNamespace(namespaceId);
    if (namespace == null) {
        throw EntityNotFoundException.byId(namespaceId.toString());
    }

    String streamingEngine = namespace.getStreamingEngine();
    String timeSeriesDB = namespace.getTimeSeriesDB();

    Collection<NamespaceServiceClusterMapping> existing = environmentService
            .listServiceClusterMapping(namespaceId);
    Optional<NamespaceServiceClusterMapping> existingStreamingEngine = existing.stream()
            .filter(m -> m.getServiceName().equals(streamingEngine))
            // this should be only one
            .findFirst();

    // indicates that mapping of streaming engine has been changed or removed
    if (existingStreamingEngine.isPresent() && !mappings.contains(existingStreamingEngine.get())) {
        assertNoTopologyReferringNamespaceIsRunning(namespaceId,
                WSUtils.getUserFromSecurityContext(securityContext));
    }

    // we're OK to just check with new mappings since we will remove existing mappings
    assertServiceIsUnique(mappings, streamingEngine);
    assertServiceIsUnique(mappings, timeSeriesDB);

    // remove any existing mapping for (namespace, service name) pairs
    Collection<NamespaceServiceClusterMapping> existingMappings = environmentService
            .listServiceClusterMapping(namespaceId);
    if (existingMappings != null) {
        existingMappings.forEach(m -> environmentService.removeServiceClusterMapping(m.getNamespaceId(),
                m.getServiceName(), m.getClusterId()));
    }

    List<NamespaceServiceClusterMapping> newMappings = mappings.stream()
            .map(environmentService::addOrUpdateServiceClusterMapping).collect(toList());

    return WSUtils.respondEntities(newMappings, CREATED);
}

From source file:org.onosproject.drivers.lumentum.LumentumFlowRuleProgrammable.java

@Override
public Collection<FlowRule> applyFlowRules(Collection<FlowRule> rules) {
    try {/*from  w ww. java  2s .c  om*/
        snmp = new LumentumSnmpDevice(data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
    }

    // Line ports
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream().map(p -> p.number())
            .collect(Collectors.toList());

    // Apply the valid rules on the device
    Collection<FlowRule> added = rules.stream().map(r -> new CrossConnectFlowRule(r, linePorts))
            .filter(xc -> installCrossConnect(xc)).collect(Collectors.toList());

    // Cache the cookie/priority
    CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
    added.forEach(xc -> cache.set(Objects.hash(data().deviceId(), xc.selector(), xc.treatment()), xc.id(),
            xc.priority()));

    return added;
}

From source file:ai.susi.mind.SusiMind.java

/**
 * This is the core principle of creativity: being able to match a given input
 * with problem-solving knowledge.//  w ww.j a  v  a 2s  .co  m
 * This method finds ideas (with a query instantiated skills) for a given query.
 * The skills are selected using a scoring system and pattern matching with the query.
 * Not only the most recent user query is considered for skill selection but also
 * previously requested queries and their answers to be able to set new skill 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<SusiSkill> skill_for_category = this.skilltrigger.get(token.categorized);
        Set<SusiSkill> skill_for_original = token.original.equals(token.categorized) ? null
                : this.skilltrigger.get(token.original);
        Set<SusiSkill> r = new HashSet<>();
        if (skill_for_category != null)
            r.addAll(skill_for_category);
        if (skill_for_original != null)
            r.addAll(skill_for_original);
        r.forEach(skill -> ideas.add(new SusiIdea(skill).setIntent(token)));
    });

    for (SusiIdea idea : ideas)
        DAO.log("idea.phrase-1: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // add catchall skills always (those are the 'bad ideas')
    Collection<SusiSkill> ca = this.skilltrigger.get(SusiSkill.CATCHALL_KEY);
    if (ca != null)
        ca.forEach(skill -> ideas.add(new SusiIdea(skill)));

    // 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.getSkill().getScore().score;
        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)
        DAO.log("idea.phrase-2: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // test ideas and collect those which match up to maxcount
    List<SusiIdea> plausibleIdeas = new ArrayList<>(Math.min(10, maxcount));
    for (SusiIdea idea : ideas) {
        SusiSkill skill = idea.getSkill();
        Collection<Matcher> m = skill.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) {
        DAO.log("idea.phrase-3: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());
        DAO.log("idea.phrase-3:   log=" + idea.getSkill().getScore().log);
    }

    return plausibleIdeas;
}

From source file:org.onosproject.drivers.lumentum.LumentumFlowRuleProgrammable.java

@Override
public Collection<FlowRule> removeFlowRules(Collection<FlowRule> rules) {
    try {//from  w  w w .  j  av  a2s .  co  m
        snmp = new LumentumSnmpDevice(data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
    }

    // Line ports
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream().map(p -> p.number())
            .collect(Collectors.toList());

    // Apply the valid rules on the device
    Collection<FlowRule> removed = rules.stream().map(r -> new CrossConnectFlowRule(r, linePorts))
            .filter(xc -> removeCrossConnect(xc)).collect(Collectors.toList());

    // Remove flow rule from cache
    CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
    removed.forEach(xc -> cache.remove(Objects.hash(data().deviceId(), xc.selector(), xc.treatment())));

    return removed;
}

From source file:org.apache.bookkeeper.stream.storage.impl.TestStorageContainerStoreImpl.java

@SuppressWarnings("unchecked")
@Before/*w w w  .  j a  v  a  2 s. c om*/
public void setUp() throws Exception {
    Endpoint endpoint = createEndpoint("127.0.0.1", 0);

    // create the client manager
    MVCCStoreFactory storeFactory = mock(MVCCStoreFactory.class);
    MVCCAsyncStore<byte[], byte[]> store = mock(MVCCAsyncStore.class);
    when(storeFactory.openStore(anyLong(), anyLong(), anyLong())).thenReturn(FutureUtils.value(store));
    when(storeFactory.closeStores(anyLong())).thenReturn(FutureUtils.Void());

    RangeStoreServiceFactory rangeStoreServiceFactory = mock(RangeStoreServiceFactory.class);
    mockRangeStoreService = mock(RangeStoreService.class);
    when(mockRangeStoreService.start()).thenReturn(FutureUtils.Void());
    when(mockRangeStoreService.stop()).thenReturn(FutureUtils.Void());
    when(rangeStoreServiceFactory.createService(anyLong())).thenReturn(mockRangeStoreService);

    rangeStore = new StorageContainerStoreImpl(storageConf,
            (storeConf, rgRegistry) -> new LocalStorageContainerManager(endpoint, storeConf, rgRegistry, 2),
            new RangeStoreContainerServiceFactoryImpl(rangeStoreServiceFactory), null,
            NullStatsLogger.INSTANCE);

    rangeStore.start();

    final String serverName = "test-server";

    Collection<ServerServiceDefinition> grpcServices = GrpcServices.create(null);
    ProxyHandlerRegistry.Builder registryBuilder = ProxyHandlerRegistry.newBuilder();
    grpcServices.forEach(service -> registryBuilder.addService(service));
    ProxyHandlerRegistry registry = registryBuilder.setChannelFinder(rangeStore).build();
    server = InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(registry).directExecutor()
            .build().start();

    channel = InProcessChannelBuilder.forName(serverName).usePlaintext().build();

    scId = ThreadLocalRandom.current().nextInt(2);

    // intercept the channel with storage container information.
    channel = ClientInterceptors.intercept(channel, new StorageContainerClientInterceptor(scId));

    tableService = TableServiceGrpc.newFutureStub(channel);
    metaRangeService = MetaRangeServiceGrpc.newFutureStub(channel);
    rootRangeService = RootRangeServiceGrpc.newFutureStub(channel);
}

From source file:org.apache.syncope.client.console.wicket.markup.html.form.AjaxPalettePanel.java

private void initialize(final IModel<List<T>> model, final Builder<T> builder) {
    setOutputMarkupId(true);/*  w  w  w  .ja v  a 2s  . c  o m*/

    this.palette = new NonI18nPalette<T>("paletteField", model, choicesModel, builder.renderer, 8,
            builder.allowOrder, builder.allowMoveAll) {

        private static final long serialVersionUID = -3074655279011678437L;

        @Override
        protected Component newAvailableHeader(final String componentId) {
            return new Label(componentId, new ResourceModel("palette.available", builder.availableLabel));
        }

        @Override
        protected Component newSelectedHeader(final String componentId) {
            return new Label(componentId, new ResourceModel("palette.selected", builder.selectedLabel));
        }

        @Override
        protected Recorder<T> newRecorderComponent() {
            return new Recorder<T>("recorder", this) {

                private static final long serialVersionUID = -9169109967480083523L;

                @Override
                public List<T> getUnselectedList() {
                    final IChoiceRenderer<? super T> renderer = getPalette().getChoiceRenderer();
                    final Collection<? extends T> choices = getPalette().getChoices();
                    final List<T> unselected = new ArrayList<>(choices.size());
                    final List<String> ids = Arrays.asList(getValue().split(","));

                    choices.forEach(choice -> {
                        final String choiceId = renderer.getIdValue(choice, 0);
                        if (!ids.contains(choiceId)) {
                            unselected.add(choice);
                        }
                    });

                    return unselected;
                }

                @Override
                public List<T> getSelectedList() {
                    final IChoiceRenderer<? super T> renderer = getPalette().getChoiceRenderer();
                    final Collection<? extends T> choices = getPalette().getChoices();
                    final List<T> selected = new ArrayList<>(choices.size());

                    // reduce number of method calls by building a lookup table
                    final Map<T, String> idForChoice = new HashMap<>(choices.size());
                    choices.forEach(choice -> {
                        idForChoice.put(choice, renderer.getIdValue(choice, 0));
                    });

                    final String value = getValue();
                    int start = value.indexOf(';') + 1;

                    for (final String id : Strings.split(value.substring(start), ',')) {
                        for (final T choice : choices) {
                            final String idValue = idForChoice.get(choice);
                            if (id.equals(idValue)) {
                                selected.add(choice);
                                break;
                            }
                        }
                    }

                    return selected;
                }
            };
        }
    };

    add(palette.setOutputMarkupId(true));

    final Form<?> form = new Form<>("form");
    add(form.setEnabled(builder.filtered).setVisible(builder.filtered));

    final AjaxTextFieldPanel filter = new AjaxTextFieldPanel("filter", "filter", queryFilter, false);
    filter.hideLabel().setOutputMarkupId(true);
    form.add(filter);

    form.add(new AjaxSubmitLink("search") {

        private static final long serialVersionUID = -1765773642975892072L;

        @Override
        protected void onAfterSubmit(final AjaxRequestTarget target, final Form<?> form) {
            super.onAfterSubmit(target, form);
            target.add(palette);
        }
    });
}

From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java

@Override
public Map<Pair<Application.Name, Page.Name>, List<PageExperiment>> getExperimentsWithoutLabels(
        Collection<Pair<Application.Name, Page.Name>> appAndPagePairs) {
    logger.debug("getExperimentsWithoutLabels {}", appAndPagePairs);
    Map<Pair<Application.Name, Page.Name>, List<PageExperiment>> resultMap = new HashMap<>();
    try {/*from w w  w .j ava  2 s.com*/
        Map<Pair<Application.Name, Page.Name>, ListenableFuture<Result<PageExperimentByAppNamePage>>> expFutureMap = new HashMap<>();
        appAndPagePairs.forEach(pair -> {
            expFutureMap.put(pair, pageExperimentIndexAccessor.asyncSelectBy(pair.getLeft().toString(),
                    pair.getRight().toString()));
        });

        for (Pair<Application.Name, Page.Name> pair : expFutureMap.keySet()) {
            ListenableFuture<Result<PageExperimentByAppNamePage>> expFuture = expFutureMap.get(pair);
            Stream<PageExperimentByAppNamePage> resultList = StreamSupport.stream(
                    Spliterators.spliteratorUnknownSize(
                            UninterruptibleUtil.getUninterruptibly(expFuture).iterator(), Spliterator.ORDERED),
                    false);
            List<PageExperiment> pageExperimentsList = resultList.map(t -> {
                PageExperiment.Builder builder = new PageExperiment.Builder(
                        Experiment.ID.valueOf(t.getExperimentId()), null, t.isAssign());
                return builder.build();
            }).collect(Collectors.toList());

            resultMap.put(pair, pageExperimentsList);
        }
    } catch (Exception e) {
        logger.error("getExperimentsWithoutLabels for {} failed", appAndPagePairs, e);
        throw new RepositoryException("Could not getExperimentsWithoutLabels", e);
    }

    logger.debug("Returning PageExperimentList map {}", resultMap);
    return resultMap;
}

From source file:de.ks.flatadocdb.session.Session.java

@Override
public void prepare() {
    Set<SessionEntry> renamed = handleRenames();

    Collection<SessionEntry> dirty = dirtyChecker.findDirty(new HashSet<>(this.entriesById.values()));
    dirty.removeAll(renamed);/*from   w  ww . j a v a  2 s .co m*/
    dirty.forEach(e -> {
        e.getEntityDescriptor().getChildRelations().stream()//
                .flatMap(r -> r.getRelatedEntities(e.getObject()).stream())//
                .filter(o -> metaModel.getEntityDescriptor(o.getClass()).getId(o) == null)//
                .filter(o -> !entity2Entry.containsKey(o))//
                .forEach(this::persist);
    });
    dirty.stream().map(e -> new EntityUpdate(repository, e)).forEach(actions::add);

    for (SessionAction action : this.actions) {
        try {
            action.prepare(this);
        } catch (RuntimeException e) {
            rollbackonly = true;
            throw e;
        }
    }
}

From source file:de.hska.ld.oidc.controller.OIDCController.java

private void enrichAuthoritiesWithStoredAuthorities(HttpServletRequest request, String sub, String issuer,
        OIDCUserinfoDto oidcUserinfoDto, String oidcToken, User user, Authentication auth) {
    DefaultUserInfo userInfo = new DefaultUserInfo();
    userInfo.setSub(oidcUserinfoDto.getSub());
    userInfo.setEmail(oidcUserinfoDto.getEmail());
    userInfo.setName(oidcUserinfoDto.getName());
    userInfo.setEmailVerified(true);/*from ww  w.  j av  a 2 s  .  com*/
    userInfo.setFamilyName(oidcUserinfoDto.getFamilyName());
    userInfo.setGivenName(oidcUserinfoDto.getGivenName());
    userInfo.setPreferredUsername(oidcUserinfoDto.getPreferredUsername());
    userInfo.setUpdatedTime(oidcUserinfoDto.getUpdatedTime());
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1];
    authorities.forEach(authority -> {
        if (authority instanceof SubjectIssuerGrantedAuthority) {
            // extract the oidc authority information
            oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority;
        }
    });

    // create new authorities that includes the authorities stored in the database
    // as well as the oidc authority
    ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
    user.getRoleList().forEach(role -> {
        newAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    });
    if (oidcAuthority[0] == null) {
        newAuthorities.add(new SubjectIssuerGrantedAuthority(sub, issuer));
    } else {
        newAuthorities.add(oidcAuthority[0]);
    }
    OIDCAuthenticationToken token = new OIDCAuthenticationToken(sub, issuer, userInfo, newAuthorities, null,
            oidcToken, null);
    token.setDetails(new WebAuthenticationDetails(request));
    SecurityContextHolder.getContext().setAuthentication(token);
}

From source file:org.onosproject.store.ecmap.EventuallyConsistentMapImpl.java

private void processUpdates(Collection<UpdateEntry<K, V>> updates) {
    if (destroyed) {
        return;/*w ww . ja  v  a 2 s . c  o  m*/
    }
    updates.forEach(update -> {
        final K key = update.key();
        final MapValue<V> value = update.value();
        if (value == null || value.isTombstone()) {
            MapValue<V> previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value));
            if (previousValue != null && previousValue.isAlive()) {
                notifyListeners(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get()));
            }
        } else if (putInternal(key, value)) {
            notifyListeners(new EventuallyConsistentMapEvent<>(mapName, PUT, key, value.get()));
        }
    });
}