1c291af0ff96525b9a79548925c504069a0a36df
[dcaegen2/analytics/tca.git] / dcae-analytics-cdap-plugins / src / main / java / org / onap / dcae / apod / analytics / cdap / plugins / streaming / dmaap / DMaaPMRReceiver.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *   You may obtain a copy of the License at
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============================LICENSE_END===========================================
19  */
20
21 package org.onap.dcae.apod.analytics.cdap.plugins.streaming.dmaap;
22
23 import co.cask.cdap.api.data.format.StructuredRecord;
24 import co.cask.cdap.api.metrics.Metrics;
25 import com.google.common.base.Optional;
26 import org.apache.spark.storage.StorageLevel;
27 import org.apache.spark.streaming.receiver.Receiver;
28 import org.onap.dcae.apod.analytics.cdap.common.utils.DMaaPMRUtils;
29 import org.onap.dcae.apod.analytics.cdap.plugins.domain.config.dmaap.DMaaPMRSourcePluginConfig;
30 import org.onap.dcae.apod.analytics.cdap.plugins.utils.CDAPPluginUtils;
31 import org.onap.dcae.apod.analytics.cdap.plugins.utils.DMaaPSourceConfigMapper;
32 import org.onap.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
33 import org.onap.dcae.apod.analytics.dmaap.DMaaPMRFactory;
34 import org.onap.dcae.apod.analytics.dmaap.service.subscriber.DMaaPMRSubscriber;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import java.util.List;
39 import java.util.concurrent.TimeUnit;
40
41 /**
42  * DMaaP MR Receiver which calls DMaaP MR Topic and stores structured records
43  * <p>
44  * @author Rajiv Singla . Creation Date: 1/19/2017.
45  */
46 public class DMaaPMRReceiver extends Receiver<StructuredRecord> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(DMaaPMRReceiver.class);
49     private static final long serialVersionUID = 1L;
50
51     private final DMaaPMRSourcePluginConfig pluginConfig;
52     private final transient Metrics metrics;
53
54     public DMaaPMRReceiver(final StorageLevel storageLevel, final DMaaPMRSourcePluginConfig pluginConfig,
55                            final Metrics metrics) {
56         super(storageLevel);
57         this.pluginConfig = pluginConfig;
58         this.metrics = metrics;
59         LOG.debug("Created DMaaP MR Receiver instance with plugin Config: {}", pluginConfig);
60     }
61
62     @Override
63     public void onStart() {
64
65         // create DMaaP MR Subscriber
66         final DMaaPMRSubscriber subscriber =
67                 DMaaPMRFactory.create().createSubscriber(DMaaPSourceConfigMapper.map(pluginConfig));
68
69         // Start a new thread with indefinite loop until receiver is stopped
70         new Thread() {
71             @Override
72             public void run() {
73                 while (!isStopped()) {
74                     storeStructuredRecords(subscriber);
75                     try {
76                         final Integer pollingInterval = pluginConfig.getPollingInterval();
77                         LOG.debug("DMaaP MR Receiver sleeping for polling interval: {}", pollingInterval);
78                         TimeUnit.MILLISECONDS.sleep(pollingInterval);
79                     } catch (InterruptedException e) {
80                         final String errorMessage = String.format(
81                                 "Interrupted Exception while DMaaP MR Receiver sleeping polling interval: %s", e);
82                         Thread.currentThread().interrupt();
83                         throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
84                     }
85                 }
86             }
87         }.start();
88
89     }
90
91     @Override
92     public void onStop() {
93         LOG.debug("Stopping DMaaP MR Receiver with plugin config: {}", pluginConfig);
94     }
95
96     /**
97      * Fetches records from DMaaP MR Subscriber and store them as structured records
98      *
99      * @param subscriber DMaaP MR Subscriber Instance
100      */
101     public void storeStructuredRecords(final DMaaPMRSubscriber subscriber) {
102
103         LOG.debug("DMaaP MR Receiver start fetching messages from DMaaP MR Topic");
104
105         // Fetch messages from DMaaP MR Topic
106         final Optional<List<String>> subscriberMessagesOptional =
107                 DMaaPMRUtils.getSubscriberMessages(subscriber, metrics);
108
109         // store records
110         if (subscriberMessagesOptional.isPresent()) {
111             final List<String> messages = subscriberMessagesOptional.get();
112             for (final String message : messages) {
113                 store(CDAPPluginUtils.createDMaaPMRResponseStructuredRecord(message));
114             }
115             LOG.debug("Stored DMaaP Subscriber messages as Structured Records. Message count {}", messages.size());
116         }
117     }
118
119 }