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:io.knotx.knot.action.ActionKnotProxyImpl.java

private KnotContext handleGetMethod(List<FormEntity> forms, KnotContext knotContext) {
    LOGGER.trace("Pass-through {} request", knotContext.getClientRequest().getMethod());
    knotContext.setTransition(DEFAULT_TRANSITION);
    forms.forEach(form -> form.fragment().content(simplifier.simplify(form.fragment().content(),
            configuration.formIdentifierName(), form.identifier())));
    return knotContext;
}

From source file:io.sqp.transbase.TBTypeRepository.java

private String createDateTimeSchema(DateRangeSpecifier highField, DateRangeSpecifier lowField) {
    List<DateRangeSpecifier> fields = DateRangeSpecifier.range(highField, lowField);
    ObjectNode schema = createDateTimeSchemaSkeleton(highField, lowField);
    ArrayNode items = _objectMapper.createArrayNode();
    fields.forEach(f -> items.add(createTypeFromSpecifier(f)));
    schema.set("items", items);
    schema.put("minItems", fields.size());
    schema.put("additionalItems", false);
    return schema.toString();
}

From source file:com.evolveum.midpoint.model.impl.trigger.TriggerScannerTaskHandler.java

private List<TriggerType> getSortedTriggers(List<PrismContainerValue<TriggerType>> triggerCVals) {
    List<TriggerType> rv = new ArrayList<>();
    triggerCVals.forEach(cval -> rv.add(cval.clone().asContainerable()));
    rv.sort(Comparator.comparingLong(t -> XmlTypeConverter.toMillis(t.getTimestamp())));
    return rv;/*ww  w . ja v a2s  .  co  m*/
}

From source file:io.tilt.minka.business.impl.SemaphoreImpl.java

private void release_(Action action, Action cause) {
    Validate.notNull(action);// w  w w .j a  v a 2  s . com
    // first unlock the dependencies so others may start running
    if (cause == null) { // only when not rolling back to avoid deadlock
        final List<Action> group = rules.get(action).getRelated(SIBLING);
        if (group != null) {
            group.forEach(a -> release_(a, action));
        }
    }
    switch (action.getScope()) {
    case LOCAL:
        // then unlock the main lock
        ReentrantLock lock = g(action);
        if (lock == null) {
            logger.error("{}: Locks not implemented for action: {} ", getClass().getSimpleName(), action);
        } else {
            if (logger.isDebugEnabled() && cause != null) {
                logger.debug("{}: {} is Releasing: {}", getClass().getSimpleName(), cause, action);
            }
            lock.unlock();
        }
        break;
    case GLOBAL:
        locks.releaseDistributedLock(nameForDistributedLock(action, null));
        break;
    }
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)/*from w  ww.  j av a2s.c  om*/
public void reserver(final LocalDate startDate, final Famille famille, final List<DayOfWeek> jours)
        throws TechnicalException {

    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    icts.forEach(ict -> {
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndDateDebut(
                activite, ict.getGroupe(),
                Date.from(Instant.from(startDate.atStartOfDay(ZoneId.systemDefault()))));
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            try {
                this.reserver(date, ict.getIndividu().getId(), famille, jours.contains(date.getDayOfWeek()));
            } catch (TechnicalException e) {
                LOGGER.error("Une erreur technique s'est produite : " + e.getMessage(), e);
            } catch (FunctionalException e) {
                LOGGER.warn("Une erreur fonctionnelle s'est produite : " + e.getMessage(), e);
            }
        });
    });
}

From source file:com.devicehive.eventbus.test.EventBusTest.java

