|
| 1 | +/* |
| 2 | + * Copyright 2015 Imply Data, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.imply.wikiticker |
| 18 | + |
| 19 | +import java.io.File |
| 20 | +import java.io.FileOutputStream |
| 21 | +import java.io.PrintStream |
| 22 | +import java.util.Properties |
| 23 | +import org.apache.kafka.clients.producer.KafkaProducer |
| 24 | +import org.apache.kafka.clients.producer.ProducerRecord |
| 25 | +import org.apache.kafka.common.serialization.StringSerializer |
| 26 | + |
| 27 | +sealed trait Writer |
| 28 | +{ |
| 29 | + def write(data: String): Unit |
| 30 | + |
| 31 | + def shutdown(): Unit |
| 32 | +} |
| 33 | + |
| 34 | +class ConsoleWriter extends Writer |
| 35 | +{ |
| 36 | + override def write(data: String): Unit = { |
| 37 | + System.out.println(data) |
| 38 | + } |
| 39 | + |
| 40 | + override def shutdown(): Unit = {} |
| 41 | +} |
| 42 | + |
| 43 | +class FileWriter(fileName: String) extends Writer |
| 44 | +{ |
| 45 | + private val outStream = new PrintStream(new FileOutputStream(new File(fileName))) |
| 46 | + |
| 47 | + override def write(data: String): Unit = { |
| 48 | + outStream.println(data) |
| 49 | + } |
| 50 | + |
| 51 | + override def shutdown(): Unit = { |
| 52 | + outStream.close() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +class KafkaWriter(brokers: String, topic: String) extends Writer |
| 57 | +{ |
| 58 | + private val props = new Properties() |
| 59 | + props.put("bootstrap.servers", brokers) |
| 60 | + props.put("acks", "all") |
| 61 | + props.put("retries", "3") |
| 62 | + |
| 63 | + private val producer = new KafkaProducer[String, String](props, new StringSerializer(), new StringSerializer()) |
| 64 | + |
| 65 | + override def write(data: String): Unit = { |
| 66 | + producer.send(new ProducerRecord[String, String](topic, data)).get() |
| 67 | + } |
| 68 | + |
| 69 | + override def shutdown(): Unit = { |
| 70 | + producer.close() |
| 71 | + } |
| 72 | +} |
0 commit comments