Java Code Examples for java.util.stream.Stream#findFirst()

The following examples show how to use java.util.stream.Stream#findFirst() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: teku   File: AttestationGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private Attestation createAttestation(
    final BeaconBlockAndState blockAndState,
    final boolean withValidSignature,
    final UnsignedLong slot) {
  UnsignedLong assignedSlot = slot;

  Optional<Attestation> attestation = Optional.empty();
  while (attestation.isEmpty()) {
    Stream<Attestation> attestations =
        withValidSignature
            ? streamAttestations(blockAndState, assignedSlot)
            : streamInvalidAttestations(blockAndState, assignedSlot);
    attestation = attestations.findFirst();
    assignedSlot = assignedSlot.plus(UnsignedLong.ONE);
  }

  return attestation.orElseThrow();
}
 
Example 2
Source Project: esjc   File: ITStreamEventsForward.java    License: MIT License 6 votes vote down vote up
@Test
public void failsToProcessDeletedStream() {
    final String stream = generateStreamName();

    eventstore.deleteStream(stream, ExpectedVersion.NO_STREAM, true).join();

    Stream<ResolvedEvent> eventStream = eventstore.streamEventsForward(stream, 0, 5, false);

    try {
        eventStream.findFirst();
        fail("should fail with 'StreamDeletedException'");
    } catch (Exception e) {
        assertThat(e, instanceOf(StreamDeletedException.class));
        assertEquals(stream, ((StreamDeletedException) e).stream);
    }
}
 
Example 3
Source Project: esjc   File: ITStreamEventsBackward.java    License: MIT License 6 votes vote down vote up
@Test
public void failsToProcessDeletedStream() {
    final String stream = generateStreamName();

    eventstore.deleteStream(stream, ExpectedVersion.NO_STREAM, true).join();

    Stream<ResolvedEvent> eventStream = eventstore.streamEventsBackward(stream, 0, 5, false);

    try {
        eventStream.findFirst();
        fail("should fail with 'StreamDeletedException'");
    } catch (Exception e) {
        assertThat(e, instanceOf(StreamDeletedException.class));
        assertEquals(stream, ((StreamDeletedException) e).stream);
    }
}
 
Example 4
Source Project: xenon   File: GridEngineSetup.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Try to find a parallel environment that can be used to get a number of cores on a single node
 *
 * @param coresPerNode
 *            number of cores to reserve on a node
 * @param queueName
 *            Name of the queue
 * @return optional parallel environment
 */
Optional<ParallelEnvironmentInfo> getSingleNodeParallelEnvironment(int coresPerNode, String queueName) {
    Stream<ParallelEnvironmentInfo> stream = this.parallelEnvironments.values().stream().filter(pe -> pe.canAllocateSingleNode(coresPerNode));
    // Filter pe on queue
    QueueInfo queue = queues.get(queueName);
    if (queue == null) {
        Set<String> pesOfQueues = new HashSet<>();
        for (QueueInfo q : queues.values()) {
            pesOfQueues.addAll(Arrays.asList(q.getParallelEnvironments()));
        }
        stream = stream.filter(pe -> pesOfQueues.contains(pe.getName()));
    } else {
        // don't know which queue the scheduler will pick, make sure at least one queue has the candidate pe
        Set<String> pesOfQueue = new HashSet<>(Arrays.asList(queue.getParallelEnvironments()));
        stream = stream.filter(pe -> pesOfQueue.contains(pe.getName()));
    }
    Optional<ParallelEnvironmentInfo> r = stream.findFirst();
    LOGGER.debug("Gridengine choose to use following pe: " + r.toString());
    return r;
}
 
Example 5
/**
 * Tries to get the mac address of the first device in alphabetic order, should be eth or en in most cases.
 * <p>
 * Warning: this method can take seconds to execute
 *
 * @return the first found hardware address
 * @throws SocketException
 * 		if an I/O error occurs.
 * @throws InvalidResultException
 * 		if no non-loopback network device exists.
 * @throws NullPointerException
 * 		if no network device exists.
 */
static String getHardwareAddress() throws SocketException {
	//Use hardware addresses as seed
	Stream<NetworkInterface> sortedStream = Collections.list(NetworkInterface.getNetworkInterfaces()).stream().filter(i -> {
		try {
			return i.getHardwareAddress() != null;
		} catch (SocketException e) {
			return false;
		}
	}).sorted(Comparator.comparing(NetworkInterface::getName));
	Optional<NetworkInterface> result = sortedStream.findFirst();
	if (!result.isPresent()) {
		throw new InvalidResultException("No non-loopback network interface exists");
	}
	return DatatypeConverter.printHexBinary(result.get().getHardwareAddress());
}
 
Example 6
/**
 * Peeks for the feature and outcome dimensions.
 * 
 * @param streamSupplier the supplier that gets streams.
 */
@VisibleForTesting
protected void peekDimensions(
    Supplier<Stream<FeatureOutcomePair>> streamSupplier) {
  Stream<FeatureOutcomePair> stream = Preconditions.checkNotNull(
      streamSupplier.get(), "Supplied a null stream!");
  Optional<FeatureOutcomePair> first = stream.findFirst();

  if (!first.isPresent()) {
    throw new IllegalArgumentException("Supplied an empty stream!");
  }

  FeatureOutcomePair firstExample = first.get();
  this.featureDimension = firstExample.getFeature().getDimension();
  this.outcomeDimension = firstExample.getOutcome().getDimension();
  this.numOutcomeClasses = Math.max(2, this.outcomeDimension);
}
 
Example 7
private IFunctionHandler matchFunctionHandler(NettyHttpRequest request) throws IllegalPathNotFoundException, IllegalMethodNotAllowedException {

        AtomicBoolean matched = new AtomicBoolean(false);

        Stream<Path> stream = functionHandlerMap.keySet().stream()
                .filter(((Predicate<Path>) path -> {
                    /**
                     *过滤 Path URI 不匹配的
                     */
                    if (request.matched(path.getUri(), path.isEqual())) {
                        matched.set(true);
                        return matched.get();
                    }
                    return false;

                }).and(path -> {
                    /**
                     * 过滤 Method 匹配的
                     */
                    return request.isAllowed(path.getMethod());
                }));

        Optional<Path> optional = stream.findFirst();

        stream.close();

        if (!optional.isPresent() && !matched.get()){
            throw  new IllegalPathNotFoundException();
        }

        if (!optional.isPresent() && matched.get()){
            throw  new IllegalMethodNotAllowedException();
        }

        return functionHandlerMap.get(optional.get());
    }
 
Example 8
@Override
public Stream<TestResultPayload> extract(Stream<TestStep> testSteps) {
    Stream<ScreenshotStepPayload> payloads = testSteps
            .flatMap(s -> s.getCombinedPayloadsOfType(ScreenshotStepPayload.class));

    Optional<ScreenshotStepPayload> first = payloads.findFirst();
    return first.map(screenshotStepPayload -> Stream.of(
            new TestResultPayload("screenshot", screenshotStepPayload.getBase64png())))
            .orElseGet(Stream::empty);
}
 
Example 9
Source Project: common-kafka   File: KafkaProducerPool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes all {@link Producer producers} that have been produced by this pool.
 * <p>
 * Any subsequent invocation of this method is ignored.
 * </p>
 *
 * @throws IOException
 *             if an error occurs during producer closure.
 *
 * {@inheritDoc}
 */
@Override
public void close() throws IOException {
    writeLock.lock();
    try {
        if (!shutdown) {
            shutdown = true;
            final Stream<Exception> exceptions = pool.values().stream()
                    .flatMap(Collection::stream)
                    .flatMap(producer -> {
                        try {
                            producer.close();
                        } catch (Exception e) {
                            LOGGER.error("Could not close producer", e);
                            return Stream.of(e);
                        }
                        return Stream.empty();
                    });

            // Throw exception if any of the producers in the pool could not be closed.
            final Optional<Exception> exception = exceptions.findFirst();
            if (exception.isPresent()) {
                throw new IOException(exception.get());
            }
        }
    } finally {
        writeLock.unlock();
    }
}
 
Example 10
@Test
public void testParseIdentifier() {
    String mockString = MCRMockIdentifier.MOCK_SCHEME + "http://google.de/";
    Stream<MCRPersistentIdentifier> mcrPersistentIdentifierStream = MCRPIManager
        .getInstance()
        .get(mockString);

    Optional<? extends MCRPersistentIdentifier> mcrMockIdentifier = mcrPersistentIdentifierStream
        .findFirst();
    Assert.assertEquals(mcrMockIdentifier.get().asString(), mockString);
}
 
Example 11
Source Project: estatio   File: Communication.java    License: Apache License 2.0 5 votes vote down vote up
@Programmatic
public Document findDocument(final String roleName) {
    final Stream<Document> documents = findDocumentsInRoleAsStream(roleName);
    final Optional<Document> documentIfAny = documents.findFirst();
    return documentIfAny.orElseThrow(() -> (RuntimeException)new ApplicationException(String.format(
            "Could not find document (via paperclip with role of '%s')",
            roleName)));
}
 
Example 12
Source Project: esjc   File: ITStreamEventsBackward.java    License: MIT License 5 votes vote down vote up
@Test
public void failsToProcessNonExistingStream() {
    final String stream = generateStreamName();

    Stream<ResolvedEvent> eventStream = eventstore.streamEventsBackward(stream, 0, 5, false);

    try {
        eventStream.findFirst();
        fail("should fail with 'StreamNotFoundException'");
    } catch (Exception e) {
        assertThat(e, instanceOf(StreamNotFoundException.class));
        assertEquals(stream, ((StreamNotFoundException) e).stream);
    }
}
 
Example 13
@Test
public void shouldGiveLogsInStream() {
    containerId = dockerClient.createContainerCmd(WANTED_IMAGE).withEnv(singletonList("WAITING_TIME=1ms"))
        .exec()
        .getId();
    dockerClient.startContainerCmd(containerId).exec();
    Stream<String> logs = defaultDockerClient.logs(containerId);
    Optional<String> firstLine = logs.findFirst();
    assertThat(firstLine).isPresent()
        .hasValueSatisfying("started"::equals);
}
 
Example 14
Source Project: vxms   File: RestRsRouteInitializer.java    License: Apache License 2.0 5 votes vote down vote up
private static void initHttpAll(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Optional<Method> errorMethod = errorMethodStream.findFirst();
    final Route route = router.route(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value() + HTTP_ALL + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpRoute(methodId, vxmsShared, service, restMethod, consumes, errorMethod, route);
}
 
Example 15
Source Project: batfish   File: PropertyChecker.java    License: Apache License 2.0 5 votes vote down vote up
public AnswerElement checkForwarding(NetworkSnapshot snapshot, HeaderQuestion question) {
  long totalTime = System.currentTimeMillis();
  HeaderQuestion q = new HeaderQuestion(question);
  q.setFailures(0);
  Tuple<Stream<Supplier<NetworkSlice>>, Long> ecs =
      findAllNetworkSlices(q, new Graph(_batfish, snapshot), true);
  Stream<Supplier<NetworkSlice>> stream = ecs.getFirst();
  Long timeAbstraction = ecs.getSecond();
  Optional<Supplier<NetworkSlice>> opt = stream.findFirst();
  if (!opt.isPresent()) {
    throw new BatfishException("Unexpected Error: checkForwarding");
  }
  long timeEc = System.currentTimeMillis();
  Supplier<NetworkSlice> sup = opt.get();
  NetworkSlice slice = sup.get();
  timeEc = System.currentTimeMillis() - timeEc;
  Graph g = slice.getGraph();
  q = new HeaderQuestion(q);
  q.setHeaderSpace(slice.getHeaderSpace());
  long timeEncoding = System.currentTimeMillis();
  Encoder encoder = new Encoder(g, q);
  encoder.computeEncoding();
  addEnvironmentConstraints(encoder, q.getBaseEnvironmentType());
  timeEncoding = System.currentTimeMillis() - timeEncoding;
  VerificationResult result = encoder.verify().getFirst();
  totalTime = System.currentTimeMillis() - totalTime;
  VerificationStats stats = result.getStats();
  if (q.getBenchmark()) {
    stats.setTimeCreateBdds((double) timeAbstraction);
    stats.setTotalTime(totalTime);
    stats.setAvgComputeEcTime(timeEc);
    stats.setMaxComputeEcTime(timeEc);
    stats.setMinComputeEcTime(timeEc);
    stats.setAvgEncodingTime(timeEncoding);
    stats.setMaxEncodingTime(timeEncoding);
    stats.setMinEncodingTime(timeEncoding);
    stats.setTimeCreateBdds((double) timeAbstraction);
  }
  return new SmtOneAnswerElement(result);
}
 
Example 16
Source Project: tutorials   File: SupplierStreamUnitTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void givenStream_whenStreamUsedTwice_thenThrowException() {
    Stream<String> stringStream = Stream.of("A", "B", "C", "D");
    Optional<String> result1 = stringStream.findAny();
    System.out.println(result1.get());
    Optional<String> result2 = stringStream.findFirst();
    System.out.println(result2.get());
}
 
Example 17
Source Project: beakerx   File: BeakerXCommRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Comm getCommByTargetName(String targetName) {
  Stream<Map.Entry<String, Comm>> entryStream = commMap.entrySet().stream().filter(x -> x.getValue().getTargetName().equals(targetName));
  Optional<Map.Entry<String, Comm>> first = entryStream.findFirst();
  if (first.isPresent()) {
    return first.get().getValue();
  }
  return null;
}
 
Example 18
Source Project: cineast   File: MediaSegmentReader.java    License: MIT License 4 votes vote down vote up
public Optional<MediaSegmentDescriptor> lookUpSegment(String segmentId) {
  Stream<MediaSegmentDescriptor> descriptors =
      this.lookUpSegmentsByField(FIELDNAMES[0], segmentId);
  return descriptors.findFirst();
}
 
Example 19
/**
 * Starts tests by compiling first generated DTO from maven plugin
 * @throws IOException if unable to start process
 * @throws InterruptedException if unable to wait the end of the process
 */
@Test(dependsOnGroups = "tools")
public void compileDTOAndLaunchTests() throws IOException, InterruptedException {

    // search DTO
    Path p = this.buildDirectory;
    final int maxDepth = 10;
    Stream<Path> matches = java.nio.file.Files.find( p, maxDepth, (path, basicFileAttributes) -> path.getFileName().toString().equals(GENERATED_DTO_NAME));

    // take first
    Optional<Path> optionalPath = matches.findFirst();
    if (!optionalPath.isPresent()) {
        throw new IllegalStateException("Unable to find generated DTO file named '" + GENERATED_DTO_NAME + "'. Check it has been generated first");
    }

    Path generatedDtoPath = optionalPath.get();

    //copy it in test resources folder where package.json is
    java.nio.file.Files.copy(generatedDtoPath, this.rootPath.resolve(DTO_FILENAME), StandardCopyOption.REPLACE_EXISTING);

    matches = java.nio.file.Files.find( p, maxDepth, (path, basicFileAttributes) -> path.getFileName().toString().equals(GENERATED_DTO_DTS_NAME));

    // take first
    optionalPath = matches.findFirst();
    if (!optionalPath.isPresent()) {
        throw new IllegalStateException("Unable to find generated DTO file named '" + GENERATED_DTO_DTS_NAME + "'. Check it has been generated first");
    }

    generatedDtoPath = optionalPath.get();

    //copy it in test resources folder where package.json is
    java.nio.file.Files.copy(generatedDtoPath, this.rootPath.resolve(DTO_DTS_FILENAME), StandardCopyOption.REPLACE_EXISTING);

    // setup command line
    List<String> command = getDockerExec();

    // avoid root permissions in generated files
    if (SystemInfo.isLinux()) {
        command.add(wrapLinuxCommand("npm test"));
    } else {
        command.add("npm test");
    }
    // setup typescript compiler
    ProcessBuilder processBuilder = new ProcessBuilder().command(command).directory(rootPath.toFile()).redirectErrorStream(true).inheritIO();
    Process process = processBuilder.start();

    LOG.info("Starting TypeScript tests...");
    int resultProcess = process.waitFor();

    if (resultProcess != 0) {
        throw new IllegalStateException("DTO has failed to compile");
    }
    LOG.info("TypeScript tests OK");

}
 
Example 20
Source Project: flow   File: JsoupUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Finds {@code "dom-module"} element inside the {@code parent}.
 * <p>
 * If {@code id} is provided then {@code "dom-module"} element is searched
 * with the given {@code id} value.
 *
 * @param parent
 *            the parent element
 * @param id
 *            optional id attribute value to search {@code "dom-module"}
 *            element, may be {@code null}
 * @return
 */
static Optional<Element> getDomModule(Element parent, String id) {
    Stream<Element> stream = parent.getElementsByTag("dom-module").stream();
    if (id != null) {
        stream = stream.filter(element -> id.equals(element.id()));
    }
    return stream.findFirst();
}