Skip to content

Commit a5de78c

Browse files
tomekl007pivovarit
authored andcommitted
Bael 766 flink (eugenp#1533)
* BAEL-756 code for flink article * reorder * simpler wordCount example * BAEL-766 changes according to PR * BAEL-766 change datasource to dataset * BAEL-766 add sorting example * BAEL-766 add simple streaming example * one missing change to dataSet * windowing example * add window example * add dependency explicitly * add plugin * add surefire plugin, change neme of the test to *IntegrationTest
1 parent 60332bb commit a5de78c

4 files changed

Lines changed: 278 additions & 0 deletions

File tree

‎libraries/pom.xml‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,31 @@
2020
<target>1.8</target>
2121
</configuration>
2222
</plugin>
23+
<plugin>
24+
<groupId>org.apache.maven.plugins</groupId>
25+
<artifactId>maven-dependency-plugin</artifactId>
26+
<dependencies>
27+
<dependency>
28+
<groupId>org.apache.felix</groupId>
29+
<artifactId>maven-bundle-plugin</artifactId>
30+
<version>3.3.0</version>
31+
<type>maven-plugin</type>
32+
33+
</dependency>
34+
</dependencies>
35+
<extensions>true</extensions>
36+
</plugin>
37+
<plugin>
38+
<groupId>org.apache.maven.plugins</groupId>
39+
<artifactId>maven-surefire-plugin</artifactId>
40+
<version>${maven-surefire-plugin.version}</version>
41+
<configuration>
42+
<excludes>
43+
<exclude>**/*IntegrationTest.java</exclude>
44+
<exclude>**/*LiveTest.java</exclude>
45+
</excludes>
46+
</configuration>
47+
</plugin>
2348
</plugins>
2449
</build>
2550

@@ -92,6 +117,21 @@
92117
<artifactId>commons-io</artifactId>
93118
<version>${commons.io.version}</version>
94119
</dependency>
120+
<dependency>
121+
<groupId>org.apache.flink</groupId>
122+
<artifactId>flink-core</artifactId>
123+
<version>${flink.version}</version>
124+
</dependency>
125+
<dependency>
126+
<groupId>org.apache.flink</groupId>
127+
<artifactId>flink-java</artifactId>
128+
<version>${flink.version}</version>
129+
</dependency>
130+
<dependency>
131+
<groupId>org.apache.flink</groupId>
132+
<artifactId>flink-test-utils_2.10</artifactId>
133+
<version>${flink.version}</version>
134+
</dependency>
95135
</dependencies>
96136

97137
<properties>
@@ -107,6 +147,8 @@
107147
<jetty.version>9.4.2.v20170220</jetty.version>
108148
<httpclient.version>4.5.3</httpclient.version>
109149
<commons.io.version>2.5</commons.io.version>
150+
<flink.version>1.2.0</flink.version>
151+
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
110152
</properties>
111153

112154
</project>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.flink;
2+
3+
import org.apache.flink.api.common.functions.FlatMapFunction;
4+
import org.apache.flink.api.java.tuple.Tuple2;
5+
import org.apache.flink.util.Collector;
6+
7+
import java.util.stream.Stream;
8+
9+
@SuppressWarnings("serial")
10+
public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
11+
12+
@Override
13+
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
14+
15+
String[] tokens = value.toLowerCase().split("\\W+");
16+
Stream.of(tokens)
17+
.filter(t -> t.length() > 0)
18+
.forEach(token -> out.collect(new Tuple2<>(token, 1)));
19+
}
20+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.flink;
2+
3+
import org.apache.flink.api.java.DataSet;
4+
import org.apache.flink.api.java.ExecutionEnvironment;
5+
import org.apache.flink.api.java.aggregation.Aggregations;
6+
import org.apache.flink.api.java.tuple.Tuple2;
7+
8+
import java.util.List;
9+
10+
public class WordCount {
11+
12+
public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
13+
DataSet<String> text = env.fromCollection(lines);
14+
15+
return text.flatMap(new LineSplitter())
16+
.groupBy(0)
17+
.aggregate(Aggregations.SUM, 1);
18+
19+
}
20+
}
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
package com.baeldung.flink;
2+
3+
import org.apache.flink.api.common.functions.ReduceFunction;
4+
import org.apache.flink.api.common.operators.Order;
5+
import org.apache.flink.api.java.DataSet;
6+
import org.apache.flink.api.java.ExecutionEnvironment;
7+
import org.apache.flink.api.java.functions.KeySelector;
8+
import org.apache.flink.api.java.tuple.Tuple2;
9+
import org.apache.flink.api.java.tuple.Tuple3;
10+
import org.apache.flink.streaming.api.datastream.DataStream;
11+
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
12+
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
13+
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
14+
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
15+
import org.apache.flink.streaming.api.windowing.time.Time;
16+
import org.junit.Test;
17+
18+
import java.time.ZonedDateTime;
19+
import java.util.Arrays;
20+
import java.util.List;
21+
22+
import static org.assertj.core.api.Assertions.assertThat;
23+
24+
25+
public class WordCountIntegrationTest {
26+
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
27+
28+
@Test
29+
public void givenDataSet_whenExecuteWordCount_thenReturnWordCount() throws Exception {
30+
//given
31+
List<String> lines = Arrays.asList("This is a first sentence", "This is a second sentence with a one word");
32+
33+
//when
34+
DataSet<Tuple2<String, Integer>> result = WordCount.startWordCount(env, lines);
35+
36+
//then
37+
List<Tuple2<String, Integer>> collect = result.collect();
38+
assertThat(collect.size()).isEqualTo(9);
39+
assertThat(collect.contains(new Tuple2<>("a", 3))).isTrue();
40+
assertThat(collect.contains(new Tuple2<>("sentence", 2))).isTrue();
41+
assertThat(collect.contains(new Tuple2<>("word", 1))).isTrue();
42+
assertThat(collect.contains(new Tuple2<>("is", 2))).isTrue();
43+
assertThat(collect.contains(new Tuple2<>("this", 2))).isTrue();
44+
assertThat(collect.contains(new Tuple2<>("second", 1))).isTrue();
45+
assertThat(collect.contains(new Tuple2<>("first", 1))).isTrue();
46+
}
47+
48+
@Test
49+
public void givenListOfAmounts_whenUseMapReduce_thenSumAmountsThatAreOnlyAboveThreshold() throws Exception {
50+
//given
51+
DataSet<Integer> amounts = env.fromElements(1, 29, 40, 50);
52+
int threshold = 30;
53+
54+
//when
55+
List<Integer> collect = amounts
56+
.filter(a -> a > threshold)
57+
.reduce((ReduceFunction<Integer>) (integer, t1) -> integer + t1)
58+
.collect();
59+
60+
//then
61+
assertThat(collect.get(0)).isEqualTo(90);
62+
}
63+
64+
@Test
65+
public void givenDataSetOfComplexObjects_whenMapToGetOneField_thenReturnedListHaveProperElements() throws Exception {
66+
//given
67+
DataSet<Person> personDataSource = env.fromCollection(Arrays.asList(new Person(23, "Tom"), new Person(75, "Michael")));
68+
69+
//when
70+
List<Integer> ages = personDataSource.map(p -> p.age).collect();
71+
72+
//then
73+
assertThat(ages.size()).isEqualTo(2);
74+
assertThat(ages.containsAll(Arrays.asList(23, 75))).isTrue();
75+
76+
}
77+
78+
@Test
79+
public void givenDataSet_whenSortItByOneField_thenShouldReturnSortedDataSet() throws Exception {
80+
//given
81+
Tuple2<Integer, String> secondPerson = new Tuple2<>(4, "Tom");
82+
Tuple2<Integer, String> thirdPerson = new Tuple2<>(5, "Scott");
83+
Tuple2<Integer, String> fourthPerson = new Tuple2<>(200, "Michael");
84+
Tuple2<Integer, String> firstPerson = new Tuple2<>(1, "Jack");
85+
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(fourthPerson, secondPerson,
86+
thirdPerson, firstPerson);
87+
88+
89+
//when
90+
List<Tuple2<Integer, String>> sorted = transactions
91+
.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING)
92+
.collect();
93+
94+
//then
95+
assertThat(sorted.size()).isEqualTo(4);
96+
assertThat(sorted.get(0)).isEqualTo(firstPerson);
97+
assertThat(sorted.get(1)).isEqualTo(secondPerson);
98+
assertThat(sorted.get(2)).isEqualTo(thirdPerson);
99+
assertThat(sorted.get(3)).isEqualTo(fourthPerson);
100+
101+
}
102+
103+
104+
@Test
105+
public void giveTwoDataSets_whenJoinUsingId_thenProduceJoinedData() throws Exception {
106+
//given
107+
Tuple3<Integer, String, String> address = new Tuple3<>(1, "5th Avenue", "London");
108+
DataSet<Tuple3<Integer, String, String>> addresses = env.fromElements(address);
109+
110+
Tuple2<Integer, String> firstTransaction = new Tuple2<>(1, "Transaction_1");
111+
DataSet<Tuple2<Integer, String>> transactions =
112+
env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
113+
114+
115+
//when
116+
List<Tuple2<Tuple2<Integer, String>, Tuple3<Integer, String, String>>> joined =
117+
transactions.join(addresses)
118+
.where(new IdKeySelectorTransaction())
119+
.equalTo(new IdKeySelectorAddress())
120+
.collect();
121+
122+
//then
123+
assertThat(joined.size()).isEqualTo(1);
124+
assertThat(joined.contains(new Tuple2<>(firstTransaction, address)));
125+
126+
}
127+
128+
@Test
129+
public void givenStreamOfEvents_whenProcessEvents_thenShouldPrintResultsOnSinkOperation() throws Exception {
130+
//given
131+
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
132+
133+
DataStream<String> text
134+
= env.fromElements("This is a first sentence", "This is a second sentence with a one word");
135+
136+
137+
SingleOutputStreamOperator<String> upperCase = text.map(String::toUpperCase);
138+
139+
upperCase.print();
140+
141+
//when
142+
env.execute();
143+
}
144+
145+
146+
@Test
147+
public void givenStreamOfEvents_whenProcessEvents_thenShouldApplyWindowingOnTransformation() throws Exception {
148+
//given
149+
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
150+
151+
SingleOutputStreamOperator<Tuple2<Integer, Long>> windowed = env.fromElements(
152+
new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()),
153+
new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())
154+
).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Integer, Long>>(Time.seconds(20)) {
155+
@Override
156+
public long extractTimestamp(Tuple2<Integer, Long> element) {
157+
return element.f1 * 1000;
158+
}
159+
});
160+
161+
SingleOutputStreamOperator<Tuple2<Integer, Long>> reduced = windowed
162+
.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
163+
.maxBy(0, true);
164+
165+
reduced.print();
166+
167+
//when
168+
env.execute();
169+
}
170+
171+
172+
private static class IdKeySelectorTransaction implements KeySelector<Tuple2<Integer, String>, Integer> {
173+
@Override
174+
public Integer getKey(Tuple2<Integer, String> value) {
175+
return value.f0;
176+
}
177+
}
178+
179+
private static class IdKeySelectorAddress implements KeySelector<Tuple3<Integer, String, String>, Integer> {
180+
@Override
181+
public Integer getKey(Tuple3<Integer, String, String> value) {
182+
return value.f0;
183+
}
184+
}
185+
186+
private static class Person {
187+
private final int age;
188+
private final String name;
189+
190+
private Person(int age, String name) {
191+
this.age = age;
192+
this.name = name;
193+
}
194+
}
195+
196+
}

0 commit comments

Comments
 (0)