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:dk.dma.msinm.service.ChartService.java

/**
 * Searchs for charts matching the given term
 * @param term the search term//from  ww  w  . j ava2  s .  c om
 * @param limit the maximum number of results
 * @return the search result
 */
public List<ChartVo> searchCharts(String term, int limit) {
    List<ChartVo> result = new ArrayList<>();
    if (StringUtils.isNotBlank(term)) {
        List<Chart> charts = em.createNamedQuery("Chart.searchCharts", Chart.class)
                .setParameter("term", "%" + term + "%").setParameter("sort", term).setMaxResults(limit)
                .getResultList();

        charts.forEach(chart -> result.add(new ChartVo(chart)));
    }
    return result;
}

From source file:natalia.dymnikova.cluster.scheduler.impl.find.optimal.FindOptimalAddressesStrategy.java

private List<GroupsRouteWithValues> findBestGroups(final Tree<List<Address>> variants,
        final List<GroupsRouteWithValues> routs) {
    if (variants.getChildren().isEmpty()) {
        if (variants.getRoot().isEmpty()) {
            return routs;
        } else {// w w w  .  j  a  v a  2 s.  c om
            return variants.getRoot().stream().map(groupOfAddresses::getGroup).distinct()
                    .flatMap(group -> routs.stream().map(rout -> new GroupsRouteWithValues(rout, group)))
                    .collect(toList());
        }
    }

    final List<Tree<List<Address>>> children = variants.getChildren();
    final List<List<GroupsRouteWithValues>> bestWay = new ArrayList<>();
    children.forEach(child -> bestWay.add(findBestGroups(child, routs)));
    final List<List<GroupsRouteWithValues>> allChildrenCombines = allCombines(bestWay);

    if (variants.getRoot().isEmpty()) {
        return allChildrenCombines.stream().flatMap(rout -> rout.stream().map(GroupsRouteWithValues::new))
                .collect(toList());
    } else {
        return variants.getRoot().stream().flatMap(address -> allChildrenCombines.stream().map(rout -> {
            final GroupsRouteWithValues routeWithValues = new GroupsRouteWithValues(
                    rout.get(0).getGroupOfAddresses());
            routeWithValues.setNextPoint(groupOfAddresses.getGroup(address));
            rout.stream().forEach(routeWithValues::setNextRoute);
            return routeWithValues;
        })).collect(toList());
    }
}

From source file:org.ow2.proactive.procci.service.occi.MixinService.java

/**
 * Remove a mixin from the database and update the references
 * @param mixinTitle the title of the mixin to remove
 *//*from   w w w. j a  v a  2  s. co  m*/
public void removeMixin(String mixinTitle) {
    Mixin mixinToRemove = getMixinByTitle(mixinTitle);
    List<Entity> entities = mixinToRemove.getEntities();

    cloudAutomationVariablesClient.delete(mixinTitle);

    entities.forEach(entity -> {
        getMixinNamesFromEntity(entity.getId()).remove(mixinTitle);
    });

    entities.forEach(entity -> {
        Set<String> entityMixins = getMixinNamesFromEntity(entity.getId());
        entityMixins.remove(mixinTitle);
        cloudAutomationVariablesClient.update(entity.getId(), mapObject(entityMixins));
    });

}

From source file:io.spring.initializr.actuate.stat.ProjectRequestDocumentFactory.java

public ProjectRequestDocument createDocument(ProjectRequestEvent event) {
    InitializrMetadata metadata = this.metadataProvider.get();
    ProjectRequest request = event.getProjectRequest();

    ProjectRequestDocument document = new ProjectRequestDocument();
    document.setGenerationTimestamp(event.getTimestamp());

    handleCloudFlareHeaders(request, document);
    String candidate = (String) request.getParameters().get("x-forwarded-for");
    if (!StringUtils.hasText(document.getRequestIp()) && candidate != null) {
        document.setRequestIp(candidate);
        document.setRequestIpv4(extractIpv4(candidate));
    }/*from   w  ww . j a v a  2s  .  c  o m*/

    Agent agent = extractAgentInformation(request);
    if (agent != null) {
        document.setClientId(agent.getId().getId());
        document.setClientVersion(agent.getVersion());
    }

    document.setGroupId(request.getGroupId());
    document.setArtifactId(request.getArtifactId());
    document.setPackageName(request.getPackageName());
    document.setBootVersion(request.getBootVersion());

    document.setJavaVersion(request.getJavaVersion());
    if (StringUtils.hasText(request.getJavaVersion())
            && metadata.getJavaVersions().get(request.getJavaVersion()) == null) {
        document.setInvalid(true);
        document.setInvalidJavaVersion(true);
    }

    document.setLanguage(request.getLanguage());
    if (StringUtils.hasText(request.getLanguage())
            && metadata.getLanguages().get(request.getLanguage()) == null) {
        document.setInvalid(true);
        document.setInvalidLanguage(true);
    }

    document.setPackaging(request.getPackaging());
    if (StringUtils.hasText(request.getPackaging())
            && metadata.getPackagings().get(request.getPackaging()) == null) {
        document.setInvalid(true);
        document.setInvalidPackaging(true);
    }

    document.setType(request.getType());
    if (StringUtils.hasText(request.getType()) && metadata.getTypes().get(request.getType()) == null) {
        document.setInvalid(true);
        document.setInvalidType(true);
    }

    // Let's not rely on the resolved dependencies here
    List<String> dependencies = new ArrayList<>();
    dependencies.addAll(request.getStyle());
    dependencies.addAll(request.getDependencies());
    dependencies.forEach((id) -> {
        if (metadata.getDependencies().get(id) != null) {
            document.getDependencies().add(id);
        } else {
            document.setInvalid(true);
            document.getInvalidDependencies().add(id);
        }
    });

    // Let's make sure that the document is flagged as invalid no matter what
    if (event instanceof ProjectFailedEvent) {
        ProjectFailedEvent failed = (ProjectFailedEvent) event;
        document.setInvalid(true);
        if (failed.getCause() != null) {
            document.setErrorMessage(failed.getCause().getMessage());
        }
    }

    return document;
}

