List of usage examples for java.util.stream Stream generate
public static <T> Stream<T> generate(Supplier<? extends T> s)
From source file:Main.java
public static void main(String[] args) { Stream.generate(Math::random).limit(5).forEach(System.out::println); }
From source file:Main.java
public static void main(String[] args) { Stream.generate(new Random()::nextInt).limit(5).forEach(System.out::println); }
From source file:Main.java
public static void main(String[] args) { Stream.generate(new Random()::nextDouble).limit(10).forEach(System.out::println); }
From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineTestService.java
/** Entry point * @param args// w w w . j a v a 2 s . c o m * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 3) { System.out .println("ARGS: <script-file> <input-file> <output-prefix> [{[len: <LEN>], [group: <GROUP>]}]"); } // STEP 1: load script file final String user_script = Files.toString(new File(args[0]), Charsets.UTF_8); // STEP 2: get a stream for the JSON file final InputStream io_stream = new FileInputStream(new File(args[1])); // STEP 3: set up control if applicable Optional<JsonNode> json = Optional.of("").filter(__ -> args.length > 3).map(__ -> args[3]) .map(Lambdas.wrap_u(j -> _mapper.readTree(j))); // STEP 4: set up the various objects final DataBucketBean bucket = Mockito.mock(DataBucketBean.class); final JsScriptEngineService service_under_test = new JsScriptEngineService(); final LinkedList<ObjectNode> emitted = new LinkedList<>(); final LinkedList<JsonNode> grouped = new LinkedList<>(); final LinkedList<JsonNode> externally_emitted = new LinkedList<>(); final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class, new Answer<Void>() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) { try { Object[] args = invocation.getArguments(); if (invocation.getMethod().getName().equals("emitMutableObject")) { final Optional<JsonNode> grouping = (Optional<JsonNode>) args[3]; if (grouping.isPresent()) { grouped.add(grouping.get()); } emitted.add((ObjectNode) args[1]); } else if (invocation.getMethod().getName().equals("externalEmit")) { final DataBucketBean to = (DataBucketBean) args[0]; final Either<JsonNode, Map<String, Object>> out = (Either<JsonNode, Map<String, Object>>) args[1]; externally_emitted .add(((ObjectNode) out.left().value()).put("__a2_bucket", to.full_name())); } } catch (Exception e) { e.printStackTrace(); } return null; } }); final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class) .with(EnrichmentControlMetadataBean::config, new LinkedHashMap<String, Object>( ImmutableMap.<String, Object>builder().put("script", user_script).build())) .done().get(); service_under_test.onStageInitialize(context, bucket, control, Tuples._2T(ProcessingStage.batch, ProcessingStage.grouping), Optional.empty()); final BeJsonParser json_parser = new BeJsonParser(); // Run the file through final Stream<Tuple2<Long, IBatchRecord>> json_stream = StreamUtils .takeUntil(Stream.generate(() -> json_parser.getNextRecord(io_stream)), i -> null == i) .map(j -> Tuples._2T(0L, new BatchRecord(j))); service_under_test.onObjectBatch(json_stream, json.map(j -> j.get("len")).map(j -> (int) j.asLong(0L)), json.map(j -> j.get("group"))); System.out.println("RESULTS: "); System.out.println("emitted: " + emitted.size()); System.out.println("grouped: " + grouped.size()); System.out.println("externally emitted: " + externally_emitted.size()); Files.write(emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "emit.json"), Charsets.UTF_8); Files.write(grouped.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "group.json"), Charsets.UTF_8); Files.write(externally_emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "external_emit.json"), Charsets.UTF_8); }
From source file:alfio.controller.support.TemplateProcessorTest.java
@Test public void resultingImageMustBeUnder300x150() { Stream.generate( () -> Pair.of(String.valueOf(random.nextInt(10_000)), String.valueOf(random.nextInt(100_000)))) .limit(1000).forEach(this::assertDimensionsUnder300x150); }
From source file:com.watchrabbit.crawler.executor.strategy.PageContentWordsStrategy.java
@Override public List<String> generateKeywords(CrawlForm form, RemoteWebDriver driver) { String pageText = driver.findElement(By.tagName("body")).getText(); List<String> words = Stream.of(pageText.split("\\s")) .map(wordWithPunctation -> wordWithPunctation.replaceAll("[^a-zA-Z]", "")) .map(mixCaseWord -> mixCaseWord.toLowerCase()) .filter(anyWord -> anyWord.length() > 3 && anyWord.length() < 20).collect(toList()); Random random = new Random(); return Stream.generate(() -> random.nextInt() % words.size()) .map(index -> index < 0 ? index + words.size() : index).map(index -> words.get(index)).distinct() .limit(maximumKeywords).collect(toList()); }
From source file:com.nirmata.workflow.details.TestJsonSerializer.java
@Test public void testRunnableTask() { Map<TaskId, ExecutableTask> tasks = Stream.generate(() -> "").limit(random.nextInt(3) + 1) .collect(Collectors.toMap(s -> new TaskId(), s -> new ExecutableTask(new RunId(), new TaskId(), randomTaskType(), randomMap(), random.nextBoolean()))); List<RunnableTaskDag> taskDags = Stream.generate(() -> new RunnableTaskDag(new TaskId(), randomTasks())) .limit(random.nextInt(3) + 1).collect(Collectors.toList()); LocalDateTime completionTime = random.nextBoolean() ? LocalDateTime.now() : null; RunId parentRunId = random.nextBoolean() ? new RunId() : null; RunnableTask runnableTask = new RunnableTask(tasks, taskDags, LocalDateTime.now(), completionTime, parentRunId);// ww w .j a v a 2 s . c om JsonNode node = newRunnableTask(runnableTask); String str = nodeToString(node); System.out.println(str); RunnableTask unRunnableTask = getRunnableTask(fromString(str)); Assert.assertEquals(runnableTask, unRunnableTask); }
From source file:alfio.util.EventUtil.java
public static Stream<MapSqlParameterSource> generateStreamForTicketCreation(int limit) { return Stream.generate(MapSqlParameterSource::new).limit(limit); }
From source file:com.cloudbees.jenkins.support.filter.FilteredOutputStreamTest.java
@Test public void shouldSupportMultipleUsesWithReset() throws IOException { FilteredOutputStream out = new FilteredOutputStream(testOutput, s -> s); List<String> paragraphs = Stream.generate(() -> FAKE_TEXT).limit(10).collect(Collectors.toList()); StringBuilder b = new StringBuilder(); for (String paragraph : paragraphs) { out.write(paragraph.getBytes(UTF_8)); out.write('\n'); b.append(paragraph).append('\n'); out.reset();/*www .java2 s. c om*/ } String expected = b.toString(); assertThat(new String(testOutput.toByteArray(), UTF_8)).isNotEmpty().isEqualTo(expected); }
From source file:com.nirmata.workflow.details.TestJsonSerializer.java
private Map<String, String> randomMap() { return Stream.generate(random::nextInt).limit(random.nextInt(3) + 1) .collect(Collectors.toMap(n -> Integer.toString(n * 4), n -> Integer.toString(n * 2))); }