Example usage for java.util.stream Stream findFirst

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

Introduction

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

Prototype

Optional<T> findFirst();

Source Link

Document

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

Usage

From source file:ru.anr.base.BaseParent.java

/**
 * A short-cut method for finding the first item in the given stream.
 * //w  w w .  j ava2s.  c  o  m
 * @param stream
 *            A stream
 * @return The resulted value if it exists, otherwise null
 * 
 * @param <S>
 *            The type of stream's elements
 */
public static <S> S first(Stream<S> stream) {

    return (stream == null) ? null : stream.findFirst().orElse(null);
}

From source file:com.juliuskrah.multipart.repository.AccountRepositoryTest.java

@Test
public void testFindByLastName() {
    Stream<Account> accountStream = accountRepository.findByLastName("Krah");
    assertThat(accountStream, notNullValue());
    assertThat(accountStream.findFirst().get().getUsername(), is("julius"));
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private void tryToSave(final String contextPath) {
    final Set<CollectedData> data = RECORDED_DATA.replace(contextPath, new HashSet<>());
    if (CollectionUtils.isEmpty(data)) {
        log.debug("Nothing to save, exiting");
        return;/*w ww  .  jav a2  s . co m*/
    }
    String name;
    do {
        name = showInputDialog(null, getMessage("session.record.save.as"),
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));

    } while (StringUtils.isEmpty(name) && !GuiUtils.showWarning(null, getMessage("warning.message")));

    if (StringUtils.isNotEmpty(name)) {
        final CollectedData collectedData;
        if (data.size() > 1) {
            final Stream<CollectedData> stream = data.stream();
            CollectedData aggregated = CollectedData.empty(stream.findFirst().get().getRequestURI(),
                    contextPath);
            collectedData = stream.reduce(aggregated, CollectedData::join);
        } else {
            collectedData = data.iterator().next();
        }
        collectedDataRepository.saveRecordedSession(name, collectedData);

        eventManager.publishEvent(
                new SessionRecorded(this, name, getMessage("session.recorded.status.message", name)));
    }
}

From source file:onl.area51.gfs.grib2.job.GribRetriever.java

/**
 * Select the specified run.// w  w  w  . j av a2s . c  om
 * <p>
 * @param date The date and hour of the required run
 * <p>
 * @throws java.io.IOException
 */
public void selectRun(LocalDateTime date) throws IOException {
    LOG.log(Level.INFO, "Retrieving directory listing");
    client.changeWorkingDirectory(DIR);
    Stream<FTPFile> dirs = client.directories().filter(f -> f.getName().startsWith("gfs."));

    if (date == null) {
        // Look for the most recent date
        dirs = dirs.sorted((a, b) -> b.getName().compareToIgnoreCase(a.getName()));
    } else {
        // Look for a specific date
        String filter = "gfs." + toGFSRunTime(date).format(DateTimeFormatter.BASIC_ISO_DATE);
        dirs = dirs.filter(f -> filter.equals(f.getName()));
    }

    @SuppressWarnings("ThrowableInstanceNotThrown")
    FTPFile dir = dirs.findFirst()
            .orElseThrow(() -> new FileNotFoundException("Failed to find remote gfs directory "));

    client.changeWorkingDirectory(dir.getName());
    String pwd = client.printWorkingDirectory();
    LOG.log(Level.INFO, () -> "Now in directory " + pwd);
}

From source file:org.fcrepo.kernel.modeshape.FedoraResourceImplTest.java

@Test
public void testGetChildrenWithEmptyChildren() throws RepositoryException {
    when(mockNode.getNodes()).thenReturn(nodeIterator());
    final Stream<FedoraResource> children = testObj.getChildren();

    assertFalse("Expected an empty stream", children.findFirst().isPresent());
}

From source file:org.fcrepo.kernel.modeshape.FedoraResourceImplTest.java

@Test
public void testGetChildrenExcludesModeSystem() throws RepositoryException {
    when(mockNode.getNodes()).thenReturn(nodeIterator(mockChild));
    when(mockChild.isNodeType("mode:system")).thenReturn(true);
    when(mockChild.getName()).thenReturn("x");
    final Stream<FedoraResource> children = testObj.getChildren();
    assertFalse("Expected an empty stream", children.findFirst().isPresent());
}

From source file:org.fcrepo.kernel.modeshape.FedoraResourceImplTest.java

@Test
public void testGetChildrenExcludesTombstones() throws RepositoryException {
    when(mockNode.getNodes()).thenReturn(nodeIterator(mockChild));
    when(mockChild.isNodeType(FEDORA_TOMBSTONE)).thenReturn(true);
    when(mockChild.getName()).thenReturn("x");
    final Stream<FedoraResource> children = testObj.getChildren();
    assertFalse("Expected an empty stream", children.findFirst().isPresent());
}

From source file:org.fcrepo.kernel.modeshape.FedoraResourceImplTest.java

@Test
public void testGetChildrenExcludesJcrContent() throws RepositoryException {
    when(mockNode.getNodes()).thenReturn(nodeIterator(mockChild));
    when(mockChild.getName()).thenReturn(JCR_CONTENT);
    final Stream<FedoraResource> children = testObj.getChildren();
    assertFalse("Expected an empty stream", children.findFirst().isPresent());
}

From source file:org.silverpeas.core.notification.user.client.NotificationManagerSettings.java

/**
 * Gets the addresses as default notification channels. If the multi channel isn't supported,
 * then//ww w .ja va2 s .  c  o m
 * returns only one among the channels set up as default. In the case no default channels are set
 * up, then the previous behaviour is used; the SMTP is used as default channel.
 * @return a set of default notification channels.
 */
static List<NotifChannel> getDefaultChannels() {
    final String defaultChannelSetting = settings.getString("notif.defaultChannels", "");
    final boolean isMultiChannelSupported = isMultiChannelNotificationEnabled();
    final String[] defaultChannels = defaultChannelSetting.replaceAll("[ ]{2,}", " ").split(" ");
    final List<NotifChannel> channels;
    final Stream<NotifChannel> streamOfChannels = Stream.of(defaultChannels).map(NotifChannel::decode)
            .filter(Optional::isPresent).map(Optional::get);
    if (!isMultiChannelSupported) {
        channels = new ArrayList<>(1);
        channels.add(streamOfChannels.findFirst().orElse(NotifChannel.SMTP));
    } else {
        channels = streamOfChannels.distinct().collect(Collectors.toList());
    }
    if (channels.isEmpty()) {
        channels.add(NotifChannel.SMTP);
    }
    return channels;
}

From source file:org.zanata.sync.plugin.zanata.util.PushPullOptionsUtil.java

public static Optional<File> findProjectConfig(File repoBase) {
    try {/*from  w  ww  . j av  a  2  s.  c om*/
        Stream<Path> pathStream = Files.find(repoBase.toPath(), MAX_DEPTH,
                (path, basicFileAttributes) -> basicFileAttributes.isRegularFile()
                        && path.toFile().getName().equals("zanata.xml"));
        Optional<Path> projectConfig = pathStream.findFirst();
        return projectConfig.flatMap(path -> Optional.ofNullable(path.toFile()));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}