├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── Vagrantfile ├── kafka-http.yml ├── pom.xml ├── run.sh ├── src └── ly │ └── stealth │ └── kafkahttp │ ├── KafkaApplication.java │ ├── KafkaConfiguration.java │ └── MessageResource.java ├── start.sh ├── stop.sh └── vagrant ├── broker.sh ├── kafka.sh └── zk.sh /.gitignore: -------------------------------------------------------------------------------- 1 | logs 2 | .vagrant 3 | *.class 4 | *.log 5 | *.idea 6 | *.iml 7 | 8 | # sbt specific 9 | dist/* 10 | target/ 11 | lib_managed/ 12 | src_managed/ 13 | project/boot/ 14 | project/plugins/project/ 15 | 16 | # Scala-IDE specific 17 | .scala_dependencies 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:trusty 2 | MAINTAINER josh 3 | 4 | RUN apt-get update && apt-get -y install python-software-properties software-properties-common 5 | RUN add-apt-repository "deb http://gb.archive.ubuntu.com/ubuntu $(lsb_release -sc) universe" 6 | RUN apt-get update 7 | 8 | RUN add-apt-repository ppa:saiarcot895/myppa 9 | RUN apt-get update 10 | RUN apt-get -y install apt-fast 11 | 12 | RUN apt-fast -y install git 13 | 14 | RUN add-apt-repository ppa:webupd8team/java 15 | RUN apt-get update 16 | RUN echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | \ 17 | /usr/bin/debconf-set-selections 18 | RUN apt-fast install -y oracle-java8-installer 19 | RUN apt-fast install -y oracle-java8-set-default 20 | 21 | 22 | ENV MAVEN_VERSION 3.2.2 23 | ADD https://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz /tmp/apache-maven-$MAVEN_VERSION-bin.tar.gz 24 | RUN tar xfz /tmp/apache-maven-$MAVEN_VERSION-bin.tar.gz -C /opt 25 | 26 | ENV PATH /opt/apache-maven-$MAVEN_VERSION/bin:$PATH 27 | 28 | RUN cd /tmp && git clone https://github.com/joshjdevl/dropwizard-kafka-http 29 | RUN cd /tmp/dropwizard-kafka-http && mvn clean install && mvn package 30 | 31 | CMD cd /tmp/dropwizard-kafka-http && java -jar target/dropwizard-kafka-http-0.0.1-SNAPSHOT.jar server kafka-http.yml 32 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dropwizard-kafka-http 2 | 3 | This project creates an Apache Kafka HTTP endpoint for producing and consuming 4 | messages. It is built on [the Dropwizard framework] that makes Java REST 5 | services operator-friendly and easy to deploy. 6 | 7 | ## Running in Development with Vagrant 8 | 9 | A `Vagrantfile` is included in the project to quickly get up and running with 10 | virtual machines to run ZooKeeper, Kafka, and the HTTP endpoint. 11 | 12 | 1. Install Vagrant 13 | 2. Install Virtual Box 14 | 3. `git clone https://github.com/stealthly/dropwizard-kafka-http` 15 | 4. `cd dropwizard-kafka-http` 16 | 5. `vagrant up` 17 | 6. `curl -d "topic=http&message=hello&key=0" "http://192.168.22.10:8080/message"` 18 | 7. `curl "http://192.168.22.10:8080/message?topic=http"` 19 | 20 | Your original message produced from the consumer: 21 | 22 | [{"topic":"http","key":"0","message":"hello","partition":0,"offset":0}] 23 | 24 | * Zookeeper will be running on 192.168.22.5 25 | * dropwizard-kafka-http is built cleanly before Zookeeper installs in `vagrant/zk.sh` 26 | * Kafka Broker One is running on 192.168.22.10 27 | * dropwizard-kafka-http launches on 192.168.22.10 after the Kafka Broker starts in `vagrant/broker.sh` 28 | 29 | If you want you can log in to the machines using `vagrant ssh zookeeper` and `vagrant ssh brokerOne`. 30 | 31 | ## Running in Your Own Environments 32 | 33 | For deployment, you'll need to build the project with Maven. Dropwizard projects 34 | produce "fat jars" so that you'll get a standalone binary ready to distribute 35 | and run with your production Java runtime. Assuming that ZooKeeper and Kafka are 36 | already running, edit the included `kafka-http.yml` to reflect the appropriate 37 | addresses for the HTTP endpoint to connect to these services. 38 | 39 | Then, use the [standard `server` Dropwizard command][dw server] to start up the 40 | HTTP server on port 8080, passing the config file as argument: 41 | 42 | $ mvn package 43 | $ java -jar target/dropwizard-kafka-http-0.0.1-SNAPSHOT.jar server kafka-http.yml 44 | $ curl -d "topic=http&message=hello&key=0" http://localhost:8080/message 45 | $ curl "http://localhost:8080/message?topic=http" 46 | 47 | You will also find an operator's interface with metrics and other info on port 48 | 8081. 49 | 50 | It is recommended that you run the process under your preferred init or service 51 | supervision tool. See [the Dropwizard configuration reference] for extensive 52 | customization options for the HTTP server, logging, etc. 53 | 54 | ## dropwizard-kafka-http api methods 55 | 56 | ### Produce messages 57 | ``` 58 | POST /message 59 | 60 | topic=$topic 61 | 62 | message=$message0 63 | key=$key0 64 | 65 | message=$message1 66 | key=$key1, ... etc 67 | 68 | Produces messages on topic. 69 | 70 | Parameters: 71 | topic - required topic name 72 | key - optional key text. Multiple values are possible 73 | message - required message text. Multiple values are possible 74 | 75 | Note: if keys are passed, then passed keys count should match messages count. 76 | 77 | Errors: 78 | 400 - wrong parameters passed 79 | ``` 80 | 81 | ### Consume messages 82 | ``` 83 | GET /message?topic=$topic&timeout=$timeout 84 | Returns consumed messages available on topic. 85 | 86 | Parameters: 87 | topic - required topic name 88 | timeout - optional timeout in ms 89 | 90 | Errors: 91 | 400 - wrong parameters passed 92 | ``` 93 | 94 | [the Dropwizard framework]: http://dropwizard.github.io/dropwizard/ 95 | [dw server]: http://dropwizard.github.io/dropwizard/getting-started.html#running-your-application 96 | [the Dropwizard configuration reference]: http://dropwizard.github.io/dropwizard/manual/configuration.html 97 | 98 | -------------------------------------------------------------------------------- /Vagrantfile: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | # -*- mode: ruby -*- 16 | # vi: set ft=ruby : 17 | 18 | # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! 19 | VAGRANTFILE_API_VERSION = "2" 20 | 21 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 22 | config.vm.box = "precise64" 23 | 24 | # The url from where the 'config.vm.box' box will be fetched if it 25 | # doesn't already exist on the user's system. 26 | config.vm.box_url = "http://files.vagrantup.com/precise64.box" 27 | 28 | config.vm.define "zookeeper" do |zookeeper| 29 | zookeeper.vm.network :private_network, ip: "192.168.22.5" 30 | zookeeper.vm.provider :virtualbox do |vb| 31 | vb.customize ["modifyvm", :id, "--memory", "1024"] 32 | end 33 | zookeeper.vm.provision "shell", path: "vagrant/zk.sh" 34 | end 35 | 36 | config.vm.define "brokerOne" do |brokerOne| 37 | brokerOne.vm.network :private_network, ip: "192.168.22.10" 38 | brokerOne.vm.provider :virtualbox do |vb| 39 | vb.customize ["modifyvm", :id, "--memory", "1024"] 40 | end 41 | brokerOne.vm.provision "shell", path: "vagrant/broker.sh", :args => "1" 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /kafka-http.yml: -------------------------------------------------------------------------------- 1 | producer: 2 | "bootstrap.servers": "192.168.22.10:9092" 3 | "key.serializer": "org.apache.kafka.common.serialization.ByteArraySerializer" 4 | "value.serializer": "org.apache.kafka.common.serialization.ByteArraySerializer" 5 | 6 | consumer: 7 | "zookeeper.connect": "192.168.22.5:2181" 8 | "group.id": "group" 9 | "auto.offset.reset": "smallest" 10 | "consumer.timeout.ms": "500" 11 | 12 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | ly.stealth 6 | dropwizard-kafka-http 7 | 0.0.1-SNAPSHOT 8 | 9 | 10 | 11 | io.dropwizard 12 | dropwizard-core 13 | 0.7.1 14 | 15 | 16 | 17 | org.apache.kafka 18 | kafka_2.10 19 | 0.8.2.0 20 | 21 | 22 | 23 | org.slf4j 24 | slf4j-log4j12 25 | 26 | 27 | 28 | 29 | 30 | 31 | UTF-8 32 | UTF-8 33 | 34 | 35 | 36 | src 37 | 38 | 39 | org.apache.maven.plugins 40 | maven-compiler-plugin 41 | 3.1 42 | 43 | 1.7 44 | 1.7 45 | UTF-8 46 | 47 | 48 | 49 | 50 | org.apache.maven.plugins 51 | maven-shade-plugin 52 | 1.6 53 | 54 | true 55 | 56 | 57 | *:* 58 | 59 | META-INF/*.SF 60 | META-INF/*.DSA 61 | META-INF/*.RSA 62 | 63 | 64 | 65 | 66 | 67 | 68 | package 69 | 70 | shade 71 | 72 | 73 | 74 | 75 | 76 | ly.stealth.kafkahttp.KafkaApplication 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | org.apache.maven.plugins 86 | maven-jar-plugin 87 | 2.3.2 88 | 89 | 90 | 91 | true 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | java -jar target/dropwizard-kafka-http-0.0.1-SNAPSHOT.jar server kafka-http.yml 2 | -------------------------------------------------------------------------------- /src/ly/stealth/kafkahttp/KafkaApplication.java: -------------------------------------------------------------------------------- 1 | package ly.stealth.kafkahttp; 2 | 3 | import com.codahale.metrics.health.HealthCheck; 4 | import io.dropwizard.Application; 5 | import io.dropwizard.lifecycle.Managed; 6 | import io.dropwizard.setup.Bootstrap; 7 | import io.dropwizard.setup.Environment; 8 | import org.apache.kafka.clients.producer.KafkaProducer; 9 | 10 | public class KafkaApplication extends Application implements Managed { 11 | public static void main(String[] args) throws Exception { 12 | new KafkaApplication().run(args); 13 | } 14 | 15 | private KafkaProducer producer; 16 | 17 | @Override 18 | public String getName() { return "kafka-http"; } 19 | 20 | @Override 21 | public void initialize(Bootstrap bootstrap) {} 22 | 23 | @Override 24 | public void run(KafkaConfiguration configuration, Environment environment) { 25 | producer = new KafkaProducer(configuration.producer); 26 | environment.jersey().register(new MessageResource(producer, configuration.consumer)); 27 | environment.healthChecks().register("empty", new EmptyHealthCheck()); 28 | } 29 | 30 | @Override 31 | public void start() throws Exception {} 32 | 33 | @Override 34 | public void stop() throws Exception { 35 | producer.close(); 36 | } 37 | 38 | private static class EmptyHealthCheck extends HealthCheck { 39 | @Override 40 | protected Result check() throws Exception { 41 | return Result.healthy(); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/ly/stealth/kafkahttp/KafkaConfiguration.java: -------------------------------------------------------------------------------- 1 | package ly.stealth.kafkahttp; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.core.JsonToken; 5 | import com.fasterxml.jackson.databind.DeserializationContext; 6 | import com.fasterxml.jackson.databind.JsonDeserializer; 7 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 8 | import io.dropwizard.Configuration; 9 | 10 | import java.io.IOException; 11 | import java.util.Properties; 12 | 13 | public class KafkaConfiguration extends Configuration { 14 | @JsonDeserialize(using = PropertiesDeserializer.class) 15 | public Properties producer = new Properties(); 16 | 17 | @JsonDeserialize(using = PropertiesDeserializer.class) 18 | public Properties consumer = new Properties(); 19 | 20 | public static class PropertiesDeserializer extends JsonDeserializer { 21 | @Override 22 | public Properties deserialize(JsonParser jp, DeserializationContext context) throws IOException { 23 | Properties props = new Properties(); 24 | if (!jp.hasCurrentToken() || jp.getCurrentToken() != JsonToken.START_OBJECT) 25 | return props; 26 | 27 | String name = null; 28 | for (JsonToken token = jp.nextToken(); token != JsonToken.END_OBJECT; token = jp.nextToken()) { 29 | switch (token) { 30 | case FIELD_NAME: name = jp.getCurrentName(); break; 31 | case VALUE_STRING: 32 | String value = jp.getValueAsString(); 33 | props.setProperty(name, value); break; 34 | default: 35 | throw new UnsupportedOperationException("Unsupported configuration item " + token + ". Only string values are supported"); 36 | } 37 | } 38 | 39 | return props; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/ly/stealth/kafkahttp/MessageResource.java: -------------------------------------------------------------------------------- 1 | package ly.stealth.kafkahttp; 2 | 3 | import com.codahale.metrics.annotation.Timed; 4 | import com.fasterxml.jackson.annotation.JsonInclude; 5 | import com.google.common.base.Strings; 6 | import kafka.consumer.Consumer; 7 | import kafka.consumer.ConsumerConfig; 8 | import kafka.consumer.ConsumerTimeoutException; 9 | import kafka.consumer.KafkaStream; 10 | import kafka.javaapi.consumer.ConsumerConnector; 11 | import kafka.message.MessageAndMetadata; 12 | import org.apache.kafka.clients.producer.KafkaProducer; 13 | import org.apache.kafka.clients.producer.ProducerRecord; 14 | 15 | import javax.ws.rs.*; 16 | import javax.ws.rs.core.MediaType; 17 | import javax.ws.rs.core.Response; 18 | import java.nio.charset.Charset; 19 | import java.util.*; 20 | 21 | @Path("/message") 22 | @Produces(MediaType.APPLICATION_JSON) 23 | public class MessageResource { 24 | private KafkaProducer producer; 25 | private Properties consumerCfg; 26 | 27 | public MessageResource(KafkaProducer producer, Properties consumerCfg) { 28 | this.producer = producer; 29 | this.consumerCfg = consumerCfg; 30 | } 31 | 32 | @POST 33 | @Timed 34 | public Response produce( 35 | @FormParam("topic") String topic, 36 | @FormParam("key") List keys, 37 | @FormParam("message") List messages 38 | ) { 39 | List errors = new ArrayList<>(); 40 | if (Strings.isNullOrEmpty(topic)) errors.add("Undefined topic"); 41 | 42 | if (messages.isEmpty()) errors.add("Undefined message"); 43 | if (!keys.isEmpty() && keys.size() != messages.size()) errors.add("Messages count != keys count"); 44 | 45 | if (!errors.isEmpty()) 46 | return Response.status(400) 47 | .entity(errors) 48 | .build(); 49 | 50 | Charset charset = Charset.forName("utf-8"); 51 | for (int i = 0; i < messages.size(); i++) { 52 | String key = keys.isEmpty() ? null : keys.get(i); 53 | String message = messages.get(i); 54 | producer.send(new ProducerRecord(topic, key != null ? key.getBytes(charset) : null, message.getBytes(charset))); 55 | } 56 | 57 | return Response.ok().build(); 58 | } 59 | 60 | @GET 61 | @Timed 62 | public Response consume( 63 | @QueryParam("topic") String topic, 64 | @QueryParam("timeout") Integer timeout 65 | ) { 66 | if (Strings.isNullOrEmpty(topic)) 67 | return Response.status(400) 68 | .entity(new String[]{"Undefined topic"}) 69 | .build(); 70 | 71 | Properties props = (Properties) consumerCfg.clone(); 72 | if (timeout != null) props.put("consumer.timeout.ms", "" + timeout); 73 | 74 | ConsumerConfig config = new ConsumerConfig(props); 75 | ConsumerConnector connector = Consumer.createJavaConsumerConnector(config); 76 | 77 | Map streamCounts = Collections.singletonMap(topic, 1); 78 | Map>> streams = connector.createMessageStreams(streamCounts); 79 | KafkaStream stream = streams.get(topic).get(0); 80 | 81 | List messages = new ArrayList<>(); 82 | try { 83 | for (MessageAndMetadata messageAndMetadata : stream) 84 | messages.add(new Message(messageAndMetadata)); 85 | } catch (ConsumerTimeoutException ignore) { 86 | } finally { 87 | connector.commitOffsets(); 88 | connector.shutdown(); 89 | } 90 | 91 | return Response.ok(messages).build(); 92 | } 93 | 94 | public static class Message { 95 | public String topic; 96 | 97 | @JsonInclude(JsonInclude.Include.NON_NULL) 98 | public String key; 99 | public String message; 100 | 101 | public int partition; 102 | public long offset; 103 | 104 | public Message(MessageAndMetadata message) { 105 | this.topic = message.topic(); 106 | 107 | this.key = message.key() != null ? new String(message.key(), Charset.forName("utf-8")) : null; 108 | this.message = new String(message.message(), Charset.forName("utf-8")); 109 | 110 | this.partition = message.partition(); 111 | this.offset = message.offset(); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | nohup ./run.sh > dropwizard.out 2>&1& 2 | echo $! > dropwizard.pid 3 | -------------------------------------------------------------------------------- /stop.sh: -------------------------------------------------------------------------------- 1 | kill -9 `cat dropwizard.pid` 2 | 3 | tokill=`ps -ef | grep java | grep 'kafka-http.yml' | awk '{print $2}'` 4 | kill -9 $tokill 5 | -------------------------------------------------------------------------------- /vagrant/broker.sh: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | #!/bin/sh -Eux 17 | 18 | # Trap non-normal exit signals: 1/HUP, 2/INT, 3/QUIT, 15/TERM, ERR 19 | trap founderror 1 2 3 15 ERR 20 | 21 | founderror() 22 | { 23 | exit 1 24 | } 25 | 26 | exitscript() 27 | { 28 | #remove lock file 29 | #rm $lockfile 30 | exit 0 31 | } 32 | 33 | apt-get -y update 34 | apt-get install -y software-properties-common python-software-properties screen vim git wget 35 | add-apt-repository -y ppa:webupd8team/java 36 | apt-get -y update 37 | /bin/echo debconf shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections 38 | apt-get -y install oracle-java7-installer oracle-java7-set-default 39 | 40 | /vagrant/vagrant/kafka.sh #install kafka 41 | 42 | IP=$(ifconfig | grep 'inet addr:'| grep 168 | grep 192|cut -d: -f2 | awk '{ print $1}') 43 | sed 's/broker.id=0/'broker.id=$1'/' /opt/apache/kafka/config/server.properties > /tmp/prop1.tmp 44 | sed 's/#advertised.host.name=/'advertised.host.name=$IP'/' /tmp/prop1.tmp > /tmp/prop2.tmp 45 | sed 's/#host.name=localhost/'host.name=$IP'/' /tmp/prop2.tmp > /tmp/prop3.tmp 46 | sed 's/zookeeper.connect=localhost:2181/'zookeeper.connect=192.168.22.5:2181'/' /tmp/prop3.tmp > /opt/server.properties 47 | 48 | /opt/apache/kafka/bin/kafka-server-start.sh /opt/server.properties 1>> /tmp/broker.log 2>> /tmp/broker.log & 49 | 50 | sleep 10 51 | 52 | cd /vagrant 53 | mkdir -p log 54 | java -jar /vagrant/target/dropwizard-kafka-http-0.0.1-SNAPSHOT.jar server kafka-http.yml 1>> /vagrant/log/stealthly.log 2>> /vagrant/log/stealthly.log & 55 | -------------------------------------------------------------------------------- /vagrant/kafka.sh: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | #!/bin/sh -Eux 17 | 18 | # Trap non-normal exit signals: 1/HUP, 2/INT, 3/QUIT, 15/TERM, ERR 19 | trap founderror 1 2 3 15 ERR 20 | 21 | founderror() 22 | { 23 | exit 1 24 | } 25 | 26 | exitscript() 27 | { 28 | #remove lock file 29 | #rm $lockfile 30 | exit 0 31 | } 32 | 33 | cd /tmp 34 | wget https://archive.apache.org/dist/kafka/0.8.2-beta/kafka_2.10-0.8.2-beta.tgz 35 | tar -xvf kafka_2.10-0.8.2-beta.tgz 36 | mkdir -p /opt/apache 37 | mv kafka_2.10-0.8.2-beta /opt/apache 38 | cd /opt/apache 39 | ln -s /opt/apache/kafka_2.10-0.8.2-beta kafka 40 | 41 | exitscript -------------------------------------------------------------------------------- /vagrant/zk.sh: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | #!/bin/sh -Eux 17 | 18 | # Trap non-normal exit signals: 1/HUP, 2/INT, 3/QUIT, 15/TERM, ERR 19 | trap founderror 1 2 3 15 ERR 20 | 21 | founderror() 22 | { 23 | exit 1 24 | } 25 | 26 | exitscript() 27 | { 28 | #remove lock file 29 | #rm $lockfile 30 | exit 0 31 | } 32 | 33 | apt-get -y update 34 | 35 | apt-get install -y software-properties-common python-software-properties screen vim git wget 36 | add-apt-repository -y ppa:webupd8team/java 37 | apt-get -y update 38 | /bin/echo debconf shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections 39 | apt-get -y install oracle-java7-installer oracle-java7-set-default 40 | 41 | export JAVA_HOME=/usr 42 | 43 | su vagrant -c "touch ~/.bashrc" 44 | su vagrant -c "echo 'export JAVA_HOME=/usr' >> ~/.bashrc" 45 | 46 | cd /tmp 47 | wget https://archive.apache.org/dist/maven/maven-3/3.1.1/binaries/apache-maven-3.1.1-bin.tar.gz 48 | mkdir -p /opt/apache 49 | cd /opt/apache/ 50 | tar -xvf /tmp/apache-maven-3.1.1-bin.tar.gz 51 | export PATH=/opt/apache/apache-maven-3.1.1/bin:$PATH 52 | su vagrant -c "echo 'export PATH=/opt/apache/apache-maven-3.1.1/bin:$PATH' >> ~/.bashrc" 53 | 54 | cd /vagrant 55 | mvn clean 56 | mvn package 57 | 58 | /vagrant/vagrant/kafka.sh #install kafka 59 | 60 | /opt/apache/kafka/bin/zookeeper-server-start.sh /opt/apache/kafka/config/zookeeper.properties 1>> /tmp/zk.log 2>> /tmp/zk.log & 61 | 62 | 63 | --------------------------------------------------------------------------------