+ private void messageHandlingLoop() {
+ while (!isStopped()) {
+ try {
+ if (isDmaapConfigured()) {
+ Iterable<String> dmaapMsgs = fetchAllMessages();
+ if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
+ logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
+ for (String msg : dmaapMsgs) {
+ processMsg(msg);
+ }
+ }
+ } else {
+ sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
+ }
+ } catch (Exception e) {
+ logger.warn("{}", e.getMessage());
+ sleep(TIME_BETWEEN_DMAAP_RETRIES);
+ }
+ }
+ }
+
+ protected boolean isStopped() {
+ return false;
+ }
+
+ protected boolean isDmaapConfigured() {
+ String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
+ String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
+ return (!producerTopicUrl.isEmpty() && !consumerTopicUrl.isEmpty());
+ }
+
+ private static List<String> parseMessages(String jsonString) {
+ JsonArray arrayOfMessages = JsonParser.parseString(jsonString).getAsJsonArray();
+ List<String> result = new ArrayList<>();
+ for (JsonElement element : arrayOfMessages) {
+ if (element.isJsonPrimitive()) {
+ result.add(element.getAsString());
+ } else {
+ String messageAsString = element.toString();
+ result.add(messageAsString);
+ }
+ }
+ return result;
+ }
+
+ protected Iterable<String> fetchAllMessages() throws ServiceException {
+ String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
+ AsyncRestClient consumer = getMessageRouterConsumer();
+ ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
+ logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
+ if (response.getStatusCode().is2xxSuccessful()) {
+ return parseMessages(response.getBody());
+ } else {
+ throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
+ + " " + response.getBody());
+ }
+ }
+
+ private void processMsg(String msg) {
+ logger.debug("Message Reveived from DMAAP : {}", msg);
+ getDmaapMessageHandler().handleDmaapMsg(msg);
+ }
+
+ protected DmaapMessageHandler getDmaapMessageHandler() {
+ if (this.dmaapMessageHandler == null) {
+ String agentBaseUrl = "http://localhost:" + this.localServerHttpPort;
+ AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl, this.applicationConfig.getWebClientConfig());
+ AsyncRestClient producer = new AsyncRestClient(this.applicationConfig.getDmaapProducerTopicUrl(),
+ this.applicationConfig.getWebClientConfig());
+ this.dmaapMessageHandler = new DmaapMessageHandler(producer, agentClient);
+ }
+ return this.dmaapMessageHandler;
+ }
+
+ protected void sleep(Duration duration) {
+ try {
+ Thread.sleep(duration.toMillis());
+ } catch (Exception e) {
+ logger.error("Failed to put the thread to sleep", e);
+ }
+ }
+
+ protected AsyncRestClient getMessageRouterConsumer() {
+ return new AsyncRestClient("", this.applicationConfig.getWebClientConfig());
+ }