@Test
public void shouldSubscribeToDeviceNotificationWithName() throws Exception {
    String deviceGuid = UUID.randomUUID().toString();

    Subscriber subscriber1 = new Subscriber(UUID.randomUUID().toString(), randomAlphabetic(5),
            UUID.randomUUID().toString());
    Subscription subscription1 = new Subscription(Action.NOTIFICATION_EVENT.name(), deviceGuid);
    eventBus.subscribe(subscriber1, subscription1);

    Subscriber subscriber2 = new Subscriber(UUID.randomUUID().toString(), randomAlphabetic(5),
            UUID.randomUUID().toString());
    Subscription subscription2 = new Subscription(Action.NOTIFICATION_EVENT.name(), deviceGuid, "temperature");
    eventBus.subscribe(subscriber2, subscription2);

    Subscriber subscriber3 = new Subscriber(UUID.randomUUID().toString(), randomAlphabetic(5),
            UUID.randomUUID().toString());
    Subscription subscription3 = new Subscription(Action.NOTIFICATION_EVENT.name(), deviceGuid, "vibration");
    eventBus.subscribe(subscriber3, subscription3);

    Subscriber subscriber4 = new Subscriber(UUID.randomUUID().toString(), randomAlphabetic(5),
            UUID.randomUUID().toString());
    Subscription subscription4 = new Subscription(Action.COMMAND_EVENT.name(), deviceGuid, "go_offline");
    eventBus.subscribe(subscriber4, subscription4);

    DeviceNotification notification = new DeviceNotification();
    notification.setDeviceGuid(deviceGuid);
    notification.setNotification("temperature");
    notification.setId(0);/*from   w ww.  jav  a  2  s.  c om*/
    notification.setTimestamp(new Date());
    NotificationEvent notificationEvent = new NotificationEvent(notification);
    eventBus.publish(notificationEvent);

    ArgumentCaptor<String> topicCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);

    verify(dispatcher, times(2)).send(topicCaptor.capture(), responseCaptor.capture());
    List<String> topics = topicCaptor.getAllValues();
    assertThat(topics, hasSize(2));
    assertThat(topics, contains(subscriber1.getReplyTo(), subscriber2.getReplyTo()));

    List<Response> responses = responseCaptor.getAllValues();
    assertThat(responses, hasSize(2));
    responses.forEach(response -> {
        assertFalse(response.isLast());
        assertFalse(response.isFailed());
        assertTrue(response.getBody() instanceof NotificationEvent);
    });

    Response response1 = responses.get(0);
    Response response2 = responses.get(1);
    assertEquals(response1.getCorrelationId(), subscriber1.getCorrelationId());
    assertEquals(response2.getCorrelationId(), subscriber2.getCorrelationId());

    assertEquals(response1.getBody(), notificationEvent);
    assertEquals(response2.getBody(), notificationEvent);
}

From source file:org.fatal1t.backend.forexbackend.engine.EsperEngine.java

@Autowired
public EsperEngine(StatementRepository repository) {
    this.log = LogManager.getLogger(EsperEngine.class);
    this.listenerStatements = new HashMap<>();
    this.statements = new HashMap<>();
    this.statementRepository = repository;
    this.config = new Configuration();
    ConfigurationDBRef bRef = new ConfigurationDBRef();

    /**/*w ww  .  j a v  a  2  s .co m*/
     * Load all input classes - TickRecords, CandleRecords ... 
     */
    this.config.addEventType("Tick", TickRecord.class);
    this.config.addEventType("Candle", CandleDataRecord.class);
    log.info("Initialized source objects");

    /**
     * Initialize EPService
     */
    this.epService = EPServiceProviderManager.getDefaultProvider(config);
    this.epService.initialize();
    log.info("Initialized EP Engine service");
    /**
     * Load main catching statements frist
     * tady pozor na poradi jak se bude loadovat ... problem bude delat to, kdyz se nejdrive bude loadovat statement, ktery je zavisly na nekterem, ktery neni nadefinovany 
     */
    List<EplStatement> eplStatements = this.statementRepository.findByIsUsedAndIsMainRule(true, false);
    if (!eplStatements.isEmpty()) {
        eplStatements.forEach(e -> {
            statements.put(e.getStatementName(),
                    this.epService.getEPAdministrator().createEPL(e.getStatement(), e.getStatementName()));
        });
    }
    log.info("Loaded auxiliary statements");

    List<EplStatement> mainEplStatements = this.statementRepository.findByIsMainRule(true);
    mainEplStatements.forEach((EplStatement e) -> {
        switch (e.getStatementName()) {
        case "test": {
            EPStatement eps2 = this.epService.getEPAdministrator().createEPL(e.getStatement(),
                    e.getStatementName());
            eps2.addListener(new UpdateListener() {
                @Override
                public void update(EventBean[] newEvents, EventBean[] oldEvents) {
                    Double averige = (Double) newEvents[0].get("averige");
                    System.out.println("New moving averige on 10 candles: " + averige);
                    counter++;
                }
            });
        }
            ;
        case "buy": {

        }
        case "sell": {

        }
        default: {

        }
        }
    });
    log.info("Loaded main statements");

    /**
     * Load all statements
     */
    /** testing scheme for development stuff
    String eplstate = "insert into candleAverige select avg(c.close) as averige from Candle c";
    EPStatement eps1 = this.epService.getEPAdministrator().createEPL(eplstate);
    String eplstate2 = "select c.averige as averige from candleAverige c";
    EPStatement eps2 = this.epService.getEPAdministrator().createEPL(eplstate2);
            
    eps2.addListener(new UpdateListener() {
    @Override
    public void update(EventBean[] newEvents, EventBean[] oldEvents) {
        Double averige =  (Double) newEvents[0].get("averige");
        System.out.println("New moving averige on 10 candles: " + averige);
        counter++;
    }
    });*/

}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

