├── LICENSE
├── README.md
├── blobs_java_driver
├── .gitignore
├── LICENSE.txt
├── README.md
├── pom.xml
└── src
│ └── main
│ └── java
│ ├── CassandraImageStore.java
│ ├── FileSystemImageStore.java
│ └── LoadImage.java
└── spark_kafka_streaming
├── .gitignore
├── README.md
├── build.sbt
├── data_model
└── email_db.cql
└── streaming
└── src
└── main
└── scala
└── sparkKafkaDemo
├── Email.scala
└── StreamingDirectEmails.scala
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Code Samples
2 |
3 | Code samples from DataStax - Coming Soon!
4 |
5 | ## Support
6 |
7 | The code, examples, and snippets provided in this repository are not "Supported Software" under any DataStax subscriptions or other agreements.
8 |
9 | ## License
10 |
11 | Copyright 2013-2018, DataStax
12 |
13 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
14 |
15 | http://www.apache.org/licenses/LICENSE-2.0
16 |
17 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
18 |
--------------------------------------------------------------------------------
/blobs_java_driver/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
14 | .idea
15 | .project
16 | *.iml
17 |
--------------------------------------------------------------------------------
/blobs_java_driver/LICENSE.txt:
--------------------------------------------------------------------------------
1 | License
2 |
3 | Copyright 2014, DataStax
4 |
5 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 |
11 | This software is not "Supported Software" and, is not supported by DataStax under any software subscription or other agreement.
12 |
13 | See the License for the specific language governing permissions and limitations under the License.
--------------------------------------------------------------------------------
/blobs_java_driver/README.md:
--------------------------------------------------------------------------------
1 | You can use any code from this repository in verbatim or modified form as all examples in this repository are covered by the Apache License v2.0.
2 |
3 | But the code, examples, and snippets are not "Supported Software" under any DataStax subscriptions or other agreements.
--------------------------------------------------------------------------------
/blobs_java_driver/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.datastax
8 | blog_example
9 | 1.0-SNAPSHOT
10 |
11 |
12 | com.datastax.cassandra
13 | cassandra-driver-core
14 | 2.0.2
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/blobs_java_driver/src/main/java/CassandraImageStore.java:
--------------------------------------------------------------------------------
1 | import com.datastax.driver.core.Cluster;
2 | import com.datastax.driver.core.ResultSet;
3 | import com.datastax.driver.core.Row;
4 | import com.datastax.driver.core.Session;
5 |
6 | import java.nio.ByteBuffer;
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | /* Copyright 2014 DataStax
11 | *
12 | * Licensed under the Apache License, Version 2.0 (the "License");
13 | * you may not use this file except in compliance with the License.
14 | * You may obtain a copy of the License at
15 | *
16 | * http://www.apache.org/licenses/LICENSE-2.0
17 | *
18 | * Unless required by applicable law or agreed to in writing, software
19 | * distributed under the License is distributed on an "AS IS" BASIS,
20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 | * See the License for the specific language governing permissions and
22 | * limitations under the License.
23 | */
24 | public class CassandraImageStore {
25 | /* The code below is intended as a usage example for the blob datatype,
26 | * not as data modeling advice. Cassandra is not designed to be a file
27 | * store and is unlikely to work well as such.
28 | */
29 |
30 | private final Session session;
31 | private final Cluster cluster;
32 |
33 | public CassandraImageStore(){
34 | cluster = Cluster.builder()
35 | .addContactPoint("127.0.0.1")
36 | .build();
37 | session = cluster.connect("est");
38 | }
39 | public void storeImage(ByteBuffer fileBlob, String imageId){
40 | session.execute("INSERT INTO images ( image_id, image) values ( ?, ? )", imageId, fileBlob);
41 | }
42 |
43 | public ByteBuffer getImage(String imageId){
44 | ResultSet rows = session.execute("SELECT image FROM images WHERE image_id = ?", imageId);
45 | List buffers = new ArrayList();
46 | for(Row row: rows){
47 | buffers.add(row.getBytes("image"));
48 | }
49 | if(buffers.size() == 1){
50 | return buffers.get(0);
51 | }else if(buffers.size()>1){
52 | throw new RuntimeException("More than one matching image for id '" + imageId + "' found");
53 | }
54 | throw new RuntimeException("None matching images for id '" + imageId + "' found");
55 | }
56 |
57 | public void shutDown(){
58 | session.close();
59 | cluster.close();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/blobs_java_driver/src/main/java/FileSystemImageStore.java:
--------------------------------------------------------------------------------
1 | import java.io.IOException;
2 | import java.io.RandomAccessFile;
3 | import java.nio.ByteBuffer;
4 | import java.nio.channels.FileChannel;
5 |
6 | /* Copyright 2014 DataStax
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * 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 | public class FileSystemImageStore {
21 |
22 | public void write(String location, ByteBuffer blob) throws IOException {
23 |
24 | ByteBuffer buf = ByteBuffer.allocate(blob.limit());
25 | buf.clear();
26 | buf.put(blob);
27 | buf.flip();
28 |
29 | RandomAccessFile file = new RandomAccessFile(location, "rw");
30 | FileChannel channel = file.getChannel();
31 | try {
32 | while (buf.hasRemaining()) {
33 | channel.write(buf);
34 | }
35 | }finally {
36 | channel.force(true);
37 | channel.close();
38 | }
39 | }
40 |
41 | public ByteBuffer read(String location) throws IOException {
42 | RandomAccessFile file = new RandomAccessFile(location, "r");
43 | FileChannel channel = file.getChannel();
44 | ByteBuffer buf = ByteBuffer.allocate((int)channel.size());
45 |
46 | try {
47 | while(channel.read(buf) > 0 ) {
48 | buf.flip();
49 | buf.clear();
50 | }
51 | }finally{
52 | channel.force(true);
53 | channel.close();
54 | }
55 | return buf;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/blobs_java_driver/src/main/java/LoadImage.java:
--------------------------------------------------------------------------------
1 | import java.io.IOException;
2 | import java.nio.ByteBuffer;
3 |
4 | /* Copyright 2014 DataStax
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | public class LoadImage {
19 |
20 | public static void main(String[] args) throws ClassNotFoundException, IOException {
21 |
22 | CassandraImageStore cassandraImageStore = new CassandraImageStore();
23 | FileSystemImageStore fileSystemImageStore = new FileSystemImageStore();
24 | try {
25 | String userHome = System.getProperty("user.home");
26 | String file2 = userHome + "/deleteMe/1.png";
27 |
28 | ByteBuffer imageBytes = fileSystemImageStore.read(file2);
29 | cassandraImageStore.storeImage(imageBytes, "001");
30 | fileSystemImageStore.write(userHome + "/deleteMe/writeToFile.png", imageBytes);
31 |
32 | ByteBuffer byteBuffer = cassandraImageStore.getImage("001");
33 | fileSystemImageStore.write(userHome + "/deleteMe/001.png", byteBuffer);
34 |
35 | System.exit(0);
36 | }finally{
37 | cassandraImageStore.shutDown();
38 | }
39 | }
40 |
41 | }
--------------------------------------------------------------------------------
/spark_kafka_streaming/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
14 | .idea
15 | .project
16 | *.iml
17 |
--------------------------------------------------------------------------------
/spark_kafka_streaming/README.md:
--------------------------------------------------------------------------------
1 | # Spark Streaming with Kafka Direct API Demo
2 |
3 | This demo simulates a stream of email metadata. This example assumes the user has an existing Kafka cluster with email data formatted as "**msg_id::tenant_id::mailbox_id::time_delivered::time_forwarded::time_read::time_replied**".
4 | It is assumed these fields have the following datatypes:
5 |
6 | * msg_id: String
7 | * tenant_id: UUID
8 | * mailbox_id: UUID
9 | * time_delivered: Long
10 | * time_forwarded: Long
11 | * time_read: Long
12 | * time_replied: Long
13 |
14 | ### Setup the KS/Table
15 |
16 | **Note: You can change RF and compaction settings in this CQL script if needed.**
17 |
18 | `cqlsh -f data_model/email_db.cql`
19 |
20 | ### Run Spark Streaming
21 |
22 | ###### Build the streaming jar
23 | `sbt streaming/assembly`
24 |
25 | Parameters:
26 |
27 | 1. kafka broker: Ex. 10.200.185.103:9092
28 |
29 | 2. debug flag (limited use): Ex. true or false
30 |
31 | 3. checkpoint directory name: Ex. dsefs://[optional-ip-address]/emails_checkpoint
32 |
33 | 4. [spark.streaming.kafka.maxRatePerPartition](http://spark.apache.org/docs/latest/configuration.html#spark-streaming): Maximum rate (number of records per second)
34 |
35 | 5. batch interval (ms)
36 |
37 | 6. [auto.offset.reset](http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.streaming.kafka.KafkaUtils$): Ex. smallest or largest
38 |
39 | 7. topic name
40 |
41 | 8. kafka stream type: ex. direct or receiver
42 |
43 | 9. number of partitions to consume per topic (controls read parallelism) (receiver approach: you'll want to match whatever used when creating the topic)
44 |
45 | 10. processesing parallelism (controls write parallelism) (receiver approach: you'll want to match whatever used when creating the topic)
46 |
47 | 11. group.id that id's the consumer processes (receiver approach: you'll want to match whatever used when creating the topic)
48 |
49 | 12. zookeeper connect string (e.g localhost:2181) (receiver approach: you'll want to match whatever used when creating the topic)
50 |
51 | ###### Running on a server in foreground
52 | `dse spark-submit --driver-memory 2G --class sparkKafkaDemo.StreamingDirectEmails streaming/target/scala-2.10/streaming-assembly-0.1.jar :9092 true dsefs://[optional-ip-address]/emails_checkpoint 50000 5000 smallest emails direct 1 100 test-consumer-group localhost:2181`
53 |
54 | ## Support
55 |
56 | The code, examples, and snippets provided in this repository are not "Supported Software" under any DataStax subscriptions or other agreements.
57 |
58 | ## License
59 |
60 | Copyright 2016, DataStax
61 |
62 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
63 |
64 | http://www.apache.org/licenses/LICENSE-2.0
65 |
66 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
--------------------------------------------------------------------------------
/spark_kafka_streaming/build.sbt:
--------------------------------------------------------------------------------
1 | val DSE_HOME = sys.env.getOrElse("DSE_HOME", sys.env("HOME")+"dse")
2 | val sparkClasspathStr = s"dse spark-classpath".!!.trim
3 | val sparkClasspathArr = sparkClasspathStr.split(':')
4 |
5 | val dseScalaVersionStr = Seq("/bin/sh", "-c", s"ls ${DSE_HOME}/resources/spark/lib/scala-compiler*jar").!!.trim
6 | val dseScalaVersionArr = dseScalaVersionStr.split("-").last.split(".jar")(0).split('.')
7 | val dseScalaVersion = dseScalaVersionArr.mkString(".")
8 | val dseScalaMajorMinorVersion = Seq(dseScalaVersionArr(0), dseScalaVersionArr(1)).mkString(".")
9 |
10 | val DSE_BIN = s"$DSE_HOME/bin/dse"
11 | val dseVersionArr = s"$DSE_BIN -v".!!.trim.split('.')
12 | val dseVersion = Seq(dseVersionArr(0), dseVersionArr(1)).mkString(".")
13 |
14 | // This needs to match whatever Spark version being used in DSE
15 | val sparkVersionStr = Seq("/bin/sh", "-c", s"ls ${DSE_HOME}/resources/spark/lib/spark-core_*jar").!!.trim
16 | val sparkVersionArr = sparkVersionStr.split('-')(2).split('.') // expected: spark-core_2.11-2.0.0.1-2cf48f7.jar
17 | val sparkVersion = Seq(sparkVersionArr(0), sparkVersionArr(1), sparkVersionArr(2)).mkString(".")
18 | val kafkaVersion = "0.8.2.1" // we'll want to generalize this once spark officially supports newer versions
19 | val kafkaMajorVersion = kafkaVersion.split('.')(0)
20 | val kafkaMinorVersion = kafkaVersion.split('.')(1)
21 | val scalaTestVersion = "2.2.4"
22 | val jodaVersion = "2.9"
23 |
24 | val sparkStreamingKafkaDep: String = {
25 | if (dseVersion.toDouble >= 5.1) {
26 | s"spark-streaming-kafka-${kafkaMajorVersion}-${kafkaMinorVersion}"
27 | } else {
28 | "spark-streaming-kafka"
29 | }
30 | }
31 |
32 | // Find all Jars on dse spark-classpath
33 | val sparkClasspath = {
34 | for ( dseJar <- sparkClasspathArr if dseJar.endsWith("jar"))
35 | yield Attributed.blank(file(dseJar))
36 | }.toSeq
37 |
38 | val globalSettings = Seq(
39 | version := "0.1",
40 | scalaVersion := dseScalaVersion
41 | )
42 |
43 | lazy val streaming = (project in file("streaming"))
44 | .settings(name := "streaming")
45 | .settings(globalSettings:_*)
46 | .settings(libraryDependencies ++= streamingDeps)
47 |
48 | val akkaVersion = "2.3.11"
49 |
50 | // Do not define in streaming deps if we reference them in existing DSE libs
51 | lazy val streamingDeps = Seq(
52 | "joda-time" % "joda-time" % jodaVersion % "provided",
53 | "org.apache.spark" %% "spark-mllib" % sparkVersion % "provided",
54 | "org.apache.spark" %% "spark-graphx" % sparkVersion % "provided",
55 | "org.apache.spark" %% "spark-sql" % sparkVersion % "provided",
56 | "org.apache.spark" %% "spark-streaming" % sparkVersion % "provided",
57 | "org.apache.spark" %% sparkStreamingKafkaDep % sparkVersion exclude("org.spark-project.spark", "unused"),
58 | "com.databricks" %% "spark-csv" % "1.2.0"
59 | )
60 |
61 | lazy val printenv = taskKey[Unit]("Prints classpaths and dependencies")
62 | val env = Map("DSE_HOME" -> DSE_HOME,
63 | "dseScalaVersion" -> dseScalaVersion,
64 | "dseVersion" -> dseVersion,
65 | "sparkClasspath" -> sparkClasspath)
66 |
67 | printenv := println(env)
68 |
69 | //Add dse jars to classpath
70 | unmanagedJars in Compile ++= sparkClasspath
71 | unmanagedJars in Test ++= sparkClasspath
72 |
--------------------------------------------------------------------------------
/spark_kafka_streaming/data_model/email_db.cql:
--------------------------------------------------------------------------------
1 | CREATE KEYSPACE IF NOT EXISTS email_db WITH replication = {'class':'NetworkTopologyStrategy', 'Analytics':1};
2 |
3 | CREATE TABLE IF NOT EXISTS email_db.email_msg_tracker (
4 | msg_id text,
5 | tenant_id uuid,
6 | mailbox_id uuid,
7 | time_delivered timestamp,
8 | time_forwarded timestamp,
9 | time_read timestamp,
10 | time_replied timestamp,
11 | PRIMARY KEY ((msg_id, tenant_id), mailbox_id)
12 | ) WITH CLUSTERING ORDER BY (mailbox_id ASC);
13 |
--------------------------------------------------------------------------------
/spark_kafka_streaming/streaming/src/main/scala/sparkKafkaDemo/Email.scala:
--------------------------------------------------------------------------------
1 | package sparkKafkaDemo
2 |
3 | import java.util.UUID
4 | import org.joda.time.DateTime
5 |
6 | case class Email(
7 | msg_id: String,
8 | tenant_id: String,
9 | mailbox_id: String,
10 | time_delivered: Long,
11 | time_forwarded: Long,
12 | time_read: Long,
13 | time_replied: Long
14 | )
15 |
--------------------------------------------------------------------------------
/spark_kafka_streaming/streaming/src/main/scala/sparkKafkaDemo/StreamingDirectEmails.scala:
--------------------------------------------------------------------------------
1 | package sparkKafkaDemo
2 |
3 | import java.util.UUID
4 | import scala.sys
5 | import kafka.serializer.StringDecoder
6 | import org.apache.hadoop.conf.Configuration
7 | import org.apache.spark.storage.StorageLevel
8 | import org.apache.spark.deploy.SparkHadoopUtil
9 | import org.apache.spark.{SparkConf, SparkContext}
10 | import org.apache.spark.rdd.RDD
11 | import org.apache.spark.sql.{SQLContext, SaveMode}
12 | import org.apache.spark.streaming.kafka.{KafkaUtils,OffsetRange,HasOffsetRanges}
13 | import org.apache.spark.streaming.{Milliseconds, StreamingContext, Time}
14 | import org.joda.time.DateTime
15 |
16 | /** This uses the Kafka Direct API introduced in Spark 1.4
17 | *
18 | */
19 | object StreamingDirectEmails {
20 |
21 | def main(args: Array[String]) {
22 |
23 | if (args.length < 3) {
24 | println("1st paramteter is kafka broker ")
25 | println("2nd param whether to display debug output (true|false) ")
26 | println("3rd param is the checkpoint path ")
27 | println("4th param is the maxRatePerPartition (records/sec to read from each kafka partition) ")
28 | println("5th param is the batch interval in milliseconds")
29 | println("6th param is the auto.offset.reset type (smallest|largest)")
30 | println("7th param is the topic name")
31 | println("8th param is the type of kafka stream (direct|receiver)")
32 | println("9th param is the number of partitions to consume per topic (used with receiver-based input stream)")
33 | println("10th param is the amount of parallelism used for processing data (used with receiver-based input stream)")
34 | println("11th param is the group.id that id's the consumer processes (used with receiver-based input stream)")
35 | println("12th param is the zookeeper connect string (e.g. localhost:2181) (used with receiver-based input stream)")
36 | }
37 |
38 | val brokers = args(0)
39 | val debugOutput = args(1).toBoolean
40 | val checkpoint_path = args(2)
41 | val maxRatePerPartition = args(3)
42 | val batchIntervalInMillis = args(4).toInt
43 | val offsetResetType = args(5)
44 | val topicName = args(6)
45 | val streamType = args(7)
46 | val numPartitions = args(8).toInt
47 | val processingParallelism = args(9).toInt
48 | val groupId = args(10)
49 | val zookeeper = args(11)
50 | val storageLevel = StorageLevel.MEMORY_AND_DISK_SER
51 | val conf = new SparkConf()
52 | .set("spark.streaming.kafka.maxRatePerPartition", maxRatePerPartition)
53 | .set("spark.locality.wait", "0")
54 | .set("spark.cassandra.connection.keep_alive_ms", (batchIntervalInMillis*5).toString)
55 |
56 | if (checkpoint_path == "dont_checkpoint") {
57 | conf.set("spark.streaming.receiver.writeAheadLog.enable", "false")
58 | } else {
59 | conf.set("spark.streaming.receiver.writeAheadLog.enable", "true")
60 | }
61 |
62 | val sc = SparkContext.getOrCreate(conf)
63 |
64 | def createStreamingContext(): StreamingContext = {
65 | // Create a new StreamingContext
66 | val newSsc = new StreamingContext(sc, Milliseconds(batchIntervalInMillis))
67 |
68 | if (checkpoint_path == "dont_checkpoint") {
69 | println("dont_checkpoint was provided in checkpoint path, so we're not checkpointing.")
70 | } else {
71 | println(s"Creating new StreamingContext $newSsc with checkpoint path of: $checkpoint_path")
72 | newSsc.checkpoint(checkpoint_path)
73 | }
74 |
75 | // Setup Kafka params
76 | val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers,
77 | "auto.offset.reset"-> offsetResetType,
78 | "group.id"->groupId,
79 | "zookeeper.connect"->zookeeper)
80 |
81 | println(s"connecting to brokers: $brokers")
82 | println(s"kafkaParams: $kafkaParams")
83 |
84 | // Create the input stream
85 | val emailsStream = {
86 | if (streamType == "direct") {
87 | val topics = Set(topicName)
88 | KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](newSsc, kafkaParams, topics)
89 |
90 | } else if (streamType == "receiver") {
91 | // Changing this number controls the number of consumer threads per input DStream
92 | val topics = Map(topicName -> 1)
93 |
94 | // Controls the number of input dstreams
95 | val streams = (1 to numPartitions) map { _ =>
96 | KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](newSsc, kafkaParams, topics, storageLevel)
97 | }
98 |
99 | // Below is way to change parallelism for downstream processing, for now we'll stick with numPartitions
100 | val unifiedStream = newSsc.union(streams)
101 | unifiedStream.repartition(processingParallelism)
102 |
103 | } else {
104 | println(s"The streaming type provided is NOT supported: $streamType")
105 | sys.exit()
106 | }
107 | }
108 |
109 | emailsStream.foreachRDD {
110 | (message: RDD[(String, String)], batchTime: Time) => {
111 | var offsetRanges = Array[OffsetRange]()
112 |
113 | if (streamType == "direct") {
114 | offsetRanges = message.asInstanceOf[HasOffsetRanges].offsetRanges
115 | for (o <- offsetRanges) {
116 | println(s"\nTopic: ${o.topic} Partition: ${o.partition} FromOffset: ${o.fromOffset} UntilOffset: ${o.untilOffset}")
117 | }
118 | }
119 |
120 | // Needs to be here: We have to create a SQLContext using the SparkContext that the StreamingContext is using.
121 | // We need to lazily instantiate a singelton instance of the SQLContext in order to recover from a checkpoint.
122 | val sqlContext = SQLContext.getOrCreate(message.sparkContext)
123 | import sqlContext.implicits._
124 |
125 | // Convert each RDD from the batch into a Email DataFrame
126 | // email data has the format msg_id:tenant_id:mailbox_id:time_delivered:time_forwarded:time_read:time_replied
127 | val df = message.map {
128 | case (key, nxtEmail) => nxtEmail.split("::")
129 | }.map(email => {
130 | val time_delivered: Long = email(3).trim.toLong
131 | val time_forwarded: Long = email(4).trim.toLong
132 | val time_read: Long = email(5).trim.toLong
133 | val time_replied: Long = email(6).trim.toLong
134 | Email(email(0).trim.toString, email(1).trim.toString, email(2).trim.toString, time_delivered, time_forwarded, time_read, time_replied)
135 | }).toDF("msg_id", "tenant_id", "mailbox_id", "time_delivered", "time_forwarded", "time_read", "time_replied")
136 |
137 | // Save the DataFrame to Cassandra
138 | // Note: Cassandra has been initialized through dse spark-submit, so we don't have to explicitly set the connection
139 | df.write.format("org.apache.spark.sql.cassandra")
140 | .mode(SaveMode.Append)
141 | .options(Map("keyspace" -> "email_db", "table" -> "email_msg_tracker"))
142 | .save()
143 |
144 | if (debugOutput) {
145 | val count = df.count()
146 | println(s"Successfully saved $count")
147 | df.show()
148 | }
149 | }
150 | }
151 | newSsc
152 | }
153 |
154 | val ssc = StreamingContext.getActiveOrCreate(checkpoint_path, createStreamingContext)
155 |
156 | ssc.start()
157 | ssc.awaitTermination()
158 | }
159 | }
160 |
--------------------------------------------------------------------------------