props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class.getName());
If you have time series events in a Kafka topic, how can you group them into variable-size, non-overlapping time intervals based on a configurable inactivity period?
To use SessionWindows
use the SessionWindows.with
method inside a windowedBy
call.
builder.stream(<INPUT TOPIC>, Consumed.with(<KEY SERDE>, <VALUE SERDE>))
.groupByKey()
.windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30)))
.<Aggregation Operation>....
The SessionsWindows.with
call determines the length inactivity before you consider the session closed. The grace
method determines is how much time elapses after the window closes before out-of-order are rejected.
Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.
To get started, make a new directory anywhere you’d like for this project:
mkdir session-windows && cd session-windows
Next, create a directory for configuration data:
mkdir configuration
This tutorial requires access to an Apache Kafka cluster, and the quickest way to get started free is on Confluent Cloud, which provides Kafka as a fully managed service.
After you log in to Confluent Cloud, click Environments
in the lefthand navigation, click on Add cloud environment
, and name the environment learn-kafka
. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.
From the Billing & payment
section in the menu, apply the promo code CC100KTS
to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1
. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.
Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.
From the Confluent Cloud Console, navigate to your Kafka cluster and then select Clients
in the lefthand navigation. From the Clients
view, create a new client and click Java
to get the connection information customized to your cluster.
Create new credentials for your Kafka cluster and Schema Registry, writing in appropriate descriptions so that the keys are easy to find and delete later. The Confluent Cloud Console will show a configuration similar to below with your new credentials automatically populated (make sure Show API keys
is checked).
Copy and paste it into a configuration/ccloud.properties
file on your machine.
# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips
# Best practice for Kafka producer to prevent data loss
acks=all
# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the Confluent Cloud Console so that it includes your Confluent Cloud information and credentials. |
This tutorial has some steps for Kafka topic management and producing and consuming events, for which you can use the Confluent Cloud Console or the Confluent CLI. Follow the instructions here to install the Confluent CLI, and then follow these steps connect the CLI to your Confluent Cloud cluster.
Create the following Gradle build file, named build.gradle
for the project:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
}
}
plugins {
id "java"
id "idea"
id "eclipse"
id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"
repositories {
mavenCentral()
maven {
url "https://packages.confluent.io/maven"
}
}
apply plugin: "com.github.johnrengelman.shadow"
dependencies {
implementation "org.apache.avro:avro:1.11.1"
implementation "org.slf4j:slf4j-simple:2.0.7"
implementation 'org.apache.kafka:kafka-streams:3.4.0'
implementation ('org.apache.kafka:kafka-clients') {
version {
strictly '3.4.0'
}
}
implementation "io.confluent:kafka-streams-avro-serde:7.3.0"
implementation "org.apache.kafka:kafka-clients:3.1.0"
testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
testImplementation "junit:junit:4.13.2"
testImplementation 'org.hamcrest:hamcrest:2.2'
}
test {
testLogging {
outputs.upToDateWhen { false }
showStandardStreams = true
exceptionFormat = "full"
}
}
jar {
manifest {
attributes(
"Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
"Main-Class": "io.confluent.developer.SessionWindow"
)
}
}
shadowJar {
archiveBaseName = "session-windows-standalone"
archiveClassifier = ''
}
And be sure to run the following command to obtain the Gradle wrapper:
gradle wrapper
Then create a development configuration file at configuration/dev.properties
:
application.id=session-windows
replication.factor=3
input.topic.name=page-views
input.topic.partitions=6
input.topic.replication.factor=3
output.topic.name=output-topic
output.topic.partitions=6
output.topic.replication.factor=3
Using the command below, append the contents of configuration/ccloud.properties
(with your Confluent Cloud configuration) to configuration/dev.properties
(with the application properties).
cat configuration/ccloud.properties >> configuration/dev.properties
Create a directory for the schemas that represent the events in the stream:
mkdir -p src/main/avro
Then create the following Avro schema file at src/main/avro/clicks.avsc
for our Clicks
object:
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "Clicks",
"fields": [
{ "name": "ip", "type": "string" },
{ "name": "timestamp", "type": "long" } ,
{ "name": "url", "type": "string" }
]
}
Because we will use an 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
First, create a directory for the Java files in this project:
mkdir -p src/main/java/io/confluent/developer
Before you create the Kafka Streams application you’ll need to create an instance of a TimestampExtractor. In Kafka Streams, timestamps drive the progress of records in the application. By default, Kafka Streams uses the timestamps contained in the ConsumerRecord. But you can configure your application to use timestamps embedded in the record payload itself. You do this by creating an class implementing the TimestampExtractor
interface and provide the class name when configuring your Kafka Streams application like so:
props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class.getName());
We’re going to create a custom TimestampExtractor
so the Kafka Streams application uses the timestamps embedded in our generated click events.
You aren’t required to use a custom TimestampExtractor in all cases. We’re using one here as it helps drive home the point of how sessions work and we can use synthetic timestamps to ensure we get distinct sessions.
|
Create the following file at src/main/java/io/confluent/developer/ClickEventTimestampExtractor.java
package io.confluent.developer;
import io.confluent.developer.avro.Clicks;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;
public class ClickEventTimestampExtractor implements TimestampExtractor {
@Override
public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
return ((Clicks)record.value()).getTimestamp();
}
}
You’ll take care of the configuration when you create the Kafka Streams topology in the next step.
In this tutorial you’ll learn about using SessionWindows with Kafka Streams. Session windows are driven by user behavior, as opposed to time.
builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
.groupByKey() (1)
.windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30))) (2)
.count() (3)
.toStream()
.map((windowedKey, count) -> { (4)
String start = timeFormatter.format(windowedKey.window().startTime());
String end = timeFormatter.format(windowedKey.window().endTime());
String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
return KeyValue.pair(windowedKey.key(), sessionInfo);
})
1 | Grouping by key, a prerequisite for aggregation operations |
2 | Specifying a session window for the windowing operation |
3 | Counting the number of clicks by key per session |
4 | Formatting the results. You probably won’t do this in practice, but it’s done in this tutorial to make the concept of a session more clear. |
For this session window, once there is a period of inactivity of 5 minutes or more for a given key the current session is closed and any new records arriving after that time start a new session.
Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.
NOTE: This in this example the incoming records have keys. If your input topic is not keyed, you’ll need to use the KStream.groupBy method and provide a KeyValueMapper instance to select to key to use for grouping.
That wraps up our discussion for the finer points of the code for this tutorial. Now create the following file at src/main/java/io/confluent/developer/SessionWindow.java
package io.confluent.developer;
import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.avro.specific.SpecificRecord;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.SessionWindows;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
public class SessionWindow {
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG)
.withLocale(Locale.US)
.withZone(ZoneId.systemDefault());
public Topology buildTopology(Properties allProps) {
final StreamsBuilder builder = new StreamsBuilder();
final String inputTopic = allProps.getProperty("input.topic.name");
final String outputTopic = allProps.getProperty("output.topic.name");
final SpecificAvroSerde<Clicks> clicksSerde = getSpecificAvroSerde(allProps);
builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
.groupByKey()
.windowedBy(SessionWindows.ofInactivityGapAndGrace(Duration.ofMinutes(5), Duration.ofSeconds(30)))
.count()
.toStream()
.map((windowedKey, count) -> {
String start = timeFormatter.format(windowedKey.window().startTime());
String end = timeFormatter.format(windowedKey.window().endTime());
String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
return KeyValue.pair(windowedKey.key(), sessionInfo);
})
.to(outputTopic, Produced.with(Serdes.String(), Serdes.String()));
return builder.build();
}
static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties allProps) {
final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();
final Map<String, String> serdeConfig = (Map)allProps;
specificAvroSerde.configure(serdeConfig, false);
return specificAvroSerde;
}
public void createTopics(Properties allProps) {
try (AdminClient client = AdminClient.create(allProps)) {
List<NewTopic> topicList = new ArrayList<>();
NewTopic sessionInput = new NewTopic(allProps.getProperty("input.topic.name"),
Integer.parseInt(allProps.getProperty("input.topic.partitions")),
Short.parseShort(allProps.getProperty("input.topic.replication.factor")));
topicList.add(sessionInput);
NewTopic counts = new NewTopic(allProps.getProperty("output.topic.name"),
Integer.parseInt(allProps.getProperty("output.topic.partitions")),
Short.parseShort(allProps.getProperty("output.topic.replication.factor")));
topicList.add(counts);
client.createTopics(topicList);
}
}
public Properties loadEnvProperties(String fileName) throws IOException {
Properties allProps = new Properties();
FileInputStream input = new FileInputStream(fileName);
allProps.load(input);
input.close();
return allProps;
}
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.");
}
SessionWindow tw = new SessionWindow();
Properties allProps = tw.loadEnvProperties(args[0]);
allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
allProps.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class);
Topology topology = tw.buildTopology(allProps);
tw.createTopics(allProps);
ClicksDataGenerator dataGenerator = new ClicksDataGenerator(allProps);
dataGenerator.generate();
final KafkaStreams streams = new KafkaStreams(topology, allProps);
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(Duration.ofSeconds(5));
latch.countDown();
}
});
try {
streams.cleanUp();
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
static class ClicksDataGenerator {
final Properties properties;
public ClicksDataGenerator(final Properties properties) {
this.properties = properties;
}
public void generate() {
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
try (Producer<String, Clicks> producer = new KafkaProducer<>(properties)) {
String topic = properties.getProperty("input.topic.name");
List<Clicks> sessionClicks = new ArrayList<>();
final String keyOne = "51.56.119.117";
final String keyTwo = "53.170.33.192";
Instant instant = Instant.now();
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(instant.plusMillis(9000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(24000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(38000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.plusMillis(10000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(32000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(instant.plusMillis(44000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(58000).toEpochMilli()).build());
Instant newSessionInstant = instant.plus(2, ChronoUnit.HOURS);
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(newSessionInstant.plusMillis(2000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(4000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(10000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.plusMillis(11000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(12000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(newSessionInstant.plusMillis(14000).toEpochMilli()).build());
sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(28000).toEpochMilli()).build());
sessionClicks.forEach(click -> {
producer.send(new ProducerRecord<>(topic, click.getIp(), click), (metadata, exception) -> {
if (exception != null) {
exception.printStackTrace(System.out);
} else {
System.out.printf("Produced record at offset %d to topic %s \n", metadata.offset(), metadata.topic());
}
});
});
}
}
}
}
Now that we have data generation working, let’s build your application by running:
./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/session-windows-standalone-0.0.1.jar configuration/dev.properties
This Kafka Streams application includes record generator to populate the topic with "sessionized" data. The first part of running the application will populate data in the input topic for the streams application to process. If you decide to re-run the application the data-generator will run again, giving you slightly different results. In practice, you don’t want to include something like this in a production application. |
Now that your Kafka Streams application is running, open a new terminal window, change directories (cd
) into the session-windows
directory and start a console-consumer to confirm the output:
confluent kafka topic consume output-topic --from-beginning --print-key
You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ccloud.properties
configuration file.
Look for the configuration parameter basic.auth.user.info
, whereby the ":" is the delimiter between the key and secret.
Enter your Schema Registry API key:
Enter your Schema Registry API secret:
Your results should look something like this:
51.56.119.117 : Session info started: 1:13:45 PM EST ended: 1:14:23 PM EST with count 4
53.170.33.192 : Session info started: 1:13:55 PM EST ended: 1:14:43 PM EST with count 4
51.56.119.117 : Session info started: 3:13:45 PM EST ended: 3:13:55 PM EST with count 4
53.170.33.192 : Session info started: 3:13:56 PM EST ended: 3:14:13 PM EST with count 4
Processed a total of 4 messages
You may try another tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all of the resources you created. Verify they are destroyed to avoid unexpected charges.
First, create a test file at configuration/test.properties
:
application.id=session-windows-test
bootstrap.servers=localhost:29092
schema.registry.url=mock://localhost:8081
input.topic.name=temp-readings
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1
Create a directory for the tests to live in:
mkdir -p src/test/java/io/confluent/developer
Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver
class makes this much more pleasant that it would otherwise be.
There is only one method in SessionWindowTest
annotated with @Test
, and that is sessionWindowTest()
. This method actually runs our Streams topology using the TopologyTestDriver
and some mocked data that is set up inside the test method.
This test is straightforward, but there is one section we should look into a little more
final int expectedNumberOfSessions = 2;
final String key = "51.56.119.117";
final List<Clicks> sessionClicks = new ArrayList<>();
Instant instant = Instant.now();
sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build()); (1)
Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES); (2)
sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());(3)
1 | Creating a record for the first "session" |
2 | Increasing the time to beyond inactivity period, the test should yield 2 sessions in the results |
3 | Adding record for second "session" |
The TestInputTopic provides useful methods when testing your topology. Here you’re using the pipeKeyValueList
to provide the records to the steams application. Here you’re not specifying any timestamp activity as the streams application pulls the timestamps embedded in the TemperatureReading
objects you created above.
Now create the following file at src/test/java/io/confluent/developer/SessionWindowTest.java
.
package io.confluent.developer;
import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
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.KeyValue;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.Test;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
public class SessionWindowTest {
private final static String TEST_CONFIG_FILE = "configuration/test.properties";
@Test
public void sessionWindowTest() throws IOException {
final SessionWindow instance = new SessionWindow();
final Properties allProps = instance.loadEnvProperties(TEST_CONFIG_FILE);
final String sessionDataInputTopic = allProps.getProperty("input.topic.name");
final String outputTopicName = allProps.getProperty("output.topic.name");
final Topology topology = instance.buildTopology(allProps);
try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {
final SpecificAvroSerde<Clicks> exampleAvroSerde = SessionWindow.getSpecificAvroSerde(allProps);
final Serializer<String> keySerializer = Serdes.String().serializer();
final Serializer<Clicks> exampleSerializer = exampleAvroSerde.serializer();
final Deserializer<String> valueDeserializer = Serdes.String().deserializer();
final Deserializer<String> keyDeserializer = Serdes.String().deserializer();
final TestInputTopic<String, Clicks> inputTopic = testDriver.createInputTopic(sessionDataInputTopic,
keySerializer,
exampleSerializer);
final TestOutputTopic<String, String> outputTopic = testDriver.createOutputTopic(outputTopicName, keyDeserializer, valueDeserializer);
final String key = "51.56.119.117";
final List<Clicks> sessionClicks = new ArrayList<>();
Instant instant = Instant.now();
final int expectedNumberOfSessions = 2;
sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES);
sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());
List<KeyValue<String, Clicks>> keyValues = sessionClicks.stream().map(o -> KeyValue.pair(o.getIp(),o)).collect(Collectors.toList());
inputTopic.pipeKeyValueList(keyValues);
final List<KeyValue<String, String>> actualResults = outputTopic.readKeyValuesToList();
// Should result in two sessions
assertEquals(expectedNumberOfSessions, actualResults.size());
}
}
}
Now run the test, which is as simple as:
./gradlew test