de.softwareforge.streamery.StreameryMain.java Source code

Java tutorial

Introduction

Here is the source code for de.softwareforge.streamery.StreameryMain.java

Source

/*
 * 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 de.softwareforge.streamery;

import static java.lang.String.format;

import org.h2.jdbcx.JdbcDataSource;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;

import rx.Observable;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import de.softwareforge.streamery.Data.DataMapper;

import java.util.UUID;

public class StreameryMain {
    public static final void main(String... args) throws Exception {
        final ObjectMapper mapper = new ObjectMapper();
        final DBI h2Dbi = getH2Dbi();

        setupData(h2Dbi);

        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        Query<Data> q = h2Dbi.open().createQuery("SELECT * FROM data").setFetchSize(200).map(DataMapper.INSTANCE);

        final Observable<Data> observable = JdbiObservable.from(q);

        observable.subscribe(new JsonStreamer<>(mapper.getFactory()));
    }

    public static final DBI getH2Dbi() {
        final JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1", UUID.randomUUID()));
        return new DBI(ds);
    }

    public interface Sql {
        @SqlUpdate("CREATE TABLE data ( id INTEGER, value VARCHAR )")
        void createTable();

        @SqlUpdate("INSERT INTO data (id, value) VALUES (:id, :value)")
        void insertTable(@Bind("id") int id, @Bind("value") String value);
    }

    public static void setupData(final DBI dbi) {
        final Sql sql = dbi.onDemand(Sql.class);

        sql.createTable();

        for (int i = 0; i < 1000; i++) {
            sql.insertTable(i, UUID.randomUUID().toString());
        }
    }
}