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:com.sample.ecommerce.config.SchemaConfiguration.java

@PostConstruct
private void setup() throws DataStoreException {
    ExistsResponse existsResponse = client.prepareExists().setIndices(indexName).setTypes("schema").execute()
            .actionGet();//from   w  w w . ja v a 2  s .  c o  m

    if (!existsResponse.exists()) {
        InputStream inputStream = SchemaConfiguration.class.getResourceAsStream("/default_schema/schema.json");

        Map<String, Object> schemaMap = asMap(getContentFromStream(inputStream));
        schemaMap.forEach((schemaId, schemaAsMap) -> {
            try {
                ((Map) schemaAsMap).put("id", schemaId);
                dataStore.createSchema(asString(schemaAsMap));
            } catch (DataStoreException ex) {
                LOGGER.error("Error Creating Schma", ex);
            }
        });

        schemaMap.keySet().forEach((String schemaId) -> {
            InputStream dataInputStream = null;
            try {
                dataInputStream = SchemaConfiguration.class
                        .getResourceAsStream("/default_schema/data/" + schemaId + ".json");
                if (dataInputStream != null) {
                    dataStore.delete(schemaId);
                    List dataValues = asList(getContentFromStream(dataInputStream));
                    dataValues.forEach(data -> {
                        try {
                            dataStore.create(schemaId, (Map<String, Object>) data);
                        } catch (DataStoreException ex) {
                            LOGGER.error("Error Creating Schma", ex);
                        }
                    });
                }

            } catch (Exception e) {
                Logger.getLogger(SchemaConfiguration.class.getName()).log(Level.SEVERE, null, e);
            } finally {
                try {
                    if (dataInputStream != null) {
                        dataInputStream.close();
                    }

                } catch (IOException ex) {
                    LOGGER.error("Error Creating Schma", ex);
                }
            }

        });
    }

}

From source file:info.losd.galen.api.GalenApiController.java