From source file:info.archinnov.achilles.embedded.AchillesInitializer.java

private void executeStartupScripts(Session session, TypedMap parameters) {
    ScriptExecutor scriptExecutor = null;
    List<String> scriptLocations = parameters.getTypedOr(SCRIPT_LOCATIONS, new ArrayList<>());
    if (scriptLocations.size() > 0) {
        scriptExecutor = new ScriptExecutor(session);
        scriptLocations.forEach(scriptExecutor::executeScript);
    }/* w  ww . j a v  a 2s  . c  om*/

    final Map<String, Map<String, Object>> scriptTemplates = parameters.getTypedOr(SCRIPT_TEMPLATES,
            new HashMap<>());
    if (scriptTemplates.size() > 0) {
        scriptExecutor = scriptExecutor == null ? new ScriptExecutor(session) : scriptExecutor;

        final ScriptExecutor executor = scriptExecutor;

        scriptTemplates.entrySet()
                .forEach(entry -> executor.executeScriptTemplate(entry.getKey(), entry.getValue()));
    }
}

From source file:org.openmhealth.shim.Application.java

/**
 * Endpoint for removing authorizations for a given user and shim.
 *
 * @param username The user record for which we're removing shim access.
 * @param shim The shim registry key of the shim authorization we're removing.
 * @return Simple response message.//from  www .  ja v  a2s.c o  m
 */
@RequestMapping(value = "/de-authorize/{shim}", method = DELETE, produces = APPLICATION_JSON_VALUE)
public List<String> removeAuthorization(@RequestParam(value = "username") String username,
        @PathVariable("shim") String shim) throws ShimException {

    List<AccessParameters> accessParameters = accessParametersRepo.findAllByUsernameAndShimKey(username, shim);

    accessParameters.forEach(accessParametersRepo::delete);

    return singletonList("Success: Authorization Removed.");
}

From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.RabbitMqConsumer.java

private void fireForType(String type, Message msg) {
    List<MessageReceivedListener> list = null;
    synchronized (this.messageListeners) {
        list = this.messageListeners.get(type);
    }/*  ww w. j  a va  2  s.c om*/

    if (list != null) {
        synchronized (list) {
            list.forEach(listener -> {
                listener.messageReceived(msg);
            });
        }
    }
}

From source file:at.christophwurst.orm.consoleclient.DbSeeder.java

