+@Component
+public class DmaapMessageConsumer {
+
+ protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
+
+ private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
+
+ private final ApplicationConfig applicationConfig;
+
+ private DmaapMessageHandler dmaapMessageHandler = null;
+
+ @Value("${server.http-port}")
+ private int localServerHttpPort;
+
+ @Autowired
+ public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
+ this.applicationConfig = applicationConfig;
+ }
+
+ /**
+ * Starts the consumer. If there is a DMaaP configuration, it will start polling
+ * for messages. Otherwise it will check regularly for the configuration.
+ *
+ * @return the running thread, for test purposes.
+ */
+ public Thread start() {
+ Thread thread = new Thread(this::messageHandlingLoop);
+ thread.start();
+ return thread;
+ }
+
+ 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;
+ }