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.blackducksoftware.integration.hub.detect.detector.pear.PearParser.java

DependencyGraph createPearDependencyGraphFromList(final List<String> dependencyList,
        final List<String> dependencyNames) {
    final MutableDependencyGraph graph = new MutableMapDependencyGraph();

    if (dependencyList.size() > 3) {
        final List<String> listing = dependencyList.subList(3, dependencyList.size() - 1);
        listing.forEach(line -> {
            final String[] dependencyInfo = splitIgnoringWhitespace(line, " ");

            final String packageName = dependencyInfo[0].trim();
            final String packageVersion = dependencyInfo[1].trim();

            if (dependencyInfo.length > 0 && dependencyNames.contains(packageName)) {
                final Dependency child = new Dependency(packageName, packageVersion,
                        externalIdFactory.createNameVersionExternalId(Forge.PEAR, packageName, packageVersion));

                graph.addChildToRoot(child);
            }/*w w  w. ja  v  a 2  s. c o  m*/
        });
    }

    return graph;
}

From source file:de.mg.stock.server.logic.StockFacade.java

@POST
@Consumes(APPLICATION_XML)/*  w  w  w. jav  a 2 s.com*/
@Path("restore")
public Response restore(List<Stock> stocks) {

    if (!config.isWriteAccessEnabled()) {
        logger.warning("no write access!");

        return Response.status(Response.Status.FORBIDDEN)
                .entity("server missing -D" + Config.SWITCH_WRITE_ACCESS).build();
    }

    if (stocks == null || stocks.isEmpty()) {
        return Response.status(Response.Status.BAD_REQUEST).entity("missing xml in body").build();
    }
    logger.info("restore: " + stockStats(stocks));

    List<Stock> peristentStocks = backup();
    peristentStocks.forEach(stock -> em.remove(stock));
    em.flush();

    stocks.forEach(s -> {
        s.getDayPrices().forEach(dp -> dp.setStock(s));
        s.getInstantPrices().forEach(ip -> ip.setStock(s));
    });
    stocks.forEach(stock -> em.persist(stock));
    em.flush();

    String msg = String.format("successfully removed %d and inserted %d", peristentStocks.size(),
            stocks.size());
    logger.info(msg);
    return Response.status(Response.Status.OK).build();
}

From source file:com.github.viktornar.dao.AtlasDaoTest.java

@Before
public void setUp() {
    atlasDao = (AtlasDao) applicationContext.getBean("atlasDao");
    extentDao = (ExtentDao) applicationContext.getBean("extentDao");

    List<Extent> extents = Arrays.asList(new Extent(null, 1.0, 1.0, 1.0, 1.0),
            new Extent(null, 2.0, 2.0, 2.0, 2.0));

    atlases = new ArrayList<>();
    extents.forEach((extent) -> {
        extentDao.create(extent);//from  ww w.ja va2  s  .  co  m
        Atlas atlas = new Atlas(getRandomlyNames(8, 1)[0], "atlas", "atlas", 1, 1, "portrait", "letter", 0, 0,
                extent.getId());

        atlas.setExtent(extent);
        atlases.add(atlas);
    });
}

From source file:ai.susi.server.api.susi.SusiService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization user,
        final JsonObjectWithDefault permissions) throws APIException {

    // parameters
    String q = post.get("q", "").trim();
    int count = post.get("count", 1);
    int timezoneOffset = post.get("timezoneOffset", 0); // minutes, i.e. -60
    double latitude = post.get("latitude", Double.NaN); // i.e. 8.68 
    double longitude = post.get("longitude", Double.NaN); // i.e. 50.11
    String language = post.get("language", "en");
    try {/*from w w  w  .j  a  v  a  2 s.c o m*/
        DAO.susi.observe(); // get a database update
    } catch (IOException e) {
        DAO.log(e.getMessage());
    }

    // find out if we are dreaming
    SusiArgument observation_argument = new SusiArgument();
    List<SusiCognition> cognitions = DAO.susi.getMemories().getCognitions(user.getIdentity().getClient());
    cognitions.forEach(cognition -> observation_argument.think(cognition.recallDispute()));
    SusiThought recall = observation_argument.mindmeld(false);
    String etherpad_dream = recall.getObservation("_etherpad_dream");
    if (etherpad_dream != null && etherpad_dream.length() != 0) {
        // we are dreaming!
        // read the pad
        String etherpadApikey = DAO.getConfig("etherpad.apikey", "");
        String etherpadUrlstub = DAO.getConfig("etherpad.urlstub", "");
        String padurl = etherpadUrlstub + "/api/1/getText?apikey=" + etherpadApikey + "&padID=$query$";
        try {
            JSONTokener serviceResponse = new JSONTokener(
                    new ByteArrayInputStream(ConsoleService.loadData(padurl, etherpad_dream)));
            JSONObject json = new JSONObject(serviceResponse);
            String text = json.getJSONObject("data").getString("text");
            // fill an empty mind with the dream
            SusiMind dream = new SusiMind(null, null, DAO.susi_watch_dir); // an empty mind!
            JSONObject rules = dream.readSkills(new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)));
            dream.learn(rules);
            // susi is now dreaming.. Try to find an answer out of the dream
            SusiCognition cognition = new SusiCognition(dream, q, timezoneOffset, latitude, longitude, count,
                    user.getIdentity());
            if (cognition.getAnswers().size() > 0) {
                DAO.susi.getMemories().addCognition(user.getIdentity().getClient(), cognition);
                return cognition.getJSON();
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }

    // answer normally
    SusiCognition cognition = new SusiCognition(DAO.susi, q, timezoneOffset, latitude, longitude, count,
            user.getIdentity());
    cognition.setLanguage(language);
    DAO.susi.getMemories().addCognition(user.getIdentity().getClient(), cognition);
    JSONObject json = cognition.getJSON();
    return json;
}

From source file:com.bitbreeds.webrtc.sctp.impl.SendService.java

/**
 *
 * @param cumulativeTsnAck lowest ack we are sure everything below has been acknowledged
 * @param gaps the acknowledged groups offset from cumulativeTsnAck
 *
 * <a href=https://tools.ietf.org/html/rfc4960#section-3.3.4>SACK spec</a>
 */// w w w.java2s .  c  o m
protected void removeAllAcknowledged(long cumulativeTsnAck, List<SackUtil.GapAck> gaps) {
    gaps.forEach(i -> {
        Collection<Long> ls = sentTSNS.keySet().stream()
                .filter(j -> j >= (cumulativeTsnAck + i.start) && j <= (cumulativeTsnAck + i.end))
                .collect(Collectors.toSet());

        synchronized (dataMutex) {
            sentTSNS = sentTSNS.minusAll(ls);
        }
    });
}

From source file:fr.lepellerin.ecole.web.controller.cantine.ReservationRepasAnneeController.java

/**
 * initialise le form./*ww  w  .j a v  a2s . co m*/
 *
 * @return <code>DetaillerReservationRepasForm</code>
 * @throws TechnicalException 
 */
@ModelAttribute("command")
public ReserverRepasForm addCommand() throws TechnicalException {
    final CurrentUser user = (CurrentUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
    final ReserverRepasForm form = new ReserverRepasForm();
    final List<DayOfWeek> jours = this.cantineService.getJourOuvertCantine(LocalDate.now(),
            user.getUser().getFamille());
    jours.forEach(j -> {
        switch (j) {
        case MONDAY:
            form.setPresLundi(true);
            break;
        case TUESDAY:
            form.setPresMardi(true);
            break;
        case WEDNESDAY:
            form.setPresMercredi(true);
            break;
        case THURSDAY:
            form.setPresJeudi(true);
            break;
        case FRIDAY:
            form.setPresVendredi(true);
            break;
        case SATURDAY:
            form.setPresSamedi(true);
            break;
        case SUNDAY:
            form.setPresDimanche(true);
            break;
        default:
            break;
        }
    });
    return form;
}

From source file:io.spring.initializr.web.mapper.InitializrMetadataV2JsonMapper.java

protected Map<String, Object> links(JSONObject parent, List<Type> types, String appUrl) {
    Map<String, Object> content = new LinkedHashMap<>();
    types.forEach(it -> content.put(it.getId(), link(appUrl, it)));
    parent.put("_links", content);
    return content;
}

From source file:cognition.pipeline.data.PatientDao.java

private void setCarers(Individual individual) {
    SessionWrapper sessionWrapper = createSourceSession();
    try {//from   w  w  w. j a  v  a  2s  .  c o m
        Query getCarers = sessionWrapper.getNamedQuery("getCarers");
        getCarers.setParameter("patientId", individual.getId());
        List carerObjects = getCarers.list();
        carerObjects.forEach(object -> {
            Object[] carerRow = (Object[]) object;
            String name = clobHelper.getStringFromExpectedClob(carerRow[0]);
            String lastName = clobHelper.getStringFromExpectedClob(carerRow[1]);
            PatientCarer carer = new PatientCarer(name, lastName);
            individual.addCarer(carer);
        });
    } catch (Exception ex) {
        logger.warn("Error while loading carers of patient " + individual.getId()
                + ". Does the specified carer table exist? " + ex.getMessage());
    } finally {
        sessionWrapper.closeSession();
    }
}

From source file:de.hska.ld.core.controller.LogEntryController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST)
@Transactional//from ww  w. j ava  2  s .c om
public Callable addClientLogEntry(List<String> values) {
    return () -> {
        try {
            LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
            values.forEach(v -> {
                String[] splittedValue = v.split("###");
                String key = splittedValue[0];
                String value = splittedValue[1];
                LoggingContext.put(key, EscapeUtil.escapeJsonForLogging(value));
            });
            Logger.trace("Client-side logging event.");
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (Exception e) {
            Logger.error(e);
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } finally {
            LoggingContext.clear();
        }
    };
}

From source file:com.compomics.colims.distributed.io.maxquant.parsers.MaxQuantQuantificationSettingsParser.java

/**
 * This method is to create QuantificationReagent and its link to QuantificationMethodCvParam.
 *
 * @param quantificationMethod/*  w w w  .  j  a v  a  2s  . c  o m*/
 * @param quantificationLabel
 * @param reagents
 * @return QuantificationMethodHasReagents list
 */
public List<QuantificationMethodHasReagent> createQuantificationReagent(
        QuantificationMethod quantificationMethod, String quantificationLabel, List<String> reagents) {
    List<QuantificationMethodHasReagent> quantificationMethodHasReagents = new ArrayList<>();

    reagents.forEach(reagent -> {
        OntologyTerm ontologyTerm = null;
        if (quantificationLabel.equals(SILAC_LABEL)) {
            ontologyTerm = ontologyMapper.getColimsMapping().getQuantificationReagents().get(reagent);
        } else {
            ontologyTerm = ontologyMapper.getMaxQuantMapping().getQuantificationReagents().get(reagent);
        }

        QuantificationMethodHasReagent quantificationMethodHasReagent = new QuantificationMethodHasReagent();
        if (ontologyTerm != null) {
            QuantificationReagent quantificationReagent = new QuantificationReagent(
                    ontologyTerm.getOntologyPrefix(), ontologyTerm.getOboId(), ontologyTerm.getLabel());

            // check if quantificationReagent is in the db
            quantificationReagent = quantificationReagentService
                    .getQuantificationReagent(quantificationReagent);

            quantificationMethodHasReagent.setQuantificationReagent(quantificationReagent);
            quantificationMethodHasReagent.setQuantificationMethod(quantificationMethod);
            quantificationMethodHasReagents.add(quantificationMethodHasReagent);
        }
    });

    return quantificationMethodHasReagents;
}