Example usage for java.util List forEach

List of usage examples for java.util List forEach

Introduction

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

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:squash.tools.FakeBookingCreator.java

public static void main(String[] args) throws IOException {
    int numberOfDays = 21;
    int numberOfCourts = 5;
    int maxCourtSpan = 5;
    int numberOfSlots = 16;
    int maxSlotSpan = 3;
    int minSurnameLength = 2;
    int maxSurnameLength = 20;
    int minBookingsPerDay = 0;
    int maxBookingsPerDay = 8;
    LocalDate startDate = LocalDate.of(2016, 7, 5);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<Booking> bookings = new ArrayList<>();
    for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) {
        int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1);
        List<Booking> daysBookings = new ArrayList<>();
        for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) {
            String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));
            String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));

            Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>();
            daysBookings.forEach((booking) -> {
                addBookingToSet(booking, bookedCourts);
            });/*  w  w  w. ja va 2 s . co m*/

            Booking booking;
            Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>();
            do {
                // Loop until we create a booking of free courts
                int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1);
                int courtSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxCourtSpan + 1, numberOfCourts - court + 2));
                int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1);
                int slotSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2));
                booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2);
                booking.setDate(date.format(formatter));
                courtsToBook.clear();
                addBookingToSet(booking, courtsToBook);
            } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0));

            daysBookings.add(booking);
        }
        bookings.addAll(daysBookings);
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingNode.put("date", booking.getDate());
        bookingsNode.add(bookingNode);
    }
    // Add empty booking rules array - just so restore works
    rootNode.putArray("bookingRules");
    rootNode.put("clearBeforeRestore", true);

    try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"),
            JsonEncoding.UTF8)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapper.writeTree(generator, rootNode);
    }
}

From source file:com.example.geomesa.kafka.KafkaLoadTester.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);
    String visibility = getVisibility(cmd);
    Integer delay = getDelay(cmd);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {/*from  www.  j  a  va 2 s .c  o  m*/
        System.out.println("visibility: '" + visibility + "'");
    }

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    System.out.println("KDS config: " + dsConf);
    dsConf.put("kafka.consumer.count", "0");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("kafka.consumer.count", "1");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    try {
        // create the schema which creates a topic in Kafka
        // (only needs to be done once)
        final String sftName = "KafkaStressTest";
        final String sftSchema = "name:String,age:Int,step:Double,lat:Double,dtg:Date,*geom:Point:srid=4326";
        SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
        producerDS.createSchema(sft);

        System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
        System.in.read();

        // the live consumer must be created before the producer writes features
        // in order to read streaming data.
        // i.e. the live consumer will only read data written after its instantiation
        SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);
        SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);

        // creates and adds SimpleFeatures to the producer every 1/5th of a second
        System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");

        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);

        Integer numFeats = getLoad(cmd);

        System.out.println("Building a list of " + numFeats + " SimpleFeatures.");
        List<SimpleFeature> features = IntStream.range(1, numFeats)
                .mapToObj(i -> createFeature(builder, i, visibility)).collect(Collectors.toList());

        // set variables to estimate feature production rate
        Long startTime = null;
        Long featuresSinceStartTime = 0L;
        int cycle = 0;
        int cyclesToSkip = 50000 / numFeats; // collect enough features
                                             // to get an accurate rate estimate

        while (true) {
            // write features
            features.forEach(feat -> {
                try {
                    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
                    featureCollection.add(feat);
                    producerFS.addFeatures(featureCollection);
                } catch (Exception e) {
                    System.out.println("Caught an exception while writing features.");
                    e.printStackTrace();
                }
                updateFeature(feat);
            });

            // count features written
            Integer consumerSize = consumerFS.getFeatures().size();
            cycle++;
            featuresSinceStartTime += consumerSize;
            System.out.println("At " + new Date() + " wrote " + consumerSize + " features");

            // if we've collected enough features, calculate the rate
            if (cycle >= cyclesToSkip || startTime == null) {
                Long endTime = System.currentTimeMillis();
                if (startTime != null) {
                    Long diffTime = endTime - startTime;
                    Double rate = (featuresSinceStartTime.doubleValue() * 1000.0) / diffTime.doubleValue();
                    System.out.printf("%.1f feats/sec (%d/%d)\n", rate, featuresSinceStartTime, diffTime);
                }
                cycle = 0;
                startTime = endTime;
                featuresSinceStartTime = 0L;
            }

            // sleep before next write
            if (delay != null) {
                System.out.printf("Sleeping for %d ms\n", delay);
                Thread.sleep(delay);
            }
        }

    } finally {
        producerDS.dispose();
        consumerDS.dispose();
    }
}

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

public static void main(String[] args) throws IOException {

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);

    DSLContext dsl = ctx.getBean(DSLContext.class);
    ApplicationService applicationDao = ctx.getBean(ApplicationService.class);
    OrganisationalUnitService ouDao = ctx.getBean(OrganisationalUnitService.class);

    List<String> animals = IOUtilities
            .readLines(AppGenerator.class.getClassLoader().getResourceAsStream("animals.txt"));
    OrganisationalUnit[] organisationalUnits = ouDao.findAll().toArray(new OrganisationalUnit[0]);

    List<AppRegistrationRequest> registrationRequests = new ArrayList<>();

    for (int i = 0; i < 5000; i++) {
        String animal = randomPick(animals.toArray(new String[0])) + " - " + i;

        OrganisationalUnit organisationalUnit = randomPick(organisationalUnits);

        LifecyclePhase phase = rnd.nextInt(10) > 7 ? randomPick(LifecyclePhase.values())
                : LifecyclePhase.PRODUCTION;

        AppRegistrationRequest app = ImmutableAppRegistrationRequest.builder().name(animal)
                .assetCode("wltz-0" + i).description("All about " + animal)
                .kind(randomPick(ApplicationKind.values())).lifecyclePhase(phase)
                .overallRating(randomPick(RagRating.R, RagRating.A, RagRating.A, RagRating.G, RagRating.G))
                .organisationalUnitId(organisationalUnit.id().get()).build();

        registrationRequests.add(app);//w  w w. ja  va  2s . c o m
    }

    dsl.deleteFrom(AUTHORITATIVE_SOURCE).execute();
    dsl.deleteFrom(APPLICATION).execute();

    registrationRequests.forEach(applicationDao::registerApp);

}

From source file:act.installer.pubchem.PubchemSynonymFinder.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*  ww  w.ja  v  a  2 s. c o  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.isDirectory()) {
        System.err.format("Index directory does not exist or is not a directory at '%s'",
                rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<String> compoundIds = null;
    if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
        compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
    } else if (cl.hasOption(OPTION_IDS_FILE)) {
        File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
        if (!idsFile.exists()) {
            System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }

        compoundIds = getCIDsFromFile(idsFile);

        if (compoundIds.size() == 0) {
            System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting",
                    idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
    } else {
        System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
                OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Run a quick check to warn users of malformed ids.
    compoundIds.forEach(x -> {
        if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
            LOGGER.warn("Specified compound id does not match expected format: %s", x);
        }
    });

    LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
    Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
    try {
        dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
        RocksDB db = dbAndHandles.getLeft();
        ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight()
                .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);

        for (String cid : compoundIds) {
            PubchemSynonyms synonyms = null;
            byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
            if (val != null) {
                ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
                // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
                synonyms = (PubchemSynonyms) oi.readObject();
            } else {
                LOGGER.warn("No synonyms available for compound id '%s'", cid);
            }
            results.put(cid, synonyms);
        }
    } finally {
        if (dbAndHandles != null) {
            dbAndHandles.getLeft().close();
        }
    }

    try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT)
            ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT))
            : System.out) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
        new OutputStreamWriter(outputStream).append('\n');
    }
    LOGGER.info("Done searching for Pubchem synonyms");
}

From source file:com.xylocore.cassandra.query.TableScanQuery.java

public static void main(String[] args) {
    Cluster myCluster = null;// ww w  . jav  a2s  . c om

    try {
        myCluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

        Session mySession = myCluster.connect("cirdan");

        List<Entity> myAllEntities = new ArrayList<Entity>();

        BiConsumer<Row, Entity> myEntityExtractor = (myRow, myEntity) -> {
            myEntity.setA(myRow.getInt("a"));
            myEntity.setB(myRow.getInt("b"));
            myEntity.setC(myRow.getInt("c"));
            myEntity.setD(myRow.getInt("d"));
        };

        Consumer<List<Entity>> myEntityProcessor = (myEntities) -> {
            myEntities.forEach(e -> {
                logger.debug("entity: {}", e);
            });

            myAllEntities.addAll(myEntities);
        };

        TableScanQueryExecutionContext<Entity> myExecutionContext = TableScanQueryExecutionContextBuilder
                .builder(Entity.class).entityCreator(() -> {
                    return new Entity();
                }).reuseEntity(false).entityExtractor(myEntityExtractor).entityProcessor(myEntityProcessor)
                .build();

        TableScanQuery<Entity> myQuery = TableScanQueryBuilder.<Entity>builder().session(mySession)
                .keyspace("cirdan").tableName("b").columns("a", "b", "c", "d")
                //                                         .column   ( "a"       )
                //                                         .column   ( "b"       )
                //                                         .column   ( "c"       )
                //                                         .column   ( "d"       )
                .build();

        CompletableFuture<Void> myFuture = myQuery.execute(myExecutionContext);
        myFuture.get();

        myAllEntities.forEach((e) -> System.err.println(e.toString()));
    } catch (Exception myException) {
        myException.printStackTrace();
    } finally {
        if (myCluster != null) {
            myCluster.close();
        }
    }
}

From source file:Main.java

public static <T> void diff(Collection<T> from, Collection<T> to, Consumer<? super T> foreachAdd,
        Consumer<? super T> foreachRemove) {
    List<T> added = new ArrayList<>(to);
    added.removeAll(from);/*from  w  w w  .  j a  va2  s .  c  om*/
    added.forEach(foreachAdd);

    List<T> removed = new ArrayList<>(from);
    removed.removeAll(to);
    removed.forEach(foreachRemove);
}

From source file:edu.usu.sdl.openstorefront.core.view.AlertView.java

public static List<AlertView> toView(List<Alert> alerts) {
    List<AlertView> views = new ArrayList<>();
    alerts.forEach(alert -> {
        views.add(toView(alert));//www  .  j  a v a 2  s.  co m
    });
    return views;
}

From source file:com.thoughtworks.go.api.representers.ConfigurationPropertyRepresenter.java

public static void toJSON(OutputListWriter propertiesWriter,
        List<ConfigurationProperty> configurationProperties) {
    configurationProperties.forEach(configurationProperty -> {
        if (configurationProperty == null) {
            return;
        }/*from w  ww .j a v a  2s  .  com*/
        propertiesWriter.addChild(propertyWriter -> toJSON(propertyWriter, configurationProperty));
    });
}

From source file:edu.usu.sdl.openstorefront.core.view.OrganizationView.java

public static List<OrganizationView> toView(List<Organization> organizations) {
    List<OrganizationView> views = new ArrayList<>();
    organizations.forEach(organization -> {
        views.add(toView(organization));
    });/*from   w  w w. j a  va 2 s  .  c o m*/
    return views;
}

From source file:edu.usu.sdl.openstorefront.core.view.ReportView.java

public static List<ReportView> toReportView(List<Report> reports) {
    List<ReportView> views = new ArrayList<>();
    reports.forEach(report -> {
        views.add(toReportView(report));
    });//  w  ww. j a v  a2  s  .com
    return views;
}