Example usage for java.util.stream Stream concat

List of usage examples for java.util.stream Stream concat

Introduction

In this page you can find the example usage for java.util.stream Stream concat.

Prototype

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) 

Source Link

Document

Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

Usage

From source file:org.lightjason.trafficsimulation.simulation.IBaseObject.java

@Override
public final Stream<ILiteral> literal(final Stream<IObject<?>> p_object) {
    return Stream
            .of(CLiteral/*  w  w  w  . j a  v  a  2 s  . c  o m*/
                    .from(m_functor,
                            Stream.concat(
                                    Stream.concat(Stream.of(CLiteral.from("name", CRawTerm.from(m_name))),
                                            m_external.stream().map(i -> i.shallowcopysuffix()).sorted()
                                                    .sequential()),
                                    this.individualliteral(p_object).sorted().sequential())));
}

From source file:org.codice.ddf.catalog.ui.forms.SearchFormsLoader.java

public List<Metacard> retrieveSystemTemplateMetacards() {
    if (!formsDirectory.exists()) {
        LOGGER.warn("Could not locate forms directory [{}]", formsDirectory.getAbsolutePath());
        return Collections.emptyList();
    }//w  w  w  .j av  a  2s. com

    File formsFile = formsDirectory.toPath().resolve(formsFileName).toFile();
    File resultsFile = formsDirectory.toPath().resolve(resultsFileName).toFile();

    return Stream.concat(loadFile(formsFile, this::formMapper), loadFile(resultsFile, this::resultsMapper))
            .collect(Collectors.toList());
}

From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

private void assertCollectdConfIsValid() throws Exception {
    collectdOut = temporaryFolder.newFile();
    collectdErr = temporaryFolder.newFile();

    collectdProcessBuilder = new ProcessBuilder();
    collectdProcessBuilder.directory(temporaryFolder.getRoot());
    collectdProcessBuilder.redirectOutput(collectdOut);
    collectdProcessBuilder.redirectError(collectdErr);

    collectdProcessBuilder.command(COLLECTD_PATH, "-C", collectdConfFile.getAbsolutePath(), "-t", "-T", "-f");

    collectdProcess = collectdProcessBuilder.start();

    int exitCode = collectdProcess.waitFor();
    assertEquals("Collectd configuration doesn't seem to be valid", 0, exitCode);

    boolean hasErrorInLog = Stream.concat(Files.lines(collectdOut.toPath()), Files.lines(collectdErr.toPath()))
            .anyMatch(l -> l.contains("[error]"));
    assertFalse("Collectd configuration doesn't seem to be valid", hasErrorInLog);
}

From source file:alfio.controller.api.admin.AdditionalServiceApiController.java