private void addHeaders(HttpRequest request, List<Map.Entry<String, String>> headers) {
    headers.forEach(e -> request.addHeader(e.getKey(), e.getValue()));
}

From source file:com.oneops.transistor.util.CloudUtil.java

/**
 * This will check if all required services are configured for clouds in
 * which platform needs to be deployed./*from   w w w  . ja v a2s .  co m*/
 * @param platformIds to check if all services required for the platform are configured
 * @throws TransistorException if not all services are configured in clouds.
 * */
public void check4missingServices(Set<Long> platformIds) {

    Set<String> errors = new HashSet<>(platformIds.size());
    Map<String, Set<String>> cloudServices = new HashMap<>();
    for (long manifestPlatformId : platformIds) {
        List<CmsRfcRelation> requiredRelations = getRequired(manifestPlatformId);
        Set<String> requiredServices = getRequiredServices(requiredRelations);
        List<CmsRfcRelation> cloudRelations = getCloudsForPlatform(manifestPlatformId);
        Map<String, TreeSet<String>> cloudsMissingServices = new HashMap<>();
        cloudRelations.forEach(cloudRelation -> {
            String cloud = cloudRelation.getToRfcCi().getCiName();
            //have not seen the cloud before
            if (!cloudServices.containsKey(cloud)) {
                cloudServices.put(cloud, getCloudServices(cloudRelation));
            }
            //check if service is configured
            cloudsMissingServices
                    .putAll(getMissingCloudServices(cloud, cloudServices.get(cloud), requiredServices));
        });

        if (!cloudsMissingServices.isEmpty()) {
            // <{c1=[s1]}>
            final String nsPath = requiredRelations.get(0).getNsPath();
            String message = getErrorMessage(cloudsMissingServices, nsPath);
            errors.add(message);
        }
    }
    if (!errors.isEmpty()) {
        throw new TransistorException(TRANSISTOR_MISSING_CLOUD_SERVICES, StringUtils.join(errors, ";\n"));
    }
}

From source file:ee.ria.xroad.confproxy.commandline.ConfProxyUtilViewConf.java

/**
 * Print the configuration proxy instance properties to the commandline.
 * @param instance configuration proxy instance name
 * @param conf configuration proxy properties instance
 * @throws Exception if errors occur when reading properties
 *//*from   ww  w  . j  a v a 2 s  . c  om*/
private void displayInfo(final String instance, final ConfProxyProperties conf) throws Exception {
    ConfigurationAnchorV2 anchor = null;
    String anchorError = null;
    try {
        anchor = new ConfigurationAnchorV2(conf.getProxyAnchorPath());
    } catch (Exception e) {
        anchorError = "'" + ConfProxyProperties.ANCHOR_XML + "' could not be loaded: " + e;
    }
    String delimiter = "==================================================";

    System.out.println("Configuration for proxy '" + instance + "'");
    int validityInterval = conf.getValidityIntervalSeconds();
    System.out.println("Validity interval: "
            + (validityInterval < 0 ? VALIDITY_INTERVAL_NA_MSG : validityInterval + " s."));
    System.out.println();

    System.out.println(ConfProxyProperties.ANCHOR_XML);
    System.out.println(delimiter);
    if (anchorError == null) {
        System.out.println("Instance identifier: " + anchor.getInstanceIdentifier());
        SimpleDateFormat sdf = new SimpleDateFormat("z yyyy-MMM-d hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("Generated at:        " + sdf.format(anchor.getGeneratedAt()));
        System.out.println("Hash:                " + anchorHash(conf));
    } else {
        System.out.println(anchorError);
    }
    System.out.println();

    System.out.println("Configuration URL");
    System.out.println(delimiter);
    if (conf.getConfigurationProxyURL().equals("0.0.0.0")) {
        System.out.println("configuration-proxy.address has not been" + " configured in 'local.ini'!");
    } else {
        System.out.println(conf.getConfigurationProxyURL() + "/" + OutputBuilder.SIGNED_DIRECTORY_NAME);
    }
    System.out.println();

    System.out.println("Signing keys and certificates");
    System.out.println(delimiter);

    System.out.println(ACTIVE_SIGNING_KEY_ID + ":");
    String activeKey = conf.getActiveSigningKey();
    System.out.println("\t" + (activeKey == null ? ACTIVE_KEY_NA_MSG : activeKey) + certInfo(activeKey, conf));
    List<String> inactiveKeys = conf.getKeyList();
    if (!inactiveKeys.isEmpty()) {
        System.out.println(SIGNING_KEY_ID_PREFIX + "*:");
        inactiveKeys.forEach(k -> System.out.println("\t" + k + certInfo(k, conf)));
    }
    System.out.println();
}