How to create tumbling windows

Problem:

you have time-series events in a Kafka topic, and you want to group them into fixed-size, non-overlapping, contiguous time intervals.

Edit this page

Example use case:

Suppose you have a topic with events that represent ratings of movies. In this tutorial, we'll write a program that maintains tumbling windows counting the total number of ratings that each movie has received.

Code example:

Try it

1
Initialize the project

To get started, make a new directory anywhere you’d like for this project:

mkdir tumbling-windows && cd tumbling-windows

2
Get Confluent Platform

Next, create the following docker-compose.yml file to obtain Confluent Platform:

---
version: '2'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.3.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-enterprise-kafka:5.3.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: broker:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'

  schema-registry:
    image: confluentinc/cp-schema-registry:5.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - zookeeper
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: 'zookeeper:2181'
      SCHEMA_REGISTRY_LOG4J_ROOT_LOGLEVEL: WARN

And launch it by running:

docker-compose up

3
Configure the project

Create the following Gradle build file, named build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.commercehub.gradle.plugin:gradle-avro-plugin:0.15.1'
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.2'
    }
}

plugins {
    id 'java'
    id 'com.google.cloud.tools.jib' version '1.1.1'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '0.0.1'

repositories {
    mavenCentral()
    jcenter()

    maven {
        url 'http://packages.confluent.io/maven'
    }
}

apply plugin: 'com.commercehub.gradle.plugin.avro'
apply plugin: 'com.github.johnrengelman.shadow'

dependencies {
    compile 'org.apache.avro:avro:1.8.2'
    implementation 'org.slf4j:slf4j-simple:1.7.26'
    implementation 'org.apache.kafka:kafka-streams:2.2.0'
    implementation 'io.confluent:kafka-streams-avro-serde:5.2.0'
    testCompile 'org.apache.kafka:kafka-streams-test-utils:2.2.0'
    testCompile 'junit:junit:4.12'
}

test {
    testLogging {
        outputs.upToDateWhen { false }
        showStandardStreams = true
        exceptionFormat = 'full'
    }
}

task run(type: JavaExec) {
   main = 'io.confluent.developer.TumblingWindow'
   classpath = sourceSets.main.runtimeClasspath
   args = ['configuration/dev.properties']
}

jar {
  manifest {
    attributes(
      'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
      'Main-Class': 'io.confluent.developer.TumblingWindow'
    )
  }
}

shadowJar {
    archiveName = "kstreams-tumbling-windows-standalone-${version}.${extension}"
}

And be sure to run the following command to obtain the Gradle wrapper:

gradle wrapper

Next, create a directory for configuration data:

mkdir configuration

Then create a development file at configuration/dev.properties:

application.id=tumbling-window-app
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081

rating.topic.name=ratings
rating.topic.partitions=1
rating.topic.replication.factor=1

rating.count.topic.name=rating-counts
rating.count.topic.partitions=1
rating.count.topic.replication.factor=1

4
Create a schema for the events

This tutorial uses a single input stream called ratings. It contains movie ratings for a few different movies submitted at times spanning a few weeks. We’ll need to create a schema for these events.

Create a directory to hold the schema file:

mkdir -p src/main/avro

Next, create an Avro schema file at src/main/avro/rating.avsc for the stream of ratings:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Rating",
  "fields": [
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"},
    {"name": "rating", "type": "double"},
    {"name": "timestamp", "type": "string"}
  ]
}

Because we will use this Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

5
Create the Kafka Streams topology

Create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

Then create the following file at src/main/java/io/confluent/developer/TumblingWindow.java.

package io.confluent.developer;

import io.confluent.developer.avro.Rating;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CountDownLatch;

public class TumblingWindow {

    public Properties buildStreamsProperties(Properties envProps) {
        Properties props = new Properties();

        props.put(StreamsConfig.APPLICATION_ID_CONFIG, envProps.getProperty("application.id"));
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, envProps.getProperty("bootstrap.servers"));
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
        props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, RatingTimestampExtractor.class.getName());
        props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
        try {
            props.put(StreamsConfig.STATE_DIR_CONFIG,
                      Files.createTempDirectory("tumbling-windows").toAbsolutePath().toString());
        }
        catch(IOException e) {
            // If we can't have our own temporary directory, we can leave it with the default. We create a custom
            // one because running the app outside of Docker multiple times in quick succession will find the
            // previous state still hanging around in /tmp somewhere, which is not the expected result.
        }
        return props;
    }

    public Topology buildTopology(Properties envProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String ratingTopic = envProps.getProperty("rating.topic.name");
        final String ratingCountTopic = envProps.getProperty("rating.count.topic.name");

        builder.<String, Rating>stream(ratingTopic)
                .map((key, rating) -> new KeyValue<>(rating.getTitle().toString(), rating))
                .groupByKey()
                .windowedBy(TimeWindows.of(Duration.ofMinutes(10)))
                .count()
                .toStream()
                .map((Windowed<String> key, Long count) -> new KeyValue(key.key(), count.toString()))
                .to(ratingCountTopic, Produced.with(Serdes.String(), Serdes.String()));

        return builder.build();
    }

    private String windowedKeyToString(Windowed<String> key) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZZZZ");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return String.format("[%s@%s/%s]",
                             key.key(),
                             sdf.format(key.window().startTime().getEpochSecond()),
                             sdf.format(key.window().endTime().getEpochSecond()));
    }


    private SpecificAvroSerde<Rating> ratedMovieAvroSerde(Properties envProps) {
        SpecificAvroSerde<Rating> movieAvroSerde = new SpecificAvroSerde<>();

        final HashMap<String, String> serdeConfig = new HashMap<>();
        serdeConfig.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                envProps.getProperty("schema.registry.url"));

        movieAvroSerde.configure(serdeConfig, false);
        return movieAvroSerde;
    }

    public void createTopics(Properties envProps) {
        Map<String, Object> config = new HashMap<>();
        config.put("bootstrap.servers", envProps.getProperty("bootstrap.servers"));
        AdminClient client = AdminClient.create(config);

        List<NewTopic> topics = new ArrayList<>();
        Map<String, String> topicConfigs = new HashMap<>();
        topicConfigs.put("retention.ms", Long.toString(Long.MAX_VALUE));

        NewTopic ratings = new NewTopic(envProps.getProperty("rating.topic.name"),
                                        Integer.parseInt(envProps.getProperty("rating.topic.partitions")),
                                        Short.parseShort(envProps.getProperty("rating.topic.replication.factor")));
        ratings.configs(topicConfigs);
        topics.add(ratings);

        NewTopic counts = new NewTopic(envProps.getProperty("rating.count.topic.name"),
                                       Integer.parseInt(envProps.getProperty("rating.count.topic.partitions")),
                                       Short.parseShort(envProps.getProperty("rating.count.topic.replication.factor")));
        counts.configs(topicConfigs);
        topics.add(counts);


        client.createTopics(topics);
        client.close();
    }

    public Properties loadEnvProperties(String fileName) throws IOException {
        Properties envProps = new Properties();
        FileInputStream input = new FileInputStream(fileName);
        envProps.load(input);
        input.close();

        return envProps;
    }

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

        if (args.length < 1) {
            throw new IllegalArgumentException("This program takes one argument: the path to an environment configuration file.");
        }

        TumblingWindow tw = new TumblingWindow();
        Properties envProps = tw.loadEnvProperties(args[0]);
        Properties streamProps = tw.buildStreamsProperties(envProps);
        Topology topology = tw.buildTopology(envProps);

        tw.createTopics(envProps);

        final KafkaStreams streams = new KafkaStreams(topology, streamProps);
        final CountDownLatch latch = new CountDownLatch(1);

        // Attach shutdown handler to catch Control-C.
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            @Override
            public void run() {
                streams.close();
                latch.countDown();
            }
        });

        try {
            streams.start();
            latch.await();
        } catch (Throwable e) {
            System.exit(1);
        }
        System.exit(0);
    }
}

Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

The first thing the method does is create an instance of StreamsBuilder, which is the helper object that lets us build our topology.

First, we call the stream() method to create a KStream<String, Rating> object. The problem is that we can’t make any assumptions about the key of this stream, so we have to repartition it explicitly. We use the map() method for that, creating a new KeyValue instance for each record, using the title as the new key.

Next we group the events by that new key by calling the groupByKey() method. We want to count the events that occur with each given key, so we must first define a tumbling window by calling windowedBy(TimeWindows.of(Duration.ofMinutes(10))). We then call count(), which directs the topology to count the grouped events that occur within each window. At this point in the toplogy, the result is a KTable<Windowed<String>, Long>. We use the map() method to turn it into two easy-to-read strings, then emit the result to the output topic with the to() method. You might not always make that last call to map(), but for our purposes here, it makes the output a lot easier to read.

6
Implement a TimestampExtractor class

The preceding topology relies on the messages in its input topic being processed according <em>event time</em>—the time at which the event actually occurred, rather than the time it happened to arrive on the topic. Event time is typically available in the message itself, as it is in this case in the form of the timestamp field. We can automatically extract this timestamp by creating the src/main/java/io/confluent/developer/RatingTimestampExtractor.java class, which is an implementation of the TimestampExtractor interface. The code is simple:

package io.confluent.developer;

import io.confluent.developer.avro.Rating;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class RatingTimestampExtractor implements TimestampExtractor {
    @Override
    public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

        String eventTime = ((Rating)record.value()).getTimestamp();

        try {
            return sdf.parse(eventTime).getTime();
        } catch(ParseException e) {
            return 0;
        }
    }
}

7
Some special configuration

There is always a little bit of boilerplate configuration in any Kafka Streams app, but three lines in this tutorial are worth comment. You don’t have to do anything on this step, so you can come back to it later if you’d like.

First, the TimestampExtractor we created in the previous step is installed into our stream processing topology through a configuration setting. This is the props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, RatingTimestampExtractor.class.getName()) line.

Second, we want to optimize our Streams app for latency at the expense of throughput. (The real thing we want here is to see results in the output terminal pane as quickly as possible, which is a less-fancy way of saying the same thing.) To make this happen, we have to disable the Streams output cache as follows: props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0).

Finally, we need to remeber that a Streams app caches its state locally on disk, in a directory pointed to by the state.dir configuration setting. If you run the application once, kill it, then run it again, it will likely find the state left on disk by the previous run. This is very much by design, but can be confusing when you’re experimenting with a small tutorial like this. To make sure state goes into a throwaway temporary directory, we set the state dir with props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("tumbling-windows").toAbsolutePath().toString()). Note that the call must be wrapped in an exception-handling block, and if we fail to create the temporary directory, we continue running with the default directory in place.

8
Compile and run the Kafka Streams program

In your terminal, run:

./gradlew shadowJar

Now that you have an uberjar for the Kafka Streams application, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.

java -jar build/libs/kstreams-tumbling-windows-standalone-0.0.1.jar configuration/dev.properties

9
Get ready to observe the counted ratings in the output topic

Before you start producing input data, it’s a good idea to set up the consumer on the output topic. This way, as soon as you produce movie ratings (and windowed and counted), you’ll see the results right away. Run this to get ready to consume the windowed counts:

docker exec -it broker /usr/bin/kafka-console-consumer --topic rating-counts --bootstrap-server broker:9092 --from-beginning --property print.key=true

You won’t see any results until the next step.

10
Produce some ratings to the input topic

When the console producer starts, it will log some text and hang, waiting for your input. You can copy and paste all of the test data at once to see the results. (Because event times are baked into each message, it doesn’t matter at what time the messages arrive in the input topic. In fact, if you want extra credit, you should be able to experiment with changing the order of the messages in this data, and still get the same output counts.)

Start the console producer with this command in a terminal window of its own:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic ratings --broker-list broker:9092 --property value.schema="$(< src/main/avro/rating.avsc)"

When the producer starts up, copy and paste these lines into the terminal:

{"title": "Die Hard", "release_year": 1998, "rating": 8.2, "timestamp": "2019-04-25T18:00:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 4.5, "timestamp": "2019-04-25T18:03:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 5.1, "timestamp": "2019-04-25T18:04:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 2.0, "timestamp": "2019-04-25T18:07:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 8.3, "timestamp": "2019-04-25T18:32:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 3.4, "timestamp": "2019-04-25T18:36:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 4.2, "timestamp": "2019-04-25T18:43:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 7.6, "timestamp": "2019-04-25T18:44:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 4.9, "timestamp": "2019-04-25T20:01:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 5.6, "timestamp": "2019-04-25T20:02:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 9.0, "timestamp": "2019-04-25T20:03:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 6.5, "timestamp": "2019-04-25T20:12:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 2.1, "timestamp": "2019-04-25T20:13:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 3.6, "timestamp": "2019-04-25T22:20:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 6.0, "timestamp": "2019-04-25T22:21:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 7.0, "timestamp": "2019-04-25T22:22:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 4.6, "timestamp": "2019-04-25T22:23:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 7.1, "timestamp": "2019-04-25T22:24:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 9.9, "timestamp": "2019-04-25T21:15:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 8.6, "timestamp": "2019-04-25T21:16:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 4.2, "timestamp": "2019-04-25T21:17:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 7.0, "timestamp": "2019-04-25T21:18:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 9.5, "timestamp": "2019-04-25T21:19:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 3.2, "timestamp": "2019-04-25T21:20:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 3.5, "timestamp": "2019-04-25T13:00:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 4.0, "timestamp": "2019-04-25T13:07:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 5.1, "timestamp": "2019-04-25T13:30:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 2.0, "timestamp": "2019-04-25T13:34:00-0700"}

Looking back up in the consumer terminal, these are the results you should see there if you paste in all the ratings as directed above:

Die Hard	1
Die Hard	2
Die Hard	3
Die Hard	4
Die Hard	1
Die Hard	2
Die Hard	1
Die Hard	2
Tree of Life	1
Tree of Life	2
Tree of Life	3
Tree of Life	1
Tree of Life	2
A Walk in the Clouds	1
A Walk in the Clouds	2
A Walk in the Clouds	3
A Walk in the Clouds	4
A Walk in the Clouds	5
The Big Lebowski	1
The Big Lebowski	2
The Big Lebowski	3
The Big Lebowski	4
The Big Lebowski	5
The Big Lebowski	1
Super Mario Bros.	1
Super Mario Bros.	2
Super Mario Bros.	1
Super Mario Bros.	2

Note that each event is counted individually. Since output caching is disabled, we see Die Hard get counted once, then counted again, then counted again, until the Die Hard ratings stop arriving. At that point, we have the final count for that movie. The same happens with all the rest. If we were to interrogate the contents of the resulting KTable after all the input messages have arrived, we would see only the final counts in the table—not the history of the counting as we see in the output topic. This is a good illustration of what we sometimes refer to as the stream-table duality.

That is a topic for further study later on, but for now, you deserve some congratulations! You have now computed an aggregation over a tumbling window. Well done.

Test it

1
Create a test configuration file

First, create a test file at configuration/test.properties:

application.id=tumbling-window-app
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081

rating.topic.name=ratings
rating.topic.partitions=1
rating.topic.replication.factor=1

rating.count.topic.name=rating-counts
rating.count.topic.partitions=1
rating.count.topic.replication.factor=1

2
Test the RatingTimestampExtractor class

Create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer

Create the following file at src/test/java/io/confluent/developer/RatingTimestampExtractorTest.java. This tests the helper class that extracts event-time timestamps from incoming messages. The class has a depenency on the TimestampExtractor interface, but otherwise does not depend on anything external to our domain; it just needs a Rating object, and returns a timestamp. As such, it’s very testable code:

package io.confluent.developer;

import io.confluent.developer.avro.Rating;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.MockProcessorContext;
import org.junit.Test;
import static org.junit.Assert.*;

import java.util.List;

public class RatingTimestampExtractorTest {

    @Test
    public void testTimestampExtraction() {
        RatingTimestampExtractor rte = new RatingTimestampExtractor();

        Rating treeOfLife = Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(9.9).setTimestamp("2019-04-25T18:00:00-0700").build();
        ConsumerRecord record = new ConsumerRecord("ratings", 0, 1, "Tree of Life", treeOfLife);

        long timestamp = rte.extract(record, 0);

        assertEquals(1556240400000L, timestamp);
    }

}

3
Test the streams topology

Now create the following file at src/test/java/io/confluent/developer/TumblingWindowTest.java. Testing a Kafka streams application requires a bit of test harness code, but the org.apache.kafka.streams.TopologyTestDriver class makes this easy.

There is only one method in TumblingWindowTest annotated with @Test, and that is testWindows(). This method actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

package io.confluent.developer;

import io.confluent.developer.avro.Rating;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import static org.junit.Assert.*;

import org.apache.kafka.streams.test.ConsumerRecordFactory;
import org.junit.Test;

import java.io.IOException;
import java.util.*;

public class TumblingWindowTest {
    private final static String TEST_CONFIG_FILE = "configuration/test.properties";


    private SpecificAvroSerializer<Rating> makeRatingSerializer(Properties envProps) {
        SpecificAvroSerializer<Rating> serializer = new SpecificAvroSerializer<>();

        Map<String, String> config = new HashMap<>();
        config.put("schema.registry.url", envProps.getProperty("schema.registry.url"));
        serializer.configure(config, false);

        return serializer;
    }

    private List<RatingCount> readOutputTopic(TopologyTestDriver testDriver,
                                              String outputTopic,
                                              Deserializer<String> keyDeserializer,
                                              Deserializer<String> valueDeserializer) {
        List<RatingCount> results = new ArrayList<>();

        while(true) {
            ProducerRecord<String, String> record = testDriver.readOutput(outputTopic, keyDeserializer, valueDeserializer);

            if (record != null) {
                results.add(new RatingCount(record.key().toString(), record.value()));
            } else {
                break;
            }
        }

        return results;
    }

    @Test
    public void testWindows() throws IOException {
        TumblingWindow tw = new TumblingWindow();
        Properties envProps = tw.loadEnvProperties(TEST_CONFIG_FILE);
        Properties streamProps = tw.buildStreamsProperties(envProps);

        String inputTopic = envProps.getProperty("rating.topic.name");
        String outputTopic = envProps.getProperty("rating.count.topic.name");

        Topology topology = tw.buildTopology(envProps);
        TopologyTestDriver testDriver = new TopologyTestDriver(topology, streamProps);

        Serializer<String> stringSerializer = Serdes.String().serializer();
        SpecificAvroSerializer<Rating> ratingSerializer = makeRatingSerializer(envProps);
        Deserializer<String> stringDeserializer = Serdes.String().deserializer();

        ConsumerRecordFactory<String, Rating> ratingFactory = new ConsumerRecordFactory<>(stringSerializer, ratingSerializer);

        List<Rating> ratings = new ArrayList<>();
        ratings.add(Rating.newBuilder().setTitle("Die Hard").setReleaseYear(1988).setRating(8.2).setTimestamp("2019-04-25T18:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Die Hard").setReleaseYear(1988).setRating(7.6).setTimestamp("2019-04-25T18:05:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(4.9).setTimestamp("2019-04-25T21:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(9.9).setTimestamp("2019-04-25T21:11:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(3.6).setTimestamp("2019-04-25T13:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(7.1).setTimestamp("2019-04-25T13:01:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("The Big Lebowski").setReleaseYear(1998).setRating(8.6).setTimestamp("2019-04-25T19:30:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("The Big Lebowski").setReleaseYear(1998).setRating(7.0).setTimestamp("2019-04-25T19:35:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Super Mario Bros.").setReleaseYear(1993).setRating(3.5).setTimestamp("2019-04-25T11:15:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Super Mario Bros.").setReleaseYear(1993).setRating(2.0).setTimestamp("2019-04-25T11:40:00-0000").build());

        List<RatingCount> ratingCounts = new ArrayList<>();
        ratingCounts.add(new RatingCount("Die Hard", "1"));
        ratingCounts.add(new RatingCount("Die Hard", "2"));
        ratingCounts.add(new RatingCount("Tree of Life", "1"));
        ratingCounts.add(new RatingCount("Tree of Life", "1"));
        ratingCounts.add(new RatingCount("A Walk in the Clouds", "1"));
        ratingCounts.add(new RatingCount("A Walk in the Clouds", "2"));
        ratingCounts.add(new RatingCount("The Big Lebowski", "1"));
        ratingCounts.add(new RatingCount("The Big Lebowski", "2"));
        ratingCounts.add(new RatingCount("Super Mario Bros.", "1"));
        ratingCounts.add(new RatingCount("Super Mario Bros.", "1"));

        for(Rating rating : ratings) {
            testDriver.pipeInput(ratingFactory.create(inputTopic, rating.getTitle(), rating));
        }

        List<RatingCount> actualOutput = readOutputTopic(testDriver,
                                                         outputTopic,
                                                         stringDeserializer,
                                                         stringDeserializer);

        assertEquals(ratingCounts.size(), actualOutput.size());
        for(int n = 0; n < ratingCounts.size(); n++) {
            assertEquals(ratingCounts.get(n).toString(), actualOutput.get(n).toString());
        }
    }
}

class RatingCount {
    private String key;
    private String value;

    public RatingCount(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    public String toString() {
        return key + "=" + value;
    }
}

4
Invoke the tests

Now run the test, which is as simple as:

./gradlew test

Take it to production

1
Create a production configuration file

First, create a new configuration file at configuration/prod.properties with the following content. Be sure to fill in the addresses of your production hosts and change any other parameters that make sense for your setup.

application.id=tumbling-window-app
bootstrap.servers=<< FILL ME IN >>:29092
schema.registry.url=http://<< FILL ME IN >>:8081

rating.topic.name=ratings
rating.topic.partitions=<< FILL ME IN >>
rating.topic.replication.factor=<< FILL ME IN >>

rating.count.topic.name=rating-counts
rating.count.topic.partitions=<< FILL ME IN >>
rating.count.topic.replication.factor=<< FILL ME IN >>

2
Build a Docker image

In your terminal, execute the following to invoke the Jib plugin to build an image:

./gradlew jibDockerBuild --image=io.confluent.developer/kstreams-tumbling-windows:0.0.1

3
Launch the container

Finally, launch the container using your preferred container orchestration service. If you want to run it locally, you can execute the following:

docker run -v $PWD/configuration/prod.properties:/config.properties io.confluent.developer/kstreams-tumbling-windows:0.0.1 config.properties