Example usage for java.util List stream

List of usage examples for java.util List stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:org.apache.nifi.minifi.integration.util.LogUtil.java

public static void verifyLogEntries(String expectedJsonFilename, Container container) throws Exception {
    List<ExpectedLogEntry> expectedLogEntries;
    try (InputStream inputStream = LogUtil.class.getClassLoader().getResourceAsStream(expectedJsonFilename)) {
        List<Map<String, Object>> expected = new ObjectMapper().readValue(inputStream, List.class);
        expectedLogEntries = expected.stream()
                .map(map -> new ExpectedLogEntry(Pattern.compile((String) map.get("pattern")),
                        (int) map.getOrDefault("occurrences", 1)))
                .collect(Collectors.toList());
    }//from   w  w  w.  j a  v  a  2 s .com
    DockerPort dockerPort = container.port(8000);
    URL url = new URL("http://" + dockerPort.getIp() + ":" + dockerPort.getExternalPort());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try (InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
        String line;
        for (ExpectedLogEntry expectedLogEntry : expectedLogEntries) {
            boolean satisfied = false;
            int occurrences = 0;
            while ((line = bufferedReader.readLine()) != null) {
                if (expectedLogEntry.pattern.matcher(line).find()) {
                    logger.info("Found expected: " + line);
                    if (++occurrences >= expectedLogEntry.numOccurrences) {
                        logger.info("Found target " + occurrences + " times");
                        satisfied = true;
                        break;
                    }
                }
            }
            if (!satisfied) {
                fail("End of log reached without " + expectedLogEntry.numOccurrences + " match(es) of "
                        + expectedLogEntry.pattern);
            }
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:cz.lbenda.common.ClassLoaderHelper.java

/** Stream of class which is in given packages
 * @param basePackage base package// w  ww .  ja  va  2  s  .  c  om
 * @param classLoader class loader where is classes found
 * @return stream of class names */
public static List<String> classInPackage(String basePackage, ClassLoader classLoader) {
    List<String> result = new ArrayList<>();
    try {
        for (Enumeration<URL> resources = classLoader.getResources(basePackage.replace(".", "/")); resources
                .hasMoreElements();) {
            URL url = resources.nextElement();
            if (String.valueOf(url).startsWith("file:")) {
                File file = new File(url.getFile());
                int prefixLength = url.getFile().length() - basePackage.length();
                List<File> files = subClasses(file);
                files.stream().forEach(f -> {
                    String fName = f.getAbsolutePath();
                    result.add(fName.substring(prefixLength, fName.length() - 6).replace("/", "."));
                });
            } else {
                URLConnection urlCon = url.openConnection();
                if (urlCon instanceof JarURLConnection) {
                    JarURLConnection jarURLConnection = (JarURLConnection) urlCon;
                    try (JarFile jar = jarURLConnection.getJarFile()) {
                        jar.stream().forEach(entry -> {
                            String entryName = entry.getName();
                            if (entryName.endsWith(".class") && entryName.startsWith(basePackage)) {
                                result.add(entryName.substring(0, entryName.length() - 6));
                            }
                        });
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.fede.util.Util.java

public static MoneyAmountSeries sumSeries(String currency, List<ExpenseChartSeriesDTO> dtos) {
    return sumSeries(currency, dtos.stream().map(dto -> dto.getSeriesName()).toArray(String[]::new));
}

From source file:net.consulion.jeotag.PhotoLoader.java

public static void load(final List<File> files) {
    final List<PhotoDataset> photos = new ArrayList<>(files.size());
    files.stream().forEach((file) -> {
        final PhotoDataset photoDataset = new PhotoDataset(file);
        final TiffImageMetadata exif = getExif(file);
        if (exif != null) {
            final Instant timeTaken = getTimeTaken(exif, file);
            if (timeTaken != null) {
                photoDataset.setInstantTaken(timeTaken);
                photoDataset.setHasGeotag(photoHasGeotag(exif, file));
                photos.add(photoDataset);
            } else {
                log(Level.ALL, String.format("Couldn't parse date/time for file %s", file));
            }//from   www.j  a  v  a  2 s.c om
        } else {
            log(Level.WARNING, String.format("No EXIF metadata found for file %s", file));
        }
    });
    DataHolder.getInstance().addPhotos(photos);
}

From source file:com.khartec.waltz.jobs.sample.BusinessRegionProductHierarchyGenerator.java

private static Set<String> readProducts() throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/products-flat.csv"));
    Set<String> productHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ",")).filter(cells -> notEmpty(cells[0]))
            .map(cells -> cells[0]).collect(toSet());

    return productHierarchy;
}

From source file:Main.java

/**
 * Convenient method to chain iterables together.
 * @param iterables to chain//ww  w . j a va 2 s . com
 * @return chained iterator
 */
public static <T> Iterator chain(Iterator<T>... iterables) {
    List<Iterator<T>> iterableList = Arrays.asList(iterables);
    return new Iterator<T>() {
        @Override
        public boolean hasNext() {
            return iterableList.stream().anyMatch(Iterator::hasNext);
        }

        @Override
        public T next() {
            return iterableList.stream().filter(Iterator::hasNext).findFirst().map(Iterator::next).orElse(null);
        }
    };
}

From source file:dk.dbc.DevelMain.java

private static String findAdminUrl(String yamlFileName) throws IOException {
    String port = System.getProperty("dw.server.adminConnectors[0].port");

    if (port != null) {
        port = "http://localhost:" + port + "/";
    } else {/* w  w w.  ja v  a 2  s.c o  m*/
        try (FileInputStream is = new FileInputStream(yamlFileName)) {
            String yaml = readInputStream(is);

            ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
            Map<String, Object> obj = (Map<String, Object>) yamlReader.readValue(yaml, Object.class);
            log.debug("obj = " + obj);
            if (obj.get("server") != null && obj.get("server") instanceof Map) {
                Map<String, Object> server = (Map<String, Object>) obj.get("server");
                if (server.get("adminConnectors") != null && server.get("adminConnectors") instanceof List) {
                    List<Object> adminConnectors = (List<Object>) server.get("adminConnectors");
                    Map<String, Object> set = adminConnectors.stream().filter(e -> e instanceof Map)
                            .map(e -> (Map<String, Object>) e).filter(e -> "http".equals(e.get("type")))
                            .findFirst().orElse(null);
                    port = String.valueOf(set.get("type")) + "://localhost:" + String.valueOf(set.get("port"))
                            + "/";
                }
            }
        }
    }
    if (port == null) {
        port = "http://localhost:8080/";
    }
    return port;
}

From source file:com.github.horrorho.inflatabledonkey.cloud.clients.AssetTokenClient.java

public static List<Asset> assets(HttpClient httpClient, CloudKitty kitty, ProtectionZone zone,
        Collection<String> fileList) throws IOException {

    List<String> nonEmptyFileList = fileList.stream().filter(Assets::isNonEmpty).collect(Collectors.toList());
    logger.debug("-- assets() - non-empty file list size: {}", nonEmptyFileList.size());

    if (nonEmptyFileList.isEmpty()) {
        return new ArrayList<>();
    }//from  ww  w.j  a v a  2s  . c o m

    List<CloudKit.RecordRetrieveResponse> responses = kitty.recordRetrieveRequest(httpClient, "_defaultZone",
            nonEmptyFileList);

    return responses.stream().filter(CloudKit.RecordRetrieveResponse::hasRecord)
            .map(CloudKit.RecordRetrieveResponse::getRecord).map(r -> asset(r, zone))
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}

From source file:io.knotx.junit.util.KnotContextFactory.java

public static KnotContext create(List<Pair<List<String>, String>> fragments) {
    return new KnotContext()
            .setFragments(// www  .ja v a2s  .c  o m
                    fragments != null
                            ? fragments.stream().map(data -> Fragment.snippet(data.getKey(), data.getValue()))
                                    .collect(Collectors.toList())
                            : null)
            .setClientRequest(new ClientRequest())
            .setClientResponse(new ClientResponse().setHeaders(MultiMap.caseInsensitiveMultiMap()));
}

From source file:Main.java

public static <T> CompletableFuture<List<T>> allOfFutures(
        List<? extends CompletableFuture<? extends T>> futures) {
    List<T> result = new ArrayList<>(futures.size());
    CompletableFuture<List<T>> cf = new CompletableFuture<>();
    CompletableFuture/*  w w w  . j av  a2s .c om*/
            .allOf(futures.stream().map(s -> s.thenAccept(result::add)).toArray(CompletableFuture<?>[]::new))
            .exceptionally(ex -> {
                cf.completeExceptionally(ex);
                return null;
            }).thenAccept(v -> cf.complete(result));
    return cf;
}