@RequestMapping(value = "/healthchecks/{name}/statistics", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/*www  .  ja va2  s . co m*/
public HttpEntity<List<HealthcheckApiStatistic>> getStatistics(@PathVariable String name,
        @RequestParam(value = "period", required = false, defaultValue = "2m") String period) {
    List<HealthcheckApiStatistic> result = new LinkedList<>();
    Period p = Period.getPeriod(period);
    List<info.losd.galen.repository.dto.HealthcheckStatistic> stats = repo.getStatisticsForPeriod(name, p);

    stats.forEach(stat -> {
        result.add(
                new HealthcheckApiStatistic(stat.getTimestamp(), stat.getResponseTime(), stat.getStatusCode()));
    });

    return new ResponseEntity<>(result, HttpStatus.OK);
}

From source file:se.uu.it.cs.recsys.dataloader.impl.FuturePlannedCourseLoader.java

private void loadCoursesToDB(List<Course> targets) {

    targets.forEach(target -> {
        se.uu.it.cs.recsys.persistence.entity.Course entry = new se.uu.it.cs.recsys.persistence.entity.Course();

        entry.setCode(target.getCode());
        entry.setName(target.getName());
        entry.setTaughtYear(target.getTaughtYear().shortValue());
        entry.setStartPeriod(target.getStartPeriod().shortValue());
        entry.setEndPeriod(target.getEndPeriod().shortValue());

        entry.setCredit(this.supportedCourseCreditRepository.findByCredit(target.getCredit()));
        entry.setLevel(this.supportedCourseLevelRepository.findByLevel(target.getLevel().toString()));

        se.uu.it.cs.recsys.persistence.entity.Course existing = this.courseRepository
                .findByCodeAndTaughtYearAndStartPeriod(entry.getCode(), entry.getTaughtYear(),
                        entry.getStartPeriod());

        if (existing == null) {
            se.uu.it.cs.recsys.persistence.entity.Course saved = this.courseRepository.save(entry);

            writeMappingInfo(saved.getAutoGenId(), target);
        }/* w w  w . ja  v  a  2 s.com*/
    });
}

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

/**
 * Add a cognition to the identity. This will cause that we forget cognitions after
 * the awareness threshold has passed.//  w w w  . j  a v a2s. com
 * @param cognition
 * @return self
 */
public SusiIdentity add(SusiCognition cognition) {
    this.short_term_memory.learn(cognition);
    List<SusiCognition> forgottenCognitions = this.short_term_memory.limitAwareness(this.attention);
    forgottenCognitions.forEach(c -> this.long_term_memory.learn(c)); // TODO add a rule to memorize only the most important ones
    try {
        Files.write(this.memorydump.toPath(), UTF8.getBytes(cognition.getJSON().toString(0) + "\n"),
                StandardOpenOption.APPEND, StandardOpenOption.CREATE);
    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }
    return this;
}

From source file:com.epam.ta.reportportal.core.statistics.StatisticsFacadeImpl.java

@Override
public void recalculateStatistics(Launch launch) {
    deleteLaunchStatistics(launch);//  w ww . j av a 2s.  co  m
    testItemRepository.findByHasChildStatus(false, launch.getId()).forEach(this::recalculateTestItemStatistics);

    List<TestItem> withIssues = testItemRepository.findTestItemWithIssues(launch.getId());
    withIssues.forEach(this::updateIssueStatistics);
}

From source file:lumbermill.internal.http.PostHandler.java

private void extractRouteParamsAsMetadata(RoutingContext context, IN e) {
    List<Entry<String, String>> entries = context.request().params().entries();
    entries.forEach(entry -> e.put(entry.getKey(), entry.getValue()));
}

From source file:com.devicehive.dao.riak.NetworkDeviceDaoRiakImpl.java

public Set<String> findDevicesForNetwork(long networkId) {
    IntIndexQuery biq = new IntIndexQuery.Builder(NETWORK_DEVICE_NS, "networkId", networkId).build();
    try {//from   ww  w .  j av  a 2  s .  c o m
        IntIndexQuery.Response response = client.execute(biq);

        List<NetworkDevice> ndList = fetchMultiple(response, NetworkDevice.class);
        Set<String> devices = new HashSet<>();
        ndList.forEach(networkDevice -> devices.add(networkDevice.getDeviceUuid()));
        return devices;
    } catch (ExecutionException | InterruptedException e) {
        throw new HivePersistenceLayerException("Cannot find device for network.", e);
    }
}

From source file:cern.jarrace.controller.rest.controller.AgentContainerController.java

@RequestMapping(value = "/{" + CONTAINER_NAME_VARIABLE_NAME + "}/start", method = RequestMethod.GET)
public String runService(@PathVariable(CONTAINER_NAME_VARIABLE_NAME) String containerName,
        @RequestParam(value = "service") String serviceName,
        @RequestParam(value = "entryPoints", defaultValue = "") String entryPoints) throws Exception {
    Optional<AgentContainer> optionalAgentContainer = agentContainerManager.findAgentContainer(containerName);
    if (!optionalAgentContainer.isPresent()) {
        throw new IllegalArgumentException("AgentContainer name must exist");
    }//from   ww w .  j a  v  a  2 s .  co m
    AgentContainer agentContainer = optionalAgentContainer.get();
    Optional<Service> serviceOptional = agentContainer.getServices().stream().filter(service -> {
        String className = service.getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        return className.equals(serviceName) ? true : false;
    }).findFirst();
    if (serviceOptional.isPresent()) {
        Service service = serviceOptional.get();
        List<String> parsedEntryPoints = Arrays.asList(entryPoints.split(","));
        parsedEntryPoints.forEach(entryPoint -> {
            if (!service.getEntryPoints().contains(entryPoint)) {
                throw new IllegalArgumentException("All entry points must exist");
            }
        });
        return agentRunnerSpawner.spawnAgentRunner(service, agentContainer.getContainerPath(),
                parsedEntryPoints);
    }
    throw new IllegalArgumentException("Service name must exist");
}

From source file:com.devicehive.dao.riak.UserNetworkDaoRiakImpl.java

public Set<Long> findUsersInNetwork(Long networkId) {
    IntIndexQuery biq = new IntIndexQuery.Builder(USER_NETWORK_NS, "networkId", networkId).build();
    try {//from   w ww .  ja  v  a2 s .  co m
        IntIndexQuery.Response response = client.execute(biq);
        List<UserNetwork> userNetworks = fetchMultiple(response, UserNetwork.class);
        Set<Long> users = new HashSet<>();
        userNetworks.forEach(userNetwork -> users.add(userNetwork.getUserId()));
        return users;
    } catch (ExecutionException | InterruptedException e) {
        throw new HivePersistenceLayerException("Cannot find users in network.", e);
    }
}

From source file:info.losd.galen.scheduler.Scheduler.java

@Scheduled(fixedDelay = 500)
public void processTasks() {
    List<Task> tasks = repo.findTasksToBeRun();
    LOG.debug("There are {} tasks waiting", tasks.size());

    tasks.forEach(task -> {
        LOG.debug("processing: {}", task.toString());

        Map<String, String> headers = new HashMap<>();
        task.getHeaders().forEach(header -> {
            headers.put(header.getHeader(), header.getValue());
        });/*  w ww.  j  a  va  2  s  . co  m*/

        SchedulerHealthcheck healthcheckRequest = new SchedulerHealthcheck();
        healthcheckRequest.setHeaders(headers);
        healthcheckRequest.setMethod(task.getMethod());
        healthcheckRequest.setTag(task.getName());
        healthcheckRequest.setUrl(task.getUrl());

        try {
            String body = mapper.writeValueAsString(healthcheckRequest);

            HttpResponse response = Request.Post("http://127.0.0.1:8080/healthchecks")
                    .bodyString(body, ContentType.APPLICATION_JSON).execute().returnResponse();

            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                task.setLastUpdated(Instant.now());
                repo.save(task);
                LOG.debug("processed:  {}", task.getId());
            } else {
                LOG.error("task: {}, status code: {}, reason: {}\nbody: {}", task.getId(),
                        status.getStatusCode(), status.getReasonPhrase(),
                        IOUtils.toString(response.getEntity().getContent()));
            }
        } catch (Exception e) {
            LOG.error("Problem processing task {}", task.getId(), e);
        }
    });
}