public void seed() {
    TemporaryEmployee e1 = new TemporaryEmployee("Jane", "Doe", DateUtil.getDate(1970, 1, 2));
    e1.setStartDate(DateUtil.getDate(2015, 10, 11));
    e1.setEndDate(DateUtil.getDate(2016, 1, 11));
    e1.setHourlyRate(70);//from   w w  w  . ja  v a  2  s  . c  o  m
    PermanentEmployee e2 = new PermanentEmployee("John", "Doe", DateUtil.getDate(1970, 3, 4));
    e2.setSalary(5000);
    List<Employee> empls = new ArrayList<>();
    empls.add(e1);
    empls.add(e2);
    List<Sprint> sprints1 = new ArrayList<>();
    sprints1.add(new Sprint(1));
    sprints1.add(new Sprint(2));
    sprints1.add(new Sprint(3));
    Requirement r11 = new Requirement("Reqirement 1-1");
    sprints1.get(0).addRequirement(r11);
    Requirement r12 = new Requirement("Reqirement 1-2");
    sprints1.get(1).addRequirement(r12);
    Requirement r13 = new Requirement("Reqirement 1-3");
    sprints1.get(2).addRequirement(r13);
    Task t111 = new Task("Design 11");
    t111.setEstimatedTime(2);
    Task t112 = new Task("Implemnt 11");
    t112.setEstimatedTime(1);
    Task t113 = new Task("Test 11");
    t113.setEstimatedTime(2);
    Task t121 = new Task("Design 12");
    t121.setEstimatedTime(1);
    Task t122 = new Task("Implemnt 12");
    t122.setEstimatedTime(1);
    Task t131 = new Task("Design 13");
    t131.setEstimatedTime(3);
    List<Task> tasks = new ArrayList();
    tasks.add(t111);
    tasks.add(t112);
    tasks.add(t113);
    tasks.add(t121);
    tasks.add(t122);
    tasks.add(t131);
    tasks.forEach((Task t) -> {
        Random r = new Random();
        LogbookEntry lbe1 = new LogbookEntry("Design modules", DateUtil.getTime(2015, 12, 14, 8, 0),
                DateUtil.getTime(2015, 12, 14, 9, 0));
        lbe1.setEmployee(empls.get(r.nextInt(empls.size())));
        LogbookEntry lbe2 = new LogbookEntry("Design interfaces", DateUtil.getTime(2015, 12, 15, 9, 0),
                DateUtil.getTime(2015, 12, 15, 10, 0));
        lbe2.setEmployee(empls.get(r.nextInt(empls.size())));
        LogbookEntry lbe3 = new LogbookEntry("Document interfaces", DateUtil.getTime(2015, 12, 16, 10, 0),
                DateUtil.getTime(2015, 12, 16, 11, 0));
        lbe3.setEmployee(empls.get(r.nextInt(empls.size())));
        t.addLogbookEntry(lbe1);
        t.addLogbookEntry(lbe2);
        t.addLogbookEntry(lbe3);
    });
    r11.addTask(t111);
    r11.addTask(t112);
    r11.addTask(t113);
    r12.addTask(t121);
    r12.addTask(t122);
    r13.addTask(t131);

    Project p1 = new Project("Project A");
    p1.addMember(e1);
    p1.addMember(e2);
    p1.addRequirement(r11);
    p1.addRequirement(r12);
    p1.addRequirement(r13);
    Project p2 = new Project("Project B");
    p2.addSprint(new Sprint(1));
    p2.addSprint(new Sprint(2));
    p2.addSprint(new Sprint(3));
    p2.addMember(e2);

    projectRepository.save(p1);
    projectRepository.save(p2);
}

From source file:org.obiba.mica.micaConfig.service.helper.DceIdAggregationMetaDataHelper.java

@Cacheable(value = "aggregations-metadata", key = "'dce'")
public Map<String, AggregationMetaDataProvider.LocalizedMetaData> getDces() {
    try {/*from  w w  w  .  j  a v a2 s. c o  m*/
        List<BaseStudy> studies = sudo(
                () -> publishedStudyService.findAllByClassName(Study.class.getSimpleName()));
        Map<String, AggregationMetaDataProvider.LocalizedMetaData> map = Maps.newHashMap();

        studies.forEach(study -> {
            SortedSet<Population> pops = study.getPopulations();
            if (pops == null)
                return;
            pops.forEach(population -> {
                SortedSet<DataCollectionEvent> dces = population.getDataCollectionEvents();
                if (dces == null)
                    return;
                dces.forEach(dce -> mapIdToMetadata(map, study, population, dce));
            });
        });

        sudo(() -> publishedStudyService.findAllByClassName(HarmonizationStudy.class.getSimpleName())).stream()
                .forEach(hStudy -> hStudy.getPopulations().stream()
                        .forEach(population -> mapIdToMetadata(map, hStudy, population, null)));

        return map;
    } catch (Exception e) {
        log.debug("Could not build DCE aggregation metadata {}", e);
        return Maps.newHashMap();
    }
}

From source file:actors.DeployLogRelay.java

@Override
public void onReceive(final Object message) throws Exception {
    if ("check".equals(message)) {
        final List<DeploymentLog> logs = DeploymentLog.getLogsSince(_deployment, DeploymentLog.ref(_lastId));

        final ObjectNode node = JsonNodeFactory.instance.objectNode();
        final ArrayNode messages = node.putArray("messages");
        logs.forEach((logLine) -> messages.addObject().put("line", logLine.getMessage())
                .put("timestamp", logLine.getLogTime().toString()).put("host",
                        Optional.fromNullable(logLine.getHost()).transform(Host::getName).or("Deployment")));
        pushLog(node);// w ww  . j  a v a2  s .c om
        _lastId = Optional.fromNullable(Iterables.getLast(logs, null)).transform(DeploymentLog::getId)
                .or(_lastId);
        _deployment.refresh();
        _logger.info("Refreshed the deploy, finished=" + _deployment.getFinished());
        if (_deployment.getFinished() != null) {
            pushEnd();
            context().system().scheduler().scheduleOnce(FiniteDuration.apply(10, TimeUnit.SECONDS), self(),
                    "close", context().dispatcher(), self());
        }
    } else if ("close".equals(message)) {
        _channel.eofAndEnd();
        self().tell(PoisonPill.getInstance(), self());
    }
}