@RequestMapping(value = "/event/{eventId}/additional-services/{additionalServiceId}", method = RequestMethod.PUT)
@Transactional//from   w  w  w  .  j ava 2  s  .  c om
public ResponseEntity<EventModification.AdditionalService> update(@PathVariable("eventId") int eventId,
        @PathVariable("additionalServiceId") int additionalServiceId,
        @RequestBody EventModification.AdditionalService additionalService, BindingResult bindingResult) {
    ValidationResult validationResult = Validator.validateAdditionalService(additionalService, bindingResult);
    Validate.isTrue(validationResult.isSuccess(), "validation failed");
    Validate.isTrue(additionalServiceId == additionalService.getId(), "wrong input");
    return eventRepository.findOptionalById(eventId).map(event -> {
        int result = additionalServiceRepository.update(additionalServiceId, additionalService.isFixPrice(),
                additionalService.getOrdinal(), additionalService.getAvailableQuantity(),
                additionalService.getMaxQtyPerOrder(),
                additionalService.getInception().toZonedDateTime(event.getZoneId()),
                additionalService.getExpiration().toZonedDateTime(event.getZoneId()),
                additionalService.getVat(), additionalService.getVatType(),
                Optional.ofNullable(additionalService.getPrice()).map(MonetaryUtil::unitToCents).orElse(0));
        Validate.isTrue(result <= 1, "too many records updated");
        Stream.concat(additionalService.getTitle().stream(), additionalService.getDescription().stream())
                .forEach(t -> {
                    if (t.getId() != null) {
                        additionalServiceTextRepository.update(t.getId(), t.getLocale(), t.getType(),
                                t.getValue());
                    } else {
                        additionalServiceTextRepository.insert(additionalService.getId(), t.getLocale(),
                                t.getType(), t.getValue());
                    }
                });
        return ResponseEntity.ok(additionalService);
    }).orElseThrow(IllegalArgumentException::new);
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

@Override
public void update() {

    // For all resources in the registry, get the URIs of everything that calls itself a Service, or is explicitly
    // registered as a service

    final Set<URI> serviceURIs = Stream.concat(super.list().stream().map(this::get).map(Util::parse)
            .flatMap(m -> m.listSubjectsWithProperty(m.getProperty(RDF_TYPE), m.getResource(CLASS_SERVICE))
                    .mapWith(Resource::getURI).toSet().stream().map(URI::create)),
            objectResourcesOf(null, PROP_CONTAINS_SERVICE, parse(this.get(registryContainer))).stream())
            .collect(Collectors.toSet());

    // Map canonical URI to service resource. If multiple service resources
    // indicate the same canonical URI, pick one arbitrarily.
    final Map<URI, URI> canonical = serviceURIs.stream().flatMap(this::attemptLookupService)
            .collect(Collectors.toMap(s -> s.canonicalURI(), s -> s.uri(), (a, b) -> a));

    canonicalUriMap.putAll(canonical);/*from w  w  w.  j  ava 2 s  . c  om*/

    canonicalUriMap.keySet().removeIf(k -> !canonical.containsKey(k));
}

From source file:nl.knaw.huygens.alexandria.query.AlexandriaQueryParser.java

private Function<Storage, Stream<AnnotationVF>> createAnnotationVFFinder(List<WhereToken> resourceWhereTokens) {
    WhereToken resourceWhereToken = resourceWhereTokens.get(0);
    if (resourceWhereTokens.size() == 1 && resourceWhereToken.getFunction().equals(QueryFunction.eq)) {
        String uuid = (String) resourceWhereToken.getParameters().get(0);
        return storage -> {
            Optional<ResourceVF> optionalResource = storage.readVF(ResourceVF.class, UUID.fromString(uuid));
            if (optionalResource.isPresent()) {
                ResourceVF resourceVF = optionalResource.get();
                Stream<AnnotationVF> resourceAnnotationsStream = resourceVF.getAnnotatedBy().stream();
                Stream<AnnotationVF> subresourceAnnotationsStream = resourceVF.getSubResources().stream()//
                        .flatMap(rvf -> rvf.getAnnotatedBy().stream());
                return Stream.concat(resourceAnnotationsStream, subresourceAnnotationsStream);
            }//from  w w  w  .j a va  2  s  .  c  om
            // Should return error, since no resource found with given uuid
            return ImmutableList.<AnnotationVF>of().stream();
        };

    }
    return null;
}

From source file:org.lightjason.examples.pokemon.CMain.java

/**
 * execute simulation/*from  w  ww.j  ava 2  s .  c  o m*/
 *
 * @param p_screen screen reference
 */
private static void execute(final CScreen p_screen) {
    IntStream.range(0, CConfiguration.INSTANCE.simulationsteps()).mapToObj(i -> {
        // update screen take screenshot and run object execution
        p_screen.iteration(i);
        Stream.concat(Stream.of(
                //CConfiguration.INSTANCE.evaluation(),
                CConfiguration.INSTANCE.environment()),
                Stream.concat(CConfiguration.INSTANCE.staticelements().parallelStream(),
                        CConfiguration.INSTANCE.agents().parallelStream()))
                .parallel().forEach(j -> {
                    try {
                        j.call();
                    } catch (final Exception l_exception) {
                        LOGGER.warning(l_exception.toString());
                        if (CConfiguration.INSTANCE.stackstrace())
                            l_exception.printStackTrace(System.err);
                    }
                });

        // thread sleep for slowing down
        if (CConfiguration.INSTANCE.threadsleeptime() > 0)
            try {
                Thread.sleep(CConfiguration.INSTANCE.threadsleeptime());
            } catch (final InterruptedException l_exception) {
                LOGGER.warning(l_exception.toString());
            }

        // checks that the simulation is closed
        return p_screen.isDisposed();
    }).filter(i -> i).findFirst();
}

From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> grouping_fields) {
    // This is currently fixed:
    java_api.set(true);/* w ww.  j ava 2  s  .  c  o  m*/

    final JsScriptEngineBean config_bean = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()),
                    JsScriptEngineBean.class)
            .get();
    _config.trySet(config_bean);
    _context.trySet(context);
    _control.trySet(control);

    // Initialize script engine:
    ScriptEngineManager manager = new ScriptEngineManager();
    _engine.trySet(manager.getEngineByName("JavaScript"));
    _script_context.trySet(_engine.get().getContext()); // (actually not needed since we're compiling things)

    _bucket_logger.set(context.getLogger(Optional.of(bucket)));

    // Load globals:
    _engine.get().put("_a2_global_context", _context.get());
    _engine.get().put("_a2_global_grouping_fields", grouping_fields.orElse(Collections.emptyList()));
    _engine.get().put("_a2_global_previous_stage", previous_next._1().toString());
    _engine.get().put("_a2_global_next_stage", previous_next._2().toString());
    _engine.get().put("_a2_global_bucket", bucket);
    _engine.get().put("_a2_global_config", BeanTemplateUtils.configureMapper(Optional.empty())
            .convertValue(config_bean.config(), JsonNode.class));
    _engine.get().put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
    _engine.get().put("_a2_bucket_logger", _bucket_logger.optional().orElse(null));
    _engine.get().put("_a2_enrichment_name", Optional.ofNullable(control.name()).orElse("no_name"));

    // Load the resources:
    Stream.concat(config_bean.imports().stream(),
            Stream.of("aleph2_js_globals_before.js", "", "aleph2_js_globals_after.js"))
            .flatMap(Lambdas.flatWrap_i(import_path -> {
                try {
                    if (import_path.equals("")) { // also import the user script just before here
                        return config_bean.script();
                    } else
                        return IOUtils.toString(
                                JsScriptEngineService.class.getClassLoader().getResourceAsStream(import_path),
                                "UTF-8");
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (script {1}): {2}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), import_path,
                                    e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            })).forEach(Lambdas.wrap_consumer_i(script -> {
                try {
                    _engine.get().eval(script);
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (main script): {1}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            }));
    ;
}

From source file:org.lightjason.agentspeak.consistency.TestCMetric.java

/**
 * test symmetric metric equality//  w w w  .  ja  va  2s .co  m
 */
@Test
public final void weightinequality() {
    Assume.assumeNotNull(m_literals);
    Assume.assumeFalse("testing literals are empty", m_literals.isEmpty());

    this.check("weight difference inequality", new CAll(), new CWeightedDifference(), m_literals,
            Stream.concat(m_literals.stream(), Stream.of(CLiteral.from("diff"))).collect(Collectors.toSet()),
            28 + 1.0 / 6, 0);
}

From source file:com.wormsim.animals.AnimalStage2.java

@Override
public String toRecentBetweenVarianceString() {
    return Stream
            .concat(Stream.concat(Stream.concat(Stream.of(food_rate), Stream.of(pheromone_rates)),
                    Stream.of(dev_time)), Stream.of(development))
            .filter((v) -> v.isVisiblyTracked()).map((v) -> v.toRecentBetweenVarianceString())
            .collect(Utils.TAB_JOINING);
}