|
| 1 | +package com.ge.predix.eventhub.spark.sample; |
| 2 | + |
| 3 | +import com.ge.predix.eventhub.*; |
| 4 | +import com.ge.predix.eventhub.client.Client; |
| 5 | +import com.ge.predix.eventhub.configuration.EventHubConfiguration; |
| 6 | +import com.ge.predix.eventhub.configuration.PublishConfiguration; |
| 7 | +import com.ge.predix.eventhub.configuration.SubscribeConfiguration; |
| 8 | +import com.google.protobuf.ByteString; |
| 9 | +import org.apache.spark.SparkConf; |
| 10 | +import org.apache.spark.api.java.JavaPairRDD; |
| 11 | +import org.apache.spark.api.java.JavaRDD; |
| 12 | +import org.apache.spark.api.java.JavaSparkContext; |
| 13 | +import org.json.JSONArray; |
| 14 | +import org.json.JSONObject; |
| 15 | +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; |
| 16 | +import org.springframework.web.bind.annotation.*; |
| 17 | +import scala.Tuple2; |
| 18 | + |
| 19 | +import javax.annotation.PostConstruct; |
| 20 | +import javax.annotation.PreDestroy; |
| 21 | +import java.io.BufferedWriter; |
| 22 | +import java.io.FileWriter; |
| 23 | +import java.io.IOException; |
| 24 | +import java.util.ArrayList; |
| 25 | +import java.util.Arrays; |
| 26 | +import java.util.Collections; |
| 27 | +import java.util.List; |
| 28 | +import java.util.concurrent.atomic.AtomicInteger; |
| 29 | +import java.util.logging.Logger; |
| 30 | + |
| 31 | +@RestController |
| 32 | +@EnableAutoConfiguration |
| 33 | +public class Controller { |
| 34 | + private static final Logger logger = Logger.getLogger(Controller.class.getName()); |
| 35 | + private static Client eventHub; |
| 36 | + private static EventHubConfiguration eventHubConfiguration; |
| 37 | + private static List<Message> rxMessages = Collections.synchronizedList(new ArrayList<Message>()); |
| 38 | + private static List<String> rxErrors = Collections.synchronizedList(new ArrayList<String>()); |
| 39 | + private static AtomicInteger rxErrorCount = new AtomicInteger(); |
| 40 | + |
| 41 | + private static final String subscriberName = "java-sdk-spark-sample-app-subscriber"; |
| 42 | + private static final String subscriberInstance = "spark-sample-app-instance"; |
| 43 | + private static BufferedWriter writer = null; |
| 44 | + private static SparkConf conf = null; |
| 45 | + private static JavaSparkContext sc = null; |
| 46 | + |
| 47 | + |
| 48 | + @PostConstruct |
| 49 | + public void makeClient() throws Exception { |
| 50 | + writer = new BufferedWriter(new FileWriter("messages.txt", true)); |
| 51 | + conf = new SparkConf().setMaster("local").setAppName("Work Count App"); |
| 52 | + sc = new JavaSparkContext(conf); |
| 53 | + System.out.println("******************************* Using environment variables *******************************"); |
| 54 | + fromExplicit(); |
| 55 | + |
| 56 | + class SubCallback implements Client.SubscribeCallback { |
| 57 | + @Override |
| 58 | + public void onMessage(Message message) { |
| 59 | + rxMessages.add(message); |
| 60 | + try { |
| 61 | + writer.write(message.toString()); |
| 62 | + writer.flush(); |
| 63 | + } catch (IOException e) { |
| 64 | + e.printStackTrace(); |
| 65 | + } |
| 66 | + } |
| 67 | + @Override |
| 68 | + public void onFailure(Throwable throwable) { |
| 69 | + rxErrors.add(throwable.getMessage()); |
| 70 | + rxErrorCount.incrementAndGet(); |
| 71 | + } |
| 72 | + } |
| 73 | + eventHub.subscribe(new SubCallback()); |
| 74 | + } |
| 75 | + |
| 76 | + @PreDestroy |
| 77 | + void closeWriter() throws IOException { |
| 78 | + writer.close(); |
| 79 | + } |
| 80 | + |
| 81 | + @RequestMapping(value = "/spark", method = RequestMethod.GET) |
| 82 | + void spark() { |
| 83 | + JavaRDD<String> lines = sc.textFile("messages.txt"); |
| 84 | + JavaPairRDD<String, Integer> pairs = lines.mapToPair(s -> new Tuple2<>(s,1)); |
| 85 | + JavaPairRDD<String, Integer> counts = pairs.reduceByKey((a, b) -> a + b); |
| 86 | + counts.saveAsTextFile("output"); |
| 87 | + sc.close(); |
| 88 | + } |
| 89 | + |
| 90 | + |
| 91 | + private void fromExplicit() throws EventHubClientException { |
| 92 | + try { |
| 93 | + EventHubConfiguration configuration = new EventHubConfiguration.Builder() |
| 94 | + .host(System.getenv("EVENTHUB_URI")) |
| 95 | + .port(Integer.parseInt(System.getenv("EVENTHUB_PORT"))) |
| 96 | + .authURL(System.getenv("AUTH_URL")) |
| 97 | + .clientID(System.getenv("CLIENT_ID")) |
| 98 | + .clientSecret(System.getenv("CLIENT_SECRET")) |
| 99 | + .zoneID(System.getenv("ZONE_ID")) |
| 100 | + .publishConfiguration(new PublishConfiguration.Builder().publisherType(PublishConfiguration.PublisherType.SYNC).build()) |
| 101 | + .subscribeConfiguration(new SubscribeConfiguration.Builder().subscriberName(subscriberName).subscriberInstance(subscriberInstance).build()) |
| 102 | + .build(); |
| 103 | + |
| 104 | + eventHub = new Client(configuration); |
| 105 | + logger.info("** logging Client credentials **"); |
| 106 | + logger.info(configuration.getAuthURL()); |
| 107 | + logger.info(configuration.getClientID()); |
| 108 | + logger.info(configuration.getHost()); |
| 109 | + logger.info(configuration.getZoneID()); |
| 110 | + logger.info(configuration.getPort() + ""); |
| 111 | + logger.info(configuration.isAutomaticTokenRenew() + ""); |
| 112 | + logger.info("** logging Client details done**"); |
| 113 | + eventHub.forceRenewToken(); |
| 114 | + eventHubConfiguration = configuration; |
| 115 | + |
| 116 | + } catch(EventHubClientException.InvalidConfigurationException e) { |
| 117 | + logger.info(e.getMessage()); |
| 118 | + System.out.println("Could not create client"); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + @RequestMapping(value = "/subscribe", method = RequestMethod.GET) |
| 123 | + String subscribe() throws EventHubClientException, IOException { |
| 124 | + JSONObject responses = new JSONObject(); |
| 125 | + JSONArray messages = new JSONArray(); |
| 126 | + JSONArray errors = new JSONArray(); |
| 127 | + |
| 128 | + |
| 129 | + while(rxMessages.size() != 0) { |
| 130 | + Message message = rxMessages.remove(0); |
| 131 | + messages.put(new JSONObject(String.format("{\"id\":\"%s\", \"body\":%s}", message.getId(), message.getBody().toStringUtf8()))); |
| 132 | + } |
| 133 | + |
| 134 | + |
| 135 | + for (String error : rxErrors) { |
| 136 | + errors.put(error); |
| 137 | + } |
| 138 | + |
| 139 | + responses.put("messages", messages); |
| 140 | + responses.put("errors", errors); |
| 141 | + |
| 142 | + return responses.toString(); |
| 143 | + } |
| 144 | + |
| 145 | + @RequestMapping(value = "/publish", method = RequestMethod.POST) |
| 146 | + String publish(@RequestBody String input, @RequestParam(value = "id") String id, @RequestParam(value = "count", required = false) Integer count ) throws EventHubClientException { |
| 147 | + List<Ack> acks; |
| 148 | + if(count != null && count >= 1){ |
| 149 | + Messages.Builder msgBuilder = Messages.newBuilder(); |
| 150 | + for(int i=0;i<count;i++){ |
| 151 | + Message msg = Message.newBuilder().setId(String.format("%s-%d", id, i)) |
| 152 | + .setZoneId(eventHubConfiguration.getZoneID()) |
| 153 | + .setBody(ByteString.copyFromUtf8(String.format("{message:\"%s\"}", input))).build(); |
| 154 | + |
| 155 | + msgBuilder.addMsg(msg); |
| 156 | + } |
| 157 | + acks = eventHub.addMessages(msgBuilder.build()).flush(); |
| 158 | + } |
| 159 | + else{ |
| 160 | + count = 1; |
| 161 | + acks = eventHub.addMessage(id, input, null).flush(); |
| 162 | + } |
| 163 | + |
| 164 | + JSONArray array = new JSONArray(); |
| 165 | + for(Ack a : acks){ |
| 166 | + array.put(ackToJSON(a)); |
| 167 | + } |
| 168 | + return array.toString(); |
| 169 | + } |
| 170 | + |
| 171 | + |
| 172 | + @RequestMapping("/") |
| 173 | + String home() { |
| 174 | + return "Hello Event Hub!"; |
| 175 | + } |
| 176 | + |
| 177 | + private JSONObject ackToJSON(Ack a) { |
| 178 | + JSONObject j = new JSONObject(); |
| 179 | + if(!a.getId().equals(a.getDefaultInstanceForType().getId())) |
| 180 | + j.put("id", a.getId()); |
| 181 | + j.put("status_code", a.getStatusCode()); |
| 182 | + if(a.getStatusCode() == AckStatus.ACCEPTED){ |
| 183 | + j.put("offset", a.getOffset()); |
| 184 | + j.put("partition", a.getPartition()); |
| 185 | + j.put("topic", a.getTopic()); |
| 186 | + }else{ |
| 187 | + j.put("desc", a.getDesc()); |
| 188 | + } |
| 189 | + return j; |
| 190 | + } |
| 191 | +} |
0 commit comments