import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

public class WindowWordCount {

	public static void main(String[] args) throws Exception {
		
		// Vorher mit nc 127.0.0.1 -kl 9995 den Eingabe-Stream in der Konsole öffnen
		// Linux/Mac bringt netcat bereits mit, unter Win ggf. nachinstallieren
		
		StreamExecutionEnvironment env = 
				StreamExecutionEnvironment.getExecutionEnvironment();
		
		DataStream<Tuple2<String, Integer>> dataStream = env
				.socketTextStream("localhost", 9995)
//				.readTextFile("file:///tmp/faust.txt")
				.flatMap((String sentence, Collector<Tuple2<String, Integer>> out) -> {
					for (String word: sentence.split(" ")) {
						out.collect(new Tuple2<String, Integer>(word, 1));
					}})	.returns(Types.TUPLE(Types.STRING, Types.INT))
				.keyBy(0)
				.timeWindow(Time.seconds(21))
//				.countWindow(5, 3)
				.sum(1);

		dataStream.print();

		env.execute("Window WordCount");

	}

}
