Fix use try-with-resources sonar issue
[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
26 import com.google.common.base.Optional;
27 import org.apache.spark.storage.StorageLevel;
28 import org.apache.spark.streaming.receiver.Receiver;
29 import org.onap.dcae.apod.analytics.cdap.common.utils.DMaaPMRUtils;
30 import org.onap.dcae.apod.analytics.cdap.plugins.domain.config.dmaap.DMaaPMRSourcePluginConfig;
31 import org.onap.dcae.apod.analytics.cdap.plugins.utils.CDAPPluginUtils;
32 import org.onap.dcae.apod.analytics.cdap.plugins.utils.DMaaPSourceConfigMapper;
33 import org.onap.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
34 import org.onap.dcae.apod.analytics.dmaap.DMaaPMRFactory;
35 import org.onap.dcae.apod.analytics.dmaap.service.subscriber.DMaaPMRSubscriber;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import java.util.List;
40 import java.util.concurrent.TimeUnit;
41
42 /**
43  * DMaaP MR Receiver which calls DMaaP MR Topic and stores structured records
44  * <p>
45  * @author Rajiv Singla . Creation Date: 1/19/2017.
46  */
47 public class DMaaPMRReceiver extends Receiver<StructuredRecord> {
48
49     private static final Logger LOG = LoggerFactory.getLogger(DMaaPMRReceiver.class);
50     private static final long serialVersionUID = 1L;
51
52     private final DMaaPMRSourcePluginConfig pluginConfig;
53     private final transient Metrics metrics;
54
55     public DMaaPMRReceiver(final StorageLevel storageLevel, final DMaaPMRSourcePluginConfig pluginConfig,
56                            final Metrics metrics) {
57         super(storageLevel);
58         this.pluginConfig = pluginConfig;
59         this.metrics = metrics;
60         LOG.debug("Created DMaaP MR Receiver instance with plugin Config: {}", pluginConfig);
61     }
62
63     @Override
64     public void onStart() {
65
66         // create DMaaP MR Subscriber
67         try(final DMaaPMRSubscriber subscriber =
68                 DMaaPMRFactory.create().createSubscriber(DMaaPSourceConfigMapper.map(pluginConfig))){
69
70             // Start a new thread with indefinite loop until receiver is stopped
71             new Thread() {
72                 @Override
73                 public void run() {
74                     while (!isStopped()) {
75                         storeStructuredRecords(subscriber);
76                         try {
77                             final Integer pollingInterval = pluginConfig.getPollingInterval();
78                             LOG.debug("DMaaP MR Receiver sleeping for polling interval: {}", pollingInterval);
79                             TimeUnit.MILLISECONDS.sleep(pollingInterval);
80                             } catch (InterruptedException e) {
81                                 final String errorMessage = String.format(
82                                         "Interrupted Exception while DMaaP MR Receiver sleeping polling interval: %s", e);
83                                 Thread.currentThread().interrupt();
84                                 throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
85                          }
86                      }
87                  }
88             }.start();
89         } catch (Exception e) {
90             LOG.error("Exception in DMaaPMRReceiver onStart",e);
91         }
92     }
93
94     @Override
95     public void onStop() {
96         LOG.debug("Stopping DMaaP MR Receiver with plugin config: {}", pluginConfig);
97     }
98
99     /**
100      * Fetches records from DMaaP MR Subscriber and store them as structured records
101      *
102      * @param subscriber DMaaP MR Subscriber Instance
103      */
104     public void storeStructuredRecords(final DMaaPMRSubscriber subscriber) {
105
106         LOG.debug("DMaaP MR Receiver start fetching messages from DMaaP MR Topic");
107
108         // Fetch messages from DMaaP MR Topic
109         final Optional<List<String>> subscriberMessagesOptional =
110                 DMaaPMRUtils.getSubscriberMessages(subscriber, metrics);
111
112         // store records
113         if (subscriberMessagesOptional.isPresent()) {
114             final List<String> messages = subscriberMessagesOptional.get();
115             for (final String message : messages) {
116                 store(CDAPPluginUtils.createDMaaPMRResponseStructuredRecord(message));
117             }
118             LOG.debug("Stored DMaaP Subscriber messages as Structured Records. Message count {}", messages.size());
119         }
120     }
121
122 }