Example usage for java.util List forEach

List of usage examples for java.util List forEach

Introduction

In this page you can find the example usage for java.util List 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:natalia.dymnikova.cluster.scheduler.impl.LocalChildrenCreator.java

private List<ActorRef> allocateLocalFlowActor(final FlowControlActor flowControlActor) {
    final List<Entry<Integer, Object>> actions = localFlow.getActions();
    final SetFlow flow = localFlow.getFlow();

    final List<ActorRef> refs = new ArrayList<>();

    actions.forEach(entry -> {
        final int id = entry.getKey();
        final Object action = entry.getValue();
        final Flow.Stage stage = getStage(flow, id);

        if (log.isDebugEnabled()) {
            log.debug("Create {} stage in ChildrenCreator", id);
            log.debug("Type: {}", stage.getType());
            log.debug("Previous actor: {}", getPreviousStageNumbers(flow, id));
        }/*from   w w w . jav a 2s  .  c o m*/
        if (action instanceof OnSubscribeWrapper) {
            //noinspection unchecked
            final ActorSelection nextActor = flowControlActor
                    .actorSelection(remoteStageActorPath(flow, getNextStageNumber(flow, id)));
            log.debug("Next actor: {}", nextActor);
            refs.add(
                    flowControlActor.actorOf(
                            StartStageActor.props(extension, nextActor, flow,
                                    new OnSubscribeWrapper(autowireHelper
                                            .autowire(((OnSubscribeWrapper) action).onSubscribe))),
                            stageName(id)));
        } else {
            final Optional<ActorSelection> nextActor;
            if (flow.getStage() == stage) {
                flowControlActor.actorOf(StartingJobActor.props(extension, flow), "StartingJobActor");
                nextActor = empty();
            } else {
                nextActor = of(flowControlActor
                        .actorSelection(remoteStageActorPath(flow, getNextStageNumber(flow, id))));
            }

            refs.add(
                    flowControlActor.actorOf(
                            IntermediateStageActor.props(extension,
                                    flowControlActor.actorSelection(remoteStageActorPath(flow,
                                            getPreviousStageNumbers(flow, id).get(0))),
                                    nextActor, asOperator(action), flow, createOnCompleteConsumer(stage, flow)),
                            stageName(id)));
        }
    });

    return refs;
}

From source file:com.watchrabbit.crawler.manager.policy.OPICImportancePolicy.java

@Override
public void processCrawlResult(CrawlResult crawlResult) {
    AddressOPIC addressOPIC = addressOPICRepository.find(crawlResult.getId());
    if (addressOPIC == null) {
        addressOPIC = new AddressOPIC.Builder().withId(crawlResult.getId()).build();
    }//ww  w  .jav a 2s. c om
    double cash = addressOPIC.getCash();
    List<LinkDto> links = crawlResult.getLinks();
    if (linkFilter != null) {
        links = linkFilter.filterLinks(links);
    }
    links = links.stream().filter(link -> !cleanupPolicy.isOnBlacklist(link)).collect(toList());
    double change = cash / links.size();
    links.forEach(url -> distribute(url, change));
    addressOPIC.resetCash(opicHistoricalResults);
    addressOPIC.addCash(crawlResult.getImportanceFactor());
    addressOPICRepository.save(addressOPIC);
}

From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ApprovalSchemaBuilder.java

private void sortFragments(List<Fragment> fragments) {
    fragments.forEach(f -> {
        if (f.compositionStrategy != null && BooleanUtils.isTrue(f.compositionStrategy.isMergeable())
                && f.compositionStrategy.getOrder() == null) {
            throw new IllegalStateException("Mergeable composition strategy with no order: "
                    + f.compositionStrategy + " in " + f.policyRule);
        }/*from w ww  .  j  a  v  a2 s  .  c o m*/
    });

    // relying on the fact that the sort algorithm is stable
    fragments.sort((f1, f2) -> {
        ApprovalCompositionStrategyType s1 = f1.compositionStrategy;
        ApprovalCompositionStrategyType s2 = f2.compositionStrategy;
        Integer o1 = s1 != null ? s1.getOrder() : null;
        Integer o2 = s2 != null ? s2.getOrder() : null;
        if (o1 == null || o2 == null) {
            return MiscUtil.compareNullLast(o1, o2);
        }
        int c = Integer.compare(o1, o2);
        if (c != 0) {
            return c;
        }
        // non-mergeable first
        boolean m1 = BooleanUtils.isTrue(s1.isMergeable());
        boolean m2 = BooleanUtils.isTrue(s2.isMergeable());
        if (m1 && !m2) {
            return 1;
        } else if (!m1 && m2) {
            return -1;
        } else {
            return 0;
        }
    });
}

From source file:com.thinkbiganalytics.alerts.spi.defaults.DefaultAlertCriteria.java

protected JPAQuery addWhere(QueryBase query, List<Predicate> preds, BooleanBuilder orFilter) {
    if (preds.isEmpty() && !orFilter.hasValue()) {
        return (JPAQuery) query;
    } else {//from ww w .  ja  v a 2  s.  c  o  m
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        preds.forEach(p -> booleanBuilder.and(p));
        if (orFilter.hasValue()) {
            booleanBuilder.and(orFilter);
        }
        return (JPAQuery) query.where(booleanBuilder);
    }
}

From source file:ru.trett.cis.services.PDFBuilderImpl.java

@Override
public String createPDF() throws IOException, DocumentException, ApplicationException {
    try {//from   ww  w.j  a  v  a2 s. c  o  m
        String templatePath = servletContext.getRealPath("WEB-INF/resources/template-settings.xml");
        Map<String, List<String>> data = TemplateParser.parse(new File(templatePath));
        String regularFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Regular.ttf");
        if (regularFontPath == null)
            throw new ApplicationException("Regular Font file was not found");
        BaseFont bfr = BaseFont.createFont(regularFontPath, BaseFont.IDENTITY_H, true);
        String boldFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Bold.ttf");
        if (boldFontPath == null)
            throw new ApplicationException("Bold Font file was not found");
        BaseFont bfb = BaseFont.createFont(boldFontPath, BaseFont.IDENTITY_H, true);
        regularFont = new Font(bfr);
        regularFont.setSize(10);
        boldFont = new Font(bfb);
        boldFont.setSize(10);

        File file = File.createTempFile("order", ".pdf");
        Document doc = new Document(PageSize.A4);
        Chunk glue = new Chunk(new VerticalPositionMark());
        PdfWriter.getInstance(doc, new FileOutputStream(file));
        doc.open();
        doc.newPage();

        //title
        Paragraph p = new Paragraph(data.get("header").get(0), boldFont);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);
        doc.add(Chunk.NEWLINE);

        //body
        for (String text : data.get("text")) {
            p = new Paragraph(text, regularFont);
            doc.add(p);
        }

        //table
        doc.add(Chunk.NEWLINE);
        List<String> cols = data.get("cols");
        PdfPTable table = new PdfPTable(cols.size());
        table.setWidthPercentage(100);

        cols.forEach(x -> table.addCell(getCell(x, PdfPCell.ALIGN_CENTER, boldFont)));

        for (Asset asset : assets) {
            table.addCell(getCell(String.format("%s %s %s", asset.getDeviceModel().getDeviceType().getType(),
                    asset.getDeviceModel().getDeviceBrand().getBrand(), asset.getDeviceModel().getModel()),
                    PdfPCell.ALIGN_CENTER, regularFont));
            table.addCell(getCell(asset.getSerialNumber(), PdfPCell.ALIGN_CENTER, regularFont));
            table.addCell(getCell(asset.getInventoryNumber(), PdfPCell.ALIGN_CENTER, regularFont));
        }

        table.getRows();
        doc.add(table);
        doc.add(Chunk.NEWLINE);
        doc.add(Chunk.NEWLINE);

        //signers
        Phrase phrase = new Phrase(new Chunk(data.get("signers").get(0) + " ", regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(issuer.getFirstName() + " " + issuer.getLastName() + "  \\__________________",
                regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(data.get("signers").get(1) + " ", regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(employee.getFirstName() + " " + employee.getLastName() + "  \\__________________",
                regularFont));
        doc.add(phrase);

        //date
        doc.add(Chunk.NEWLINE);
        doc.add(Chunk.NEWLINE);
        p = new Paragraph(data.get("place").get(0), regularFont);
        p.add(new Chunk(glue));
        p.add(date.format(dateFormat));
        doc.add(p);
        doc.close();
        return file.getPath();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpWebSocketGroupRegistry.java

/**
 * Send to group.//w  w w . j a v  a 2 s. c  o  m
 *
 * @param groupName
 *          the group name
 * @param message
 *          the message
 * @param except
 *          the except
 */
public void sendToGroup(String groupName, byte[] message, SystemIdKey... except) {
    List<WebSocketSession> group = getGroup(groupName);

    if (group == null)
        return;

    group.forEach(c -> {
        try {
            AbstractRegistryKey<?> systemId = getKeyForWebSocketSession(c);
            if (!excepted(systemId, except))
                send(systemId, message);
        } catch (Exception e) {
            log.error("Unexpected exception sending message to {}", c, e);
        }
    });

}

From source file:com.tascape.qa.th.SystemConfiguration.java

public void listAppProperties() {
    LOG.debug("Application properties");
    List<String> keys = new ArrayList<>(this.properties.stringPropertyNames());
    Collections.sort(keys);//from w ww. j av a  2 s.c om
    keys.forEach((key) -> {
        LOG.debug(String.format("%50s : %s", key, this.properties.getProperty(key)));
    });
}

From source file:com.devicehive.dao.NetworkDaoTest.java

@Test
public void shouldListByNameWithSortingAndLimit() throws Exception {
    String name = RandomStringUtils.randomAlphabetic(10);
    for (int i = 0; i < 100; i++) {
        NetworkVO network = new NetworkVO();
        network.setKey(RandomStringUtils.randomAlphabetic(10));
        if (i % 2 == 0) {
            network.setName(name);//from w  w w .j a  v a2  s  . c  o  m
        } else {
            network.setName(RandomStringUtils.randomAlphabetic(10));
        }
        network.setEntityVersion((long) i);
        networkDao.persist(network);
    }

    List<NetworkVO> networks = networkDao.list(name, null, "entityVersion", true, 10, 0, Optional.empty());
    assertThat(networks, hasSize(10));
    networks.forEach(n -> assertEquals(name, n.getName()));
    networks.stream().reduce((last, current) -> {
        if (last.getEntityVersion() > current.getEntityVersion())
            Assert.fail("Not sorted");
        return current;
    });
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Creates a {@link OkHttpClient} to start a TLS connection.
 *
 * @param cookies list of cookies to include in the client.
 * @return new http client./*from w w w . j  ava 2  s . co  m*/
 */
public static OkHttpClient sslOkHttpClient(List<HttpCookie> cookies) {
    checkNotNull(cookies);

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }

    SSLSocketFactory socketFactory = sslContext.getSocketFactory();

    OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory)
            .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false);

    client.setRetryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookies.forEach(c -> cookieManager.getCookieStore().add(null, c));
    client.setCookieHandler(cookieManager);
    return client;
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.DataProcessor.java

private long calculateMetric(@NonNull List<SolutionPerJob> spjList,
        BiConsumer<SolutionPerJob, Double> resultSaver, Consumer<SolutionPerJob> ifEmpty) {
    //to support also parallel stream.
    AtomicLong executionTime = new AtomicLong();

    spjList.forEach(spj -> {
        Pair<Optional<Double>, Long> result = simulateClass(spj);
        executionTime.addAndGet(result.getRight());
        Optional<Double> optionalValue = result.getLeft();
        if (optionalValue.isPresent())
            resultSaver.accept(spj, optionalValue.get());
        else/*from ww  w. j  av  a  2  s .c o  m*/
            ifEmpty.accept(spj);
    });

    return executionTime.get();
}