demos.SynchronousRead.java Source code

Java tutorial

Introduction

Here is the source code for demos.SynchronousRead.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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.google.common.base.Stopwatch;

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

/**
 * Demonstrates reading data synchronously. 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 SynchronousRead implements Runnable {

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

    private final int NUM_METRICS = 25;

    public void run() {
        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);
        List<DataPoint> dataPoints = new ArrayList<>();

        Stopwatch stopwatch = new Stopwatch().start();
        for (int i = 0; i < NUM_METRICS; ++i) {
            ResultSet resultSet = session.execute(query.bind("metric-" + i, start.toDate(), end.toDate()));
            resultSet.forEach(
                    row -> dataPoints.add(new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2))));
        }
        stopwatch.stop();

        logger.info("Retrieved {} data points in {} ms", dataPoints.size(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

}