Java Examples for org.apache.kafka.streams.kstream.Transformer

The following java examples will help you to understand the usage of org.apache.kafka.streams.kstream.Transformer. These source code samples are taken from different open source projects.

Example 1
Project: kafka-master  File: KStreamTransformTest.java View source code
public Transformer<Number, Number, KeyValue<Integer, Integer>> get() {
    return new Transformer<Number, Number, KeyValue<Integer, Integer>>() {

        private int total = 0;

        @Override
        public void init(ProcessorContext context) {
        }

        @Override
        public KeyValue<Integer, Integer> transform(Number key, Number value) {
            total += value.intValue();
            return KeyValue.pair(key.intValue() * 2, total);
        }

        @Override
        public KeyValue<Integer, Integer> punctuate(long timestamp) {
            return KeyValue.pair(-1, (int) timestamp);
        }

        @Override
        public void close() {
        }
    };
}
Example 2
Project: examples-master  File: StateStoresInTheDSLIntegrationTest.java View source code
@Override
public Transformer<byte[], String, KeyValue<String, Long>> get() {
    return new Transformer<byte[], String, KeyValue<String, Long>>() {

        private KeyValueStore<String, Long> stateStore;

        @SuppressWarnings("unchecked")
        @Override
        public void init(ProcessorContext context) {
            stateStore = (KeyValueStore<String, Long>) context.getStateStore(stateStoreName);
        }

        @Override
        public KeyValue<String, Long> transform(byte[] key, String value) {
            // For simplification (and unlike the traditional wordcount) we assume that the value is
            // a single word, i.e. we don't split the value by whitespace into potentially one or more
            // words.
            Optional<Long> count = Optional.ofNullable(stateStore.get(value));
            Long incrementedCount = count.orElse(0L) + 1;
            stateStore.put(value, incrementedCount);
            return KeyValue.pair(value, incrementedCount);
        }

        @Override
        public KeyValue<String, Long> punctuate(long timestamp) {
            // Not needed
            return null;
        }

        @Override
        public void close() {
        // Note: The store should NOT be closed manually here via `stateStore.close()`!
        // The Kafka Streams API will automatically close stores when necessary.
        }
    };
}