├── .github
└── workflows
│ └── maven.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── iniesta
│ │ ├── com
│ │ ├── SimpleDataQuery.java
│ │ └── SimpleSubscriber.java
│ │ └── flink
│ │ └── connector
│ │ ├── mqtt
│ │ ├── Mqtt2Mysql.java
│ │ ├── MqttMessage.java
│ │ ├── MqttOutputFormat.java
│ │ ├── MqttSink.java
│ │ ├── MqttSource.java
│ │ ├── MqttWordCount2Mqtt.java
│ │ ├── SocketTextStreamWordCount2Mqtt.java
│ │ └── WordCount2Mqtt.java
│ │ └── mysql
│ │ ├── MysqlDao.java
│ │ └── MysqlSink.java
└── resources
│ └── create.sql
└── test
└── java
└── com
└── iniesta
└── flink
└── connector
└── mqtt
├── BrokerPublisherManual.java
└── DummyTest.java
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
3 |
4 | name: Java CI with Maven
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Set up JDK 1.8
20 | uses: actions/setup-java@v1
21 | with:
22 | java-version: 1.8
23 | - name: Build with Maven
24 | run: mvn -B package --file pom.xml
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 | .settings
11 | .classpath
12 | .project
13 | /bin/
14 | /conf.properties
15 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM java:8
2 |
3 | USER root
4 |
5 | RUN mkdir /usr/mqtt2mysql
6 |
7 | #RUN curl -Ls https://github.com/ajiniesta/flink-connector-mqtt/releases/download/0.1/flink-connector-mqtt-0.1.jar > /usr/mqtt2mysql/flink-con-mqtt.jar
8 |
9 | COPY target/flink-connector-mqtt-*.jar /usr/mqtt2mysql/flink-con-mqtt.jar
10 |
11 | CMD sleep 15 && java -cp /usr/mqtt2mysql/flink-con-mqtt.jar com.iniesta.flink.connector.mqtt.Mqtt2Mysql --conf /conf/conf.properties
12 |
13 |
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # flink-connector-mqtt
2 | Connector to MQTT in Flink
3 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | com.iniesta
5 | flink-connector-mqtt
6 | 0.2
7 | jar
8 |
9 | Flink Connector for mqtt
10 | http://iniestadev.com
11 |
12 |
13 | UTF-8
14 | 1.3.2
15 | 1.7.7
16 | 1.2.17
17 | 2.10
18 | 1.12
19 | MM.yyyy
20 | ${maven.build.timestamp}
21 |
22 |
23 |
24 |
27 |
28 | flink-connector-mqtt
29 | Flink Connector Mqtt
30 | ${yearMonth}
31 | java
32 | UTF-8
33 | jacoco
34 |
35 | 0.7.2.201409121644
36 |
38 | 1.4
39 |
41 |
42 |
49 | ${project.build.directory}
50 |
51 | jacoco-ut.exec
52 |
54 | ${jacoco.outputDir}/${jacoco.out.ut.file}
55 |
56 | jacoco-it.exec
57 |
59 | ${jacoco.outputDir}/${jacoco.out.it.file}
60 |
61 |
62 |
63 |
64 |
65 |
67 |
68 |
69 |
70 | apache.snapshots
71 | Apache Development Snapshot Repository
72 | https://repository.apache.org/content/repositories/snapshots/
73 |
74 | false
75 |
76 |
77 | true
78 |
79 |
80 |
81 |
82 |
83 |
84 | org.fusesource.mqtt-client
85 | mqtt-client
86 | ${mqtt-client.version}
87 |
88 |
89 | org.apache.flink
90 | flink-java
91 | ${flink.version}
92 |
93 |
94 | org.apache.flink
95 | flink-streaming-java_2.10
96 | ${flink.version}
97 |
98 |
99 | org.fusesource.hawtbuf
100 | hawtbuf
101 | 1.11
102 |
103 |
104 | org.fusesource.hawtdispatch
105 | hawtdispatch
106 | 1.22
107 |
108 |
109 | org.fusesource.hawtdispatch
110 | hawtdispatch-transport
111 | 1.22
112 |
113 |
114 | mysql
115 | mysql-connector-java
116 | [8.0.16,)
117 |
118 |
119 | postgresql
120 | postgresql
121 | 9.1-901-1.jdbc4
122 |
123 |
124 | junit
125 | junit
126 | 4.12
127 | test
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 | external.atlassian.jgitflow
136 | jgitflow-maven-plugin
137 | 1.0-m5.1
138 |
139 |
140 | com.jcraft
141 | jsch
142 | 0.1.54
143 |
144 |
145 |
146 | true
147 | [RELEASE]
148 |
149 |
150 |
151 | org.jacoco
152 | jacoco-maven-plugin
153 | ${jacoco.version}
154 |
155 | jacoco.agent.argLine
156 | ${sonar.jacoco.itReportPath}
157 | true
158 |
159 |
160 |
161 | agent
162 |
163 | prepare-agent
164 |
165 |
166 |
167 |
168 |
169 | org.apache.maven.plugins
170 | maven-compiler-plugin
171 | 3.1
172 |
173 | 1.8
174 | 1.8
175 |
176 |
177 |
178 | org.apache.maven.plugins
179 | maven-javadoc-plugin
180 | 3.1.0
181 |
182 | -Xdoclint:none
183 | none
184 |
185 |
186 |
187 | org.apache.maven.plugins
188 | maven-shade-plugin
189 | 2.4.1
190 |
191 |
192 | package
193 |
194 | shade
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/com/SimpleDataQuery.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.com;
2 |
3 | import java.io.FileInputStream;
4 | import java.util.List;
5 | import java.util.Properties;
6 |
7 | import com.iniesta.flink.connector.mysql.MysqlDao;
8 |
9 | public class SimpleDataQuery {
10 |
11 | public static void main(String[] args) throws Exception {
12 | Properties props = new Properties();
13 | props.load(new FileInputStream(args[0]));
14 |
15 | MysqlDao dao = new MysqlDao(props);
16 | dao.open();
17 |
18 | List res = dao.testQuery();
19 | System.out.println(res);
20 |
21 | dao.close();
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/com/SimpleSubscriber.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.com;
2 |
3 | import java.io.FileInputStream;
4 | import java.util.Properties;
5 |
6 | import org.fusesource.mqtt.client.BlockingConnection;
7 | import org.fusesource.mqtt.client.MQTT;
8 | import org.fusesource.mqtt.client.Message;
9 | import org.fusesource.mqtt.client.QoS;
10 | import org.fusesource.mqtt.client.Topic;
11 |
12 | import com.iniesta.flink.connector.mqtt.MqttMessage;
13 |
14 | public class SimpleSubscriber {
15 |
16 | public static void main(String[] args) throws Exception {
17 | Properties props = new Properties();
18 | props.load(new FileInputStream(args[0]));
19 |
20 | String hostName = props.getProperty("mqtt.host");
21 | int port = Integer.parseInt(props.getProperty("mqtt.port", "1883"));
22 | String topic = props.getProperty("mqtt.topic");
23 |
24 |
25 | MQTT mqtt = new MQTT();
26 | mqtt.setHost(hostName, port);
27 | BlockingConnection blockingConnection = mqtt.blockingConnection();
28 | try {
29 | blockingConnection.connect();
30 | } catch(Exception ex) {
31 | System.out.println("[Source] Not connected");
32 | ex.printStackTrace();
33 | }
34 | System.out.println("[Source] Connected to mqtt broker");
35 |
36 | byte[] qoses = blockingConnection.subscribe(new Topic[] {new Topic(topic, QoS.AT_LEAST_ONCE)});
37 | System.out.println("[Source] Subscribe to " + topic);
38 |
39 | while(blockingConnection.isConnected()) {
40 | Message message = blockingConnection.receive();
41 | System.out.println("[Source] Receiving message, now process internal message");
42 | MqttMessage mmsg = new MqttMessage(message.getTopic(), new String(message.getPayload()));
43 | System.out.println("[Source]: " + mmsg);
44 | message.ack();
45 | System.out.println("[msg] "+ mmsg);
46 | }
47 | blockingConnection.disconnect();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/Mqtt2Mysql.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import java.io.FileInputStream;
4 | import java.util.Properties;
5 |
6 | /*
7 | * Licensed to the Apache Software Foundation (ASF) under one or more
8 | * contributor license agreements. See the NOTICE file distributed with
9 | * this work for additional information regarding copyright ownership.
10 | * The ASF licenses this file to You under the Apache License, Version 2.0
11 | * (the "License"); you may not use this file except in compliance with
12 | * the License. You may obtain a copy of the License at
13 | *
14 | * http://www.apache.org/licenses/LICENSE-2.0
15 | *
16 | * Unless required by applicable law or agreed to in writing, software
17 | * distributed under the License is distributed on an "AS IS" BASIS,
18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 | * See the License for the specific language governing permissions and
20 | * limitations under the License.
21 | */
22 |
23 | import org.apache.flink.api.common.functions.FlatMapFunction;
24 | import org.apache.flink.api.java.tuple.Tuple2;
25 | import org.apache.flink.api.java.utils.ParameterTool;
26 | import org.apache.flink.streaming.api.datastream.DataStream;
27 | import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
28 | import org.apache.flink.util.Collector;
29 |
30 | import com.iniesta.flink.connector.mysql.MysqlSink;
31 |
32 |
33 | public class Mqtt2Mysql {
34 |
35 | //
36 | // Program
37 | //
38 |
39 | public static void main(String[] args) throws Exception {
40 |
41 | ParameterTool pt = ParameterTool.fromArgs(args);
42 |
43 | String properties = pt.getRequired("conf");
44 | Properties props = new Properties();
45 | props.load(new FileInputStream(properties));
46 |
47 | String hostName = props.getProperty("mqtt.host");
48 | int port = Integer.parseInt(props.getProperty("mqtt.port", "1883"));
49 | String topicIn = props.getProperty("mqtt.topic");
50 | System.out.println("Properties.... " + props.toString());
51 |
52 | // set up the execution environment
53 | final StreamExecutionEnvironment env = StreamExecutionEnvironment
54 | .getExecutionEnvironment();
55 |
56 | // get input data
57 | DataStream text = env.addSource(new MqttSource(hostName, port, topicIn));
58 |
59 | // DataStream> counts =
60 | // split up the lines in pairs (2-tuples) containing: (word,1)
61 | // text.flatMap(new LineSplitter())
62 | // group by the tuple field "0" and sum up tuple field "1"
63 | // .keyBy(0)
64 | // .sum(1);
65 |
66 | // text.print();
67 | // counts.addSink(new MqttSink<>(hostName, topicOut));
68 | text.addSink(new MysqlSink(props));
69 | // execute program
70 | int parallelism = Integer.parseInt(props.getProperty("flink.parallelism", "2"));
71 | env.setParallelism(parallelism);
72 | System.out.println("About to execute....");
73 | env.execute("Mqtt 2 JDBC");
74 | }
75 |
76 | //
77 | // User Functions
78 | //
79 |
80 | /**
81 | * Implements the string tokenizer that splits sentences into words as a user-defined
82 | * FlatMapFunction. The function takes a line (String) and splits it into
83 | * multiple pairs in the form of "(word,1)" (Tuple2).
84 | */
85 | @SuppressWarnings("serial")
86 | public static final class LineSplitter implements FlatMapFunction> {
87 |
88 | @Override
89 | public void flatMap(MqttMessage value, Collector> out) {
90 | // normalize and split the line
91 | String[] tokens = value.getPayload().toLowerCase().split("\\W+");
92 |
93 | // emit the pairs
94 | for (String token : tokens) {
95 | if (token.length() > 0) {
96 | out.collect(new Tuple2(token, 1));
97 | }
98 | }
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/MqttMessage.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import java.io.Serializable;
4 |
5 | public class MqttMessage implements Serializable {
6 |
7 | private static final long serialVersionUID = -4673414704450588069L;
8 |
9 | private String topic;
10 | private String payload;
11 |
12 | public MqttMessage() {
13 | }
14 |
15 | public MqttMessage(String topic, String payload) {
16 | super();
17 | this.topic = topic;
18 | this.payload = payload;
19 | }
20 |
21 | public String getTopic() {
22 | return topic;
23 | }
24 |
25 | public void setTopic(String topic) {
26 | this.topic = topic;
27 | }
28 |
29 | public String getPayload() {
30 | return payload;
31 | }
32 |
33 | public void setPayload(String payload) {
34 | this.payload = payload;
35 | }
36 |
37 | @Override
38 | public int hashCode() {
39 | final int prime = 31;
40 | int result = 1;
41 | result = prime * result + ((payload == null) ? 0 : payload.hashCode());
42 | result = prime * result + ((topic == null) ? 0 : topic.hashCode());
43 | return result;
44 | }
45 |
46 | @Override
47 | public boolean equals(Object obj) {
48 | if (this == obj)
49 | return true;
50 | if (obj == null)
51 | return false;
52 | if (getClass() != obj.getClass())
53 | return false;
54 | MqttMessage other = (MqttMessage) obj;
55 | if (payload == null) {
56 | if (other.payload != null)
57 | return false;
58 | } else if (!payload.equals(other.payload))
59 | return false;
60 | if (topic == null) {
61 | if (other.topic != null)
62 | return false;
63 | } else if (!topic.equals(other.topic))
64 | return false;
65 | return true;
66 | }
67 |
68 | @Override
69 | public String toString() {
70 | return "MqttMessage [topic=" + topic + ", payload=" + payload + "]";
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/MqttOutputFormat.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import java.io.IOException;
4 | import java.net.URISyntaxException;
5 |
6 | import org.apache.flink.api.common.io.RichOutputFormat;
7 | import org.apache.flink.configuration.Configuration;
8 | import org.fusesource.mqtt.client.BlockingConnection;
9 | import org.fusesource.mqtt.client.MQTT;
10 | import org.fusesource.mqtt.client.QoS;
11 |
12 | public class MqttOutputFormat extends RichOutputFormat{
13 |
14 | private static final long serialVersionUID = -260008582961487797L;
15 |
16 | private transient BlockingConnection blockingConnection;
17 | private transient MQTT mqtt;
18 | private String topic;
19 | private QoS qos;
20 | private boolean retain;
21 | private String host;
22 | private int port;
23 |
24 | public MqttOutputFormat(String host, String topic) {
25 | this(host, 1883, topic, QoS.AT_LEAST_ONCE, false);
26 | }
27 |
28 | public MqttOutputFormat(String host, int port, String topic) {
29 | this(host, port, topic, QoS.AT_LEAST_ONCE, false);
30 | }
31 |
32 | public MqttOutputFormat(String host, int port, String topic, QoS qos, boolean retain) {
33 | this.host = host;
34 | this.port = port;
35 | this.topic = topic;
36 | this.qos = qos;
37 | this.retain = retain;
38 | }
39 |
40 | @Override
41 | public void close() throws IOException {
42 | System.out.println("closing....");
43 | try {
44 | if(blockingConnection!=null) {
45 | blockingConnection.disconnect();
46 | }
47 | } catch (Exception e) {
48 | e.printStackTrace();
49 | }
50 | }
51 |
52 | @Override
53 | public void configure(Configuration arg0) {
54 | System.out.println("configuring output format....");
55 | }
56 |
57 | @Override
58 | public void open(int arg0, int arg1) throws IOException {
59 | System.out.println("opening...."+ arg0 + " " + arg1);
60 | mqtt = new MQTT();
61 | try {
62 | mqtt.setHost(host, port);
63 | blockingConnection = mqtt.blockingConnection();
64 | blockingConnection.connect();
65 | } catch (URISyntaxException e) {
66 | e.printStackTrace();
67 | } catch (Exception e) {
68 | e.printStackTrace();
69 | }
70 |
71 | }
72 |
73 | @Override
74 | public void writeRecord(IT record) throws IOException {
75 | System.out.println("writing record...." + record);
76 | byte[] payload = record.toString().getBytes();
77 | try {
78 | blockingConnection.publish(topic, payload, qos, retain);
79 | } catch (Exception e) {
80 | e.printStackTrace();
81 | }
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/MqttSink.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import org.apache.flink.configuration.Configuration;
4 | import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
5 | import org.fusesource.mqtt.client.BlockingConnection;
6 | import org.fusesource.mqtt.client.MQTT;
7 | import org.fusesource.mqtt.client.QoS;
8 |
9 | public class MqttSink extends RichSinkFunction {
10 |
11 | private static final long serialVersionUID = 7883296716671354462L;
12 |
13 | private transient BlockingConnection blockingConnection;
14 | private String topic;
15 | private QoS qos;
16 | private boolean retain;
17 |
18 | private String host;
19 |
20 | private int port;
21 |
22 | public MqttSink(String host, String topic) {
23 | this(host, 1883, topic, QoS.AT_LEAST_ONCE, false);
24 | }
25 |
26 |
27 | public MqttSink(String host, int port, String topic) {
28 | this(host, port, topic, QoS.AT_LEAST_ONCE, false);
29 | }
30 |
31 | public MqttSink(String host, int port, String topic, QoS qos, boolean retain) {
32 | this.host = host;
33 | this.port = port;
34 | this.topic = topic;
35 | this.qos = qos;
36 | this.retain = retain;
37 | }
38 |
39 | @Override
40 | public void invoke(T event) throws Exception {
41 | byte[] payload = event.toString().getBytes();
42 | blockingConnection.publish(topic, payload, qos, retain);
43 | }
44 |
45 | @Override
46 | public void close() throws Exception {
47 | super.close();
48 | blockingConnection.disconnect();
49 | }
50 |
51 | @Override
52 | public void open(Configuration parameters) throws Exception {
53 | super.open(parameters);
54 | MQTT mqtt = new MQTT();
55 | mqtt.setHost(host, port);
56 | blockingConnection = mqtt.blockingConnection();
57 | blockingConnection.connect();
58 | }
59 |
60 |
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/MqttSource.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
4 | import org.fusesource.mqtt.client.BlockingConnection;
5 | import org.fusesource.mqtt.client.MQTT;
6 | import org.fusesource.mqtt.client.Message;
7 | import org.fusesource.mqtt.client.QoS;
8 | import org.fusesource.mqtt.client.Topic;
9 |
10 | public class MqttSource extends RichSourceFunction{
11 |
12 | private String host;
13 | private int port;
14 | private String topic;
15 | private QoS qos;
16 | private boolean retain;
17 |
18 | public MqttSource(String host, String topic) {
19 | this(host, 1883, topic, QoS.AT_LEAST_ONCE, false);
20 | }
21 |
22 | public MqttSource(String host, int port, String topic) {
23 | this(host, port, topic, QoS.AT_LEAST_ONCE, false);
24 | }
25 |
26 | public MqttSource(String host, int port, String topic, QoS qos, boolean retain) {
27 | this.host = host;
28 | this.port = port;
29 | this.topic = topic;
30 | this.qos = qos;
31 | this.retain = retain;
32 | }
33 |
34 | @Override
35 | public void cancel() {
36 | // TODO Auto-generated method stub
37 |
38 | }
39 |
40 | @Override
41 | public void run(SourceContext sourceContext) throws Exception {
42 | System.out.println("[Source] Running source");
43 | MQTT mqtt = new MQTT();
44 | mqtt.setHost(host, port);
45 | BlockingConnection blockingConnection = mqtt.blockingConnection();
46 | blockingConnection.connect();
47 | System.out.println("[Source] Connected to mqtt broker");
48 |
49 | byte[] qoses = blockingConnection.subscribe(new Topic[] {new Topic(topic, qos)});
50 | System.out.println("[Source] Subscribed to " + topic);
51 |
52 | while(blockingConnection.isConnected()) {
53 | Message message = blockingConnection.receive();
54 | MqttMessage mmsg = new MqttMessage(message.getTopic(), new String(message.getPayload()));
55 | message.ack();
56 | sourceContext.collect(mmsg);
57 | }
58 | blockingConnection.disconnect();
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/MqttWordCount2Mqtt.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | /*
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with
6 | * this work for additional information regarding copyright ownership.
7 | * The ASF licenses this file to You under the Apache License, Version 2.0
8 | * (the "License"); you may not use this file except in compliance with
9 | * the License. You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.apache.flink.api.common.functions.FlatMapFunction;
21 | import org.apache.flink.api.java.tuple.Tuple2;
22 | import org.apache.flink.streaming.api.datastream.DataStream;
23 | import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
24 | import org.apache.flink.util.Collector;
25 |
26 | public class MqttWordCount2Mqtt {
27 |
28 | //
29 | // Program
30 | //
31 |
32 | public static void main(String[] args) throws Exception {
33 |
34 | if (args.length != 3) {
35 | System.err.println("USAGE:\nMqttWordCount2Mqtt ");
36 | return;
37 | }
38 |
39 | String hostName = args[0];
40 | String topicIn = args[1];
41 | String topicOut = args[2];
42 |
43 | // set up the execution environment
44 | final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
45 |
46 | // get input data
47 | DataStream text = env.addSource(new MqttSource(hostName, topicIn));
48 |
49 | DataStream> counts =
50 | // split up the lines in pairs (2-tuples) containing: (word,1)
51 | text.flatMap(new LineSplitter())
52 | // group by the tuple field "0" and sum up tuple field "1"
53 | .keyBy(0).sum(1);
54 |
55 | // counts.print();
56 | counts.addSink(new MqttSink<>(hostName, topicOut));
57 |
58 | // execute program
59 | env.execute("Java WordCount from SocketTextStream Example");
60 | }
61 |
62 | //
63 | // User Functions
64 | //
65 |
66 | /**
67 | * Implements the string tokenizer that splits sentences into words as a
68 | * user-defined FlatMapFunction. The function takes a line (String) and splits
69 | * it into multiple pairs in the form of "(word,1)" (Tuple2).
70 | */
71 | @SuppressWarnings("serial")
72 | public static final class LineSplitter implements FlatMapFunction> {
73 |
74 | @Override
75 | public void flatMap(MqttMessage value, Collector> out) {
76 | // normalize and split the line
77 | String[] tokens = value.getPayload().toLowerCase().split("\\W+");
78 |
79 | // emit the pairs
80 | for (String token : tokens) {
81 | if (token.length() > 0) {
82 | out.collect(new Tuple2(token, 1));
83 | }
84 | }
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/SocketTextStreamWordCount2Mqtt.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import org.apache.flink.api.common.functions.FlatMapFunction;
4 | import org.apache.flink.api.java.tuple.Tuple2;
5 | import org.apache.flink.streaming.api.datastream.DataStream;
6 | import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
7 | import org.apache.flink.util.Collector;
8 |
9 | public class SocketTextStreamWordCount2Mqtt {
10 |
11 | //
12 | // Program
13 | //
14 |
15 | public static void main(String[] args) throws Exception {
16 |
17 | if (args.length != 2) {
18 | System.err.println("USAGE:\nSocketTextStreamWordCount ");
19 | return;
20 | }
21 |
22 | String hostName = args[0];
23 | Integer port = Integer.parseInt(args[1]);
24 |
25 | // set up the execution environment
26 | final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
27 |
28 | // get input data
29 | DataStream text = env.socketTextStream(hostName, port);
30 |
31 | DataStream> counts =
32 | // split up the lines in pairs (2-tuples) containing: (word,1)
33 | text.flatMap(new LineSplitter())
34 | // group by the tuple field "0" and sum up tuple field "1"
35 | .keyBy(0).sum(1);
36 |
37 | // counts.print();
38 | counts.addSink(new MqttSink<>("cydonia", "/samples"));
39 |
40 | // execute program
41 | env.execute("Java WordCount from SocketTextStream Example");
42 | }
43 |
44 | //
45 | // User Functions
46 | //
47 |
48 | /**
49 | * Implements the string tokenizer that splits sentences into words as a
50 | * user-defined FlatMapFunction. The function takes a line (String) and splits
51 | * it into multiple pairs in the form of "(word,1)" (Tuple2).
52 | */
53 | public static final class LineSplitter implements FlatMapFunction> {
54 |
55 | @Override
56 | public void flatMap(String value, Collector> out) {
57 | // normalize and split the line
58 | String[] tokens = value.toLowerCase().split("\\W+");
59 |
60 | // emit the pairs
61 | for (String token : tokens) {
62 | if (token.length() > 0) {
63 | out.collect(new Tuple2(token, 1));
64 | }
65 | }
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mqtt/WordCount2Mqtt.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | /**
4 | * Licensed to the Apache Software Foundation (ASF) under one
5 | * or more contributor license agreements. See the NOTICE file
6 | * distributed with this work for additional information
7 | * regarding copyright ownership. The ASF licenses this file
8 | * to you under the Apache License, Version 2.0 (the
9 | * "License"); you may not use this file except in compliance
10 | * with the License. You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
21 | import org.apache.flink.api.java.DataSet;
22 | import org.apache.flink.api.java.ExecutionEnvironment;
23 | import org.apache.flink.api.java.operators.DataSink;
24 | import org.apache.flink.api.common.functions.FlatMapFunction;
25 | import org.apache.flink.api.java.tuple.Tuple2;
26 | import org.apache.flink.util.Collector;
27 |
28 | public class WordCount2Mqtt {
29 |
30 | //
31 | // Program
32 | //
33 |
34 | public static void main(String[] args) throws Exception {
35 |
36 | // set up the execution environment
37 | final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
38 |
39 | // get input data
40 | DataSet text = env.fromElements("To be, or not to be,--that is the question:--",
41 | "Whether 'tis nobler in the mind to suffer", "The slings and arrows of outrageous fortune",
42 | "Or to take arms against a sea of troubles,");
43 |
44 | DataSet> counts =
45 | // split up the lines in pairs (2-tuples) containing: (word,1)
46 | text.flatMap(new LineSplitter())
47 | // group by the tuple field "0" and sum up tuple field "1"
48 | .groupBy(0).sum(1);
49 |
50 | // execute and print result
51 | // counts.print();
52 |
53 | DataSink> dataSink = counts.output(new MqttOutputFormat<>("cydonia", 1883, "/samples"));
54 |
55 | env.execute();
56 |
57 | }
58 |
59 | //
60 | // User Functions
61 | //
62 |
63 | /**
64 | * Implements the string tokenizer that splits sentences into words as a
65 | * user-defined FlatMapFunction. The function takes a line (String) and splits
66 | * it into multiple pairs in the form of "(word,1)" (Tuple2).
67 | */
68 | public static final class LineSplitter implements FlatMapFunction> {
69 |
70 | @Override
71 | public void flatMap(String value, Collector> out) {
72 | // normalize and split the line
73 | String[] tokens = value.toLowerCase().split("\\W+");
74 |
75 | // emit the pairs
76 | for (String token : tokens) {
77 | if (token.length() > 0) {
78 | out.collect(new Tuple2(token, 1));
79 | }
80 | }
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mysql/MysqlDao.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mysql;
2 |
3 | import java.io.Serializable;
4 | import java.sql.Connection;
5 | import java.sql.DriverManager;
6 | import java.sql.PreparedStatement;
7 | import java.sql.ResultSet;
8 | import java.sql.SQLException;
9 | import java.sql.Statement;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 | import java.util.Properties;
13 |
14 | import org.slf4j.Logger;
15 | import org.slf4j.LoggerFactory;
16 |
17 | import com.iniesta.flink.connector.mqtt.MqttMessage;
18 |
19 | public class MysqlDao implements Serializable {
20 |
21 | private static final Logger logger = LoggerFactory.getLogger(MysqlDao.class);
22 |
23 | private String url;
24 | private String user;
25 | private String pass;
26 | private String driver;
27 | private transient Connection connection;
28 |
29 | private final String defaultInsertQuery = "insert into messages(topic, payload, ts) values (?,?,now())";
30 | private final String defaultCreateQuery = "create table if not exists messages(id int not null auto_increment primary key, topic varchar(255), payload varchar(10000),ts datetime)";
31 | private String sqlCreate;
32 | private String sqlInsert;
33 |
34 | public MysqlDao(Properties props) {
35 |
36 | url = props.getProperty("jdbc.url");
37 | user = props.getProperty("jdbc.user");
38 | pass = props.getProperty("jdbc.pass");
39 | driver = props.getProperty("jdbc.driver");
40 | sqlCreate = props.getProperty("jdbc.sql.create", defaultCreateQuery);
41 | sqlInsert = props.getProperty("jdbc.sql.insert", defaultInsertQuery);
42 | }
43 |
44 | public void open() {
45 | if (connection == null) {
46 | try {
47 | Class.forName(driver);
48 | connection = DriverManager.getConnection(url, user, pass);
49 | createTable();
50 | } catch (ClassNotFoundException e) {
51 | e.printStackTrace();
52 | } catch (SQLException e) {
53 | e.printStackTrace();
54 | }
55 | }
56 | }
57 |
58 | public void close() {
59 | if (connection != null) {
60 | logger.debug("Destroying connection to: {}:{}", url, user);
61 | try {
62 | connection.close();
63 | } catch (SQLException e) {
64 | e.printStackTrace();
65 | }
66 | }
67 | connection = null;
68 | }
69 |
70 | public void process(MqttMessage msg) {
71 | insertData(msg);
72 | }
73 |
74 | private static String escapeSQL(String s) {
75 | return s.replaceAll("'", "\\'");
76 | }
77 |
78 | private void insertData(MqttMessage msg) {
79 | try {
80 | PreparedStatement insertStmnt = connection.prepareStatement(sqlInsert );
81 | insertStmnt.setString(1, escapeSQL(msg.getTopic()));
82 | insertStmnt.setString(2, escapeSQL(msg.getPayload()));
83 | insertStmnt.execute();
84 | } catch (SQLException e) {
85 | logger.error("Error during the updating of the event", e);
86 | }
87 | }
88 |
89 | private void createTable() {
90 | try {
91 | Statement statement = connection.createStatement();
92 | statement.executeUpdate(sqlCreate);
93 | }catch(SQLException e) {
94 | logger.error("Error during the creation of the table", e);
95 | }
96 | }
97 |
98 | public List testQuery() throws SQLException {
99 | List output = new ArrayList<>();
100 | PreparedStatement ps = connection.prepareStatement("select id, a, b from data");
101 | ResultSet rs = ps.executeQuery();
102 | while(rs!=null && rs.next()) {
103 | String res = String.format("(%s,%s,%s)", rs.getInt(1), rs.getInt(2), rs.getInt(3));
104 | output.add(res);
105 | }
106 | return output;
107 | }
108 | }
109 |
110 |
--------------------------------------------------------------------------------
/src/main/java/com/iniesta/flink/connector/mysql/MysqlSink.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mysql;
2 |
3 | import java.util.Properties;
4 |
5 | import org.apache.flink.configuration.Configuration;
6 | import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
7 |
8 | import com.iniesta.flink.connector.mqtt.MqttMessage;
9 |
10 | public class MysqlSink extends RichSinkFunction {
11 |
12 | private MysqlDao mysqlDao;
13 |
14 | public MysqlSink(Properties props) {
15 | mysqlDao = new MysqlDao(props);
16 | }
17 |
18 | @Override
19 | public void invoke(MqttMessage msg) throws Exception {
20 | mysqlDao.process(msg);
21 | }
22 |
23 | @Override
24 | public void open(Configuration parameters) throws Exception {
25 | super.open(parameters);
26 | mysqlDao.open();
27 | }
28 |
29 | @Override
30 | public void close() throws Exception {
31 | super.close();
32 | mysqlDao.close();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/resources/create.sql:
--------------------------------------------------------------------------------
1 | create table if not exists messages(
2 | id int not null auto_increment primary key,
3 | topic varchar(255),
4 | payload varchar(10000),
5 | ts datetime
6 | )
--------------------------------------------------------------------------------
/src/test/java/com/iniesta/flink/connector/mqtt/BrokerPublisherManual.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import java.net.URISyntaxException;
4 | import java.util.Random;
5 | import java.util.concurrent.ExecutorService;
6 | import java.util.concurrent.Executors;
7 |
8 | import org.fusesource.mqtt.client.BlockingConnection;
9 | import org.fusesource.mqtt.client.MQTT;
10 | import org.fusesource.mqtt.client.Message;
11 | import org.fusesource.mqtt.client.QoS;
12 | import org.fusesource.mqtt.client.Topic;
13 |
14 | public class BrokerPublisherManual {
15 |
16 | public static void main(String[] args) throws Exception {
17 | Runnable runnable = new Runnable() {
18 |
19 | @Override
20 | public void run() {
21 | try {
22 | publish(1000);
23 | } catch (Exception e) {
24 | e.printStackTrace();
25 | }
26 | }
27 | };
28 | ExecutorService pool = Executors.newFixedThreadPool(3);
29 | for (int i = 0; i < 50; i++) {
30 | pool.submit(runnable);
31 | }
32 |
33 | }
34 |
35 |
36 |
37 | private static void publish(int num) throws URISyntaxException, Exception {
38 | MQTT mqtt = new MQTT();
39 | mqtt.setHost("cydonia", 1883);
40 |
41 | Random random = new Random();
42 | BlockingConnection blockingConnection = mqtt.blockingConnection();
43 |
44 | blockingConnection.connect();
45 | for (int i = 0; i < num; i++) {
46 | String payload = "Hello " + random.nextInt(10);
47 | blockingConnection.publish("/samples/in", payload.getBytes(), QoS.AT_LEAST_ONCE, false);
48 | }
49 |
50 | blockingConnection.disconnect();
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/test/java/com/iniesta/flink/connector/mqtt/DummyTest.java:
--------------------------------------------------------------------------------
1 | package com.iniesta.flink.connector.mqtt;
2 |
3 | import org.junit.Assert;
4 |
5 | public class DummyTest {
6 |
7 | public void test1() {
8 | Assert.assertTrue(true);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------