List of usage examples for java.util.stream Stream map
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
From source file:com.spankingrpgs.scarletmoon.loader.CharacterLoader.java
/** * Hydrates the character's primary statistics. * * @param statistics The JSON nodes containing the character's statistics * * @return The hydrated statistics//from ww w.ja va2 s. com */ private LinkedHashMap<String, Integer> hydrateStatistics(JsonNode statistics, Function<String, String> hydrateStatName, Stream<Enum> allStatisticNames) { LinkedHashMap<String, Integer> hydratedStatistics = new LinkedHashMap<>( PrimaryStatisticName.values().length); Iterator<String> statisticNames = statistics.fieldNames(); while (statisticNames.hasNext()) { String jsonStatisticName = statisticNames.next(); String statisticName = hydrateStatName.apply(jsonStatisticName); hydratedStatistics.put(statisticName, statistics.get(jsonStatisticName).asInt()); } allStatisticNames.map(Enum::name).filter(statistic -> !hydratedStatistics.containsKey(statistic)) .forEach(statistic -> hydratedStatistics.put(statistic, 0)); return hydratedStatistics; }
From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java
private Map<String, TopicVO> getTopicMetadata(String... topics) { if (kafkaVersion.compareTo(new Version(0, 9, 0)) >= 0) { return retryTemplate .execute(context -> brokerChannel(null).execute(channel -> getTopicMetadata(channel, topics))); } else {/*from w w w . j a v a 2s . com*/ Stream<String> topicStream; if (topics == null || topics.length == 0) { topicStream = Optional.ofNullable(topicTreeCache.getCurrentChildren(ZkUtils.BrokerTopicsPath())) .map(Map::keySet).map(Collection::stream).orElse(Stream.empty()); } else { topicStream = Stream.of(topics); } return topicStream.map(this::getTopicZkData).filter(Objects::nonNull) .collect(Collectors.toMap(TopicVO::getName, topic -> topic)); } }
From source file:com.sri.tasklearning.ui.core.term.ExerciseStepParameter.java
public boolean isRangeParameter() { if (vc != null) { String min = this.getCurrentValueConstraintMinLiteral() != null ? this.getCurrentValueConstraintMinLiteral().getString() : null;// w ww.j a va 2 s. c o m String max = this.getCurrentValueConstraintMaxLiteral() != null ? this.getCurrentValueConstraintMaxLiteral().getString() : null; if (min != null || max != null) return true; Set<String> types = getPossibleEnumTypes(false); Stream<String> stream = types.stream(); // Stream<String> stream2 = types.stream(); // stream2.map(x -> TypeUtilities.getUnqualifiedTypeName(x)).forEach(x -> System.out.println("Element " + x)); return stream.map(x -> TypeUtilities.getUnqualifiedTypeName(x)) .anyMatch(x -> NUMERIC_RANGE_TYPES.contains(x)); } return false; }
From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java
@Override public List<PageExperiment> getExperiments(Application.Name applicationName, Page.Name pageName) { Stream<PageExperimentByAppNamePage> resultList = Stream.empty(); try {/*from ww w . j a v a2 s . c o m*/ Result<PageExperimentByAppNamePage> result = pageExperimentIndexAccessor .selectBy(applicationName.toString(), pageName.toString()); resultList = StreamSupport .stream(Spliterators.spliteratorUnknownSize(result.iterator(), Spliterator.ORDERED), false); } catch (ReadTimeoutException | UnavailableException | NoHostAvailableException e) { throw new RepositoryException( new StringBuilder("Could not retrieve the experiments for applicationName:\"") .append(applicationName).append("\", page:\"").append(pageName).append("\"").toString(), e); } //TODO: make the experiment label part of the pageExperimentIndex to save a query per page return resultList.map(t -> { Optional<com.intuit.wasabi.repository.cassandra.pojo.Experiment> experiment = Optional .ofNullable(experimentAccessor.selectBy(t.getExperimentId()).one()); PageExperiment.Builder builder = new PageExperiment.Builder(Experiment.ID.valueOf(t.getExperimentId()), null, t.isAssign()); if (experiment.isPresent()) { builder.setLabel(Experiment.Label.valueOf(experiment.get().getLabel())); } return builder.build(); }).filter(t -> t.getLabel() != null).collect(Collectors.toList()); }
From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java
@Override public Optional<ConsumerVO> getConsumerByTopic(String groupId, TopicVO topic) { final ConsumerVO consumer = new ConsumerVO(groupId); final ZKGroupDirs groupDirs = new ZKGroupDirs(groupId); if (consumerTreeCache.getCurrentData(groupDirs.consumerGroupDir()) == null) return Optional.empty(); // todo: get number of threads in each instance (subscription -> topic -> # threads) Optional.ofNullable(consumerTreeCache.getCurrentChildren(groupDirs.consumerRegistryDir())) .ifPresent(children -> children.keySet().stream().map(id -> readConsumerRegistration(groupDirs, id)) .forEach(consumer::addActiveInstance)); Stream<String> topicStream = null; if (topic != null) { if (consumerTreeCache .getCurrentData(groupDirs.consumerGroupDir() + "/owners/" + topic.getName()) != null) { topicStream = Stream.of(topic.getName()); } else {/*from w w w.j a v a2 s .c o m*/ topicStream = Stream.empty(); } } else { topicStream = Optional .ofNullable(consumerTreeCache.getCurrentChildren(groupDirs.consumerGroupDir() + "/owners")) .map(Map::keySet).map(Collection::stream).orElse(Stream.empty()); } topicStream.map(ConsumerTopicVO::new).forEach(consumerTopic -> { getConsumerPartitionStream(groupId, consumerTopic.getTopic(), topic).forEach(consumerTopic::addOffset); consumer.addTopic(consumerTopic); }); return Optional.of(consumer); }
From source file:org.obiba.mica.network.rest.DraftNetworksResource.java
@GET @Path("/networks") @Timed//from ww w. j a v a 2s . c o m public List<Mica.NetworkSummaryDto> list(@QueryParam("study") String studyId, @QueryParam("query") String query, @QueryParam("from") @DefaultValue("0") Integer from, @QueryParam("limit") Integer limit, @Context HttpServletResponse response) { Stream<Network> result; long totalCount; if (limit == null) limit = MAX_LIMIT; if (limit < 0) throw new IllegalArgumentException("limit cannot be negative"); if (Strings.isNullOrEmpty(query)) { List<Network> networks = networkService.findAllNetworks(studyId).stream() .filter(n -> subjectAclService.isPermitted("/draft/network", "VIEW", n.getId())) .collect(toList()); totalCount = networks.size(); result = networks.stream().sorted((o1, o2) -> o1.getId().compareTo(o2.getId()))// .skip(from).limit(limit); } else { DocumentService.Documents<Network> networkDocuments = draftNetworkService.find(from, limit, null, null, studyId, query); totalCount = networkDocuments.getTotal(); result = networkService.findAllNetworks( networkDocuments.getList().stream().map(AbstractGitPersistable::getId).collect(toList())) .stream(); } response.addHeader("X-Total-Count", Long.toString(totalCount)); return result.map(n -> dtos.asSummaryDto(n, true)).collect(toList()); }
From source file:org.obiba.mica.project.rest.DraftProjectsResource.java
@GET @Path("/projects") @Timed/*from w ww. ja va 2 s. c o m*/ public Mica.ProjectsDto list(@QueryParam("query") String query, @QueryParam("from") @DefaultValue("0") Integer from, @QueryParam("limit") Integer limit, @Context HttpServletResponse response) { Stream<Project> result; long totalCount; if (limit == null) limit = MAX_LIMIT; if (limit < 0) throw new IllegalArgumentException("limit cannot be negative"); if (Strings.isNullOrEmpty(query)) { List<Project> projects = projectService.findAllProjects().stream() .filter(n -> subjectAclService.isPermitted("/draft/project", "VIEW", n.getId())) .collect(toList()); totalCount = projects.size(); result = projects.stream().sorted((o1, o2) -> o1.getId().compareTo(o2.getId())).skip(from).limit(limit); } else { DocumentService.Documents<Project> projectDocuments = draftProjectService.find(from, limit, null, null, null, query); totalCount = projectDocuments.getTotal(); result = projectService.findAllProjects( projectDocuments.getList().stream().map(AbstractGitPersistable::getId).collect(toList())) .stream(); } Mica.ProjectsDto.Builder builder = Mica.ProjectsDto.newBuilder(); builder.setFrom(from).setLimit(limit).setTotal(Long.valueOf(totalCount).intValue()); builder.addAllProjects(result.map(n -> dtos.asDto(n, true)).collect(toList())); if (subjectAclService.isPermitted("/draft/project", "ADD")) { builder.addActions("ADD"); } return builder.build(); }
From source file:org.talend.dataprep.preparation.service.PreparationService.java
/** * <p>/*from w ww .j a va 2 s . c om*/ * Search preparation entry point. * </p> * <p> * <p> * So far at least one search criteria can be processed at a time among the following ones : * <ul> * <li>dataset id</li> * <li>preparation name & exact match</li> * <li>folderId path</li> * </ul> * </p> * * @param dataSetId to search all preparations based on this dataset id. * @param folderId to search all preparations located in this folderId. * @param name to search all preparations that match this name. * @param exactMatch if true, the name matching must be exact. * @param sort Sort key (by name, creation date or modification date). * @param order Order for sort key (desc or asc). */ public Stream<UserPreparation> searchPreparations(String dataSetId, String folderId, String name, boolean exactMatch, Sort sort, Order order) { final Stream<Preparation> result; if (dataSetId != null) { result = searchByDataSet(dataSetId); } else if (folderId != null) { result = searchByFolder(folderId); } else { result = searchByName(name, exactMatch); } // convert & sort the result return result.map(p -> beanConversionService.convert(p, UserPreparation.class)) // .sorted(getPreparationComparator(sort, order, p -> getDatasetMetadata(p.getDataSetId()))); }
From source file:com.ikanow.aleph2.analytics.hadoop.assets.SampleReduceEnrichmentModule.java
@Override public void onObjectBatch(Stream<Tuple2<Long, IBatchRecord>> batch, Optional<Integer> batch_size, Optional<JsonNode> grouping_key) { // Just to make it simple // 2 different cases: // 1) If I'm a combiner or a single-step reducer, then count the batchs // and emit (key, count) // 2) If I'm the second stage of a combine-reduce then sum the counts Patterns.match(_stage.get()).andAct().when(s -> s == Stage.map, __ -> { batch.forEach(obj -> {/*from w w w. j a v a 2s .co m*/ final JsonNode new_grouping_key = _key_fields.get().stream().reduce(_mapper.createObjectNode(), (acc, v) -> { final Optional<String> key_field = JsonUtils.getProperty(v, obj._2().getJson()) .filter(j -> j.isTextual()).map(j -> j.asText()); return key_field.map(kf -> acc.put(v.replaceAll("__+", "_").replace(".", "__"), kf)) .orElse(acc); }, (acc1, acc2) -> acc1) // (not possible ; final ObjectNode to_output = _mapper.createObjectNode().put("count", 1); _logger.info("OUTPUT FROM MAP = " + to_output + " key " + new_grouping_key); _context.get().emitMutableObject(obj._1(), to_output, Optional.empty(), Optional.of(new_grouping_key)); }); }).otherwise(s -> { // combine or reduce final long count = batch.map(b -> Optional.ofNullable(b._2().getJson().get("count")) .filter(j -> j.isNumber()).map(j -> j.asLong()).orElse(0L)) .collect(Collectors.summingLong(l -> l)); final ObjectNode to_output = ((s == Stage.reduce) ? ((ObjectNode) grouping_key.get().deepCopy()) : _mapper.createObjectNode()).put("count", count); _logger.info("OUTPUT FROM COMBINE/REDUCE = " + to_output + " (stage=" + s + " key " + grouping_key); _context.get().emitMutableObject(0L, to_output, Optional.empty(), (s == Stage.reduce) ? Optional.empty() : grouping_key); }); }
From source file:fi.vm.sade.eperusteet.ylops.service.ops.impl.OpetussuunnitelmaServiceImpl.java
private void luoOpsPohjasta(Opetussuunnitelma pohja, Opetussuunnitelma ops) { ops.setPohja(pohja);/*from w ww .j a v a2 s . co m*/ if (pohja.getPerusteenDiaarinumero() == null) { throw new BusinessRuleViolationException("Pohjalta puuttuu perusteen diaarinumero"); } ops.setPerusteenDiaarinumero(pohja.getPerusteenDiaarinumero()); ops.setCachedPeruste(ops.getCachedPeruste()); if (ops.getCachedPeruste() == null) { PerusteDto peruste = eperusteetService.getPeruste(ops.getPerusteenDiaarinumero()); PerusteCache perusteCache = perusteCacheRepository.findNewestEntryForPeruste(peruste.getId()); if (perusteCache == null) { throw new BusinessRuleViolationException("Opetussuunnitelman pohjasta ei lytynyt perustetta"); } ops.setCachedPeruste(perusteCache); } boolean teeKopio = pohja.getTyyppi() == Tyyppi.POHJA; kasitteleTekstit(pohja.getTekstit(), ops.getTekstit(), teeKopio); boolean onPohjastaTehtyPohja = isPohjastaTehtyPohja(pohja); Copier<Oppiaine> oppiaineCopier = teeKopio ? Oppiaine.basicCopier() : Copier.nothing(); Map<Long, Oppiaine> newOppiaineByOld = new HashMap<>(); Copier<Oppiaine> kurssiCopier = null; if (pohja.getKoulutustyyppi().isLukio()) { luoLukiokoulutusPohjasta(pohja, ops); kurssiCopier = getLukiokurssitOppiaineCopier(pohja, ops, teeKopio); oppiaineCopier = oppiaineCopier.and(kurssiCopier).and((fromOa, toOa) -> { toOa.setAbstrakti(fromOa.getAbstrakti()); newOppiaineByOld.put(fromOa.getId(), toOa); }); } else if (teeKopio) { oppiaineCopier = oppiaineCopier.and(Oppiaine.perusopetusCopier()); } final Copier<Oppiaine> oppiainePerusCopier = oppiaineCopier; if (teeKopio && (!onPohjastaTehtyPohja || pohja.getKoulutustyyppi().isLukio())) { ConstructedCopier<Oppiaine> omConst = oppiainePerusCopier .construct(oa -> new Oppiaine(oa.getTunniste())); if (onPohjastaTehtyPohja && pohja.getKoulutustyyppi().isLukio()) { oppiaineCopier = oppiaineCopier.and(Oppiaine.oppimaaraCopier(om -> !om.isAbstraktiBool(), omConst)); } else { oppiaineCopier = oppiaineCopier.and(Oppiaine.oppimaaraCopier(omConst)); } } else if (kurssiCopier != null) { final Copier<Oppiaine> finalKurssiCopier = kurssiCopier; oppiaineCopier = oppiaineCopier.and((from, to) -> { if (from.isKoosteinen() && from.getOppiaine() == null) { from.getOppimaarat().forEach(om -> finalKurssiCopier.copy(om, om)); } }); } ConstructedCopier<OpsOppiaine> opsOppiaineCopier = OpsOppiaine.copier( oppiaineCopier.construct(existing -> teeKopio ? new Oppiaine(existing.getTunniste()) : existing), teeKopio); Stream<OpsOppiaine> oppiaineetToCopy = pohja.getKoulutustyyppi().isLukio() && pohja.getTyyppi() == Tyyppi.POHJA // ei kopioida pohjasta abstakteja yltason oppiaineita, mutta OPS:sta kyll ? pohja.getOppiaineet().stream().filter(opsOa -> !opsOa.getOppiaine().isAbstraktiBool()) : pohja.getOppiaineet().stream(); ops.setOppiaineet(oppiaineetToCopy.map(opsOppiaineCopier::copy).collect(toSet())); ops.getOppiaineJarjestykset().addAll(pohja.getOppiaineJarjestykset().stream() .map(old -> !teeKopio ? new LukioOppiaineJarjestys(ops, old.getOppiaine(), old.getJarjestys()) : (newOppiaineByOld.get(old.getId().getOppiaineId()) != null ? new LukioOppiaineJarjestys( ops, newOppiaineByOld.get(old.getId().getOppiaineId()), old.getJarjestys()) : null)) .filter(Objects::nonNull).collect(toSet())); Set<OpsVuosiluokkakokonaisuus> ovlkoot = pohja.getVuosiluokkakokonaisuudet().stream() .filter(ovlk -> ops.getVuosiluokkakokonaisuudet().stream() .anyMatch(vk -> vk.getVuosiluokkakokonaisuus().getTunniste() .equals(ovlk.getVuosiluokkakokonaisuus().getTunniste()))) .map(ovlk -> teeKopio ? new OpsVuosiluokkakokonaisuus( Vuosiluokkakokonaisuus.copyOf(ovlk.getVuosiluokkakokonaisuus()), true) : new OpsVuosiluokkakokonaisuus(ovlk.getVuosiluokkakokonaisuus(), false)) .collect(toSet()); ops.setVuosiluokkakokonaisuudet(ovlkoot); }