demos.AsynchronousRead.java Source code

Java tutorial

Introduction

Here is the source code for demos.AsynchronousRead.java

Source

/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package demos;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.StreamSupport;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Session;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Demonstrates reading data asynchronously. You must first run
 * <code>src/main/resources/demo.cql</code> prior to running this example. One of the
 * examples for inserting data should be run before this.
 *
 * @author jsanda
 */
public class AsynchronousRead implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AsynchronousRead.class);

    private final int NUM_METRICS = 25;

    @Override
    public void run() {
        try {
            logger.info("Preparing to read data points");

            Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
            Session session = cluster.connect("demo");
            PreparedStatement query = session.prepare(
                    "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?");
            DateTime end = DateTime.now();
            DateTime start = end.minusYears(1);
            final CountDownLatch latch = new CountDownLatch(NUM_METRICS);
            final Set<DataPoint> dataPoints = new ConcurrentSkipListSet<>(
                    comparing(DataPoint::getTimestamp).thenComparing(DataPoint::getValue));

            Stopwatch stopwatch = new Stopwatch().start();
            for (int i = 0; i < NUM_METRICS; ++i) {
                ResultSetFuture queryFuture = session
                        .executeAsync(query.bind("metric-" + i, start.toDate(), end.toDate()));
                ListenableFuture<List<DataPoint>> dataFuture = Futures.transform(queryFuture,
                        (ResultSet resultSet) -> StreamSupport.stream(resultSet.spliterator(), false)
                                .map(row -> new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2)))
                                .collect(toList()));
                Futures.addCallback(dataFuture, new FutureCallback<List<DataPoint>>() {
                    @Override
                    public void onSuccess(List<DataPoint> results) {
                        dataPoints.addAll(results);
                        latch.countDown();
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        logger.warn("There was an error reading data", t);
                        latch.countDown();
                    }
                });
            }
            latch.await();
            stopwatch.stop();

            logger.info("Retrieved {} data points in {} ms", dataPoints.size(),
                    stopwatch.elapsed(TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            logger.info("There was an interrupt while waiting for inserts to complete");
        }
    }
}