aboutsummaryrefslogtreecommitdiffstats
path: root/dcae-analytics-cdap-tca/src/main/java/org/openecomp/dcae/apod/analytics/cdap/tca/worker/TCADMaaPMockSubscriberWorker.java
blob: 4d721e2910ef0eb8459787dabfbe82a1b86bfdeb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
 * ===============================LICENSE_START======================================
 *  dcae-analytics
 * ================================================================================
 *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  ============================LICENSE_END===========================================
 */

package org.openecomp.dcae.apod.analytics.cdap.tca.worker;

import co.cask.cdap.api.annotation.Property;
import co.cask.cdap.api.worker.AbstractWorker;
import co.cask.cdap.api.worker.WorkerContext;
import com.fasterxml.jackson.core.type.TypeReference;
import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCAAppPreferences;
import org.openecomp.dcae.apod.analytics.cdap.tca.utils.CDAPTCAUtils;
import org.openecomp.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
import org.openecomp.dcae.apod.analytics.model.domain.cef.EventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static org.openecomp.dcae.apod.analytics.tca.utils.TCAUtils.readValue;
import static org.openecomp.dcae.apod.analytics.tca.utils.TCAUtils.writeValueAsString;

/**
 * CDAP Worker which mocks fetching VES Messages from DMaaP MR topic.
 * The mock instead of making DMaaP MR calls will actually take messages
 * from file and send them to stream at subscriber polling interval
 *
 * TODO: To be removed before going to production - only for testing purposes
 *
 * @author Rajiv Singla . Creation Date: 11/4/2016.
 */
public class TCADMaaPMockSubscriberWorker extends AbstractWorker {

    private static final Logger LOG = LoggerFactory.getLogger(TCADMaaPMockSubscriberWorker.class);

    // TODO: Remove this file before going to production - only for mocking purposes
    private static final String MOCK_MESSAGE_FILE_LOCATION = "ves_mock_messages.json";
    private static final TypeReference<List<EventListener>> EVENT_LISTENER_TYPE_REFERENCE =
            new TypeReference<List<EventListener>>() {
            };

    private TCAAppPreferences tcaAppPreferences;
    private boolean stopSendingMessages;
    @Property
    private final String tcaSubscriberOutputStreamName;

    public TCADMaaPMockSubscriberWorker(final String tcaSubscriberOutputStreamName) {
        this.tcaSubscriberOutputStreamName = tcaSubscriberOutputStreamName;
    }

    @Override
    public void configure() {
        setName("MockTCASubscriberWorker");
        setDescription("Writes Mocked VES messages to CDAP Stream");
        LOG.info("Configuring Mock TCA MR DMaaP Subscriber worker with name: {}", "MockTCASubscriberWorker");
    }

    @Override
    public void initialize(WorkerContext context) throws Exception {
        super.initialize(context);

        final TCAAppPreferences appPreferences = CDAPTCAUtils.getValidatedTCAAppPreferences(context);
        LOG.info("Initializing Mock TCA MR DMaaP Subscriber worker with preferences: {}", appPreferences);
        this.tcaAppPreferences = appPreferences;
        this.stopSendingMessages = false;
    }


    @Override
    public void run() {
        final Integer subscriberPollingInterval = tcaAppPreferences.getSubscriberPollingInterval();
        LOG.debug("Mock TCA Subscriber Polling interval: {}", subscriberPollingInterval);

        final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream
                (MOCK_MESSAGE_FILE_LOCATION);

        if (resourceAsStream == null) {
            LOG.error("Unable to find file at location: {}", MOCK_MESSAGE_FILE_LOCATION);
            throw new DCAEAnalyticsRuntimeException("Unable to find file", LOG, new FileNotFoundException());
        }


        try {
            List<EventListener> eventListeners = readValue(resourceAsStream, EVENT_LISTENER_TYPE_REFERENCE);

            final int totalMessageCount = eventListeners.size();
            LOG.debug("Mock message count to be written to cdap stream: ()", totalMessageCount);

            int i = 1;
            for (EventListener eventListener : eventListeners) {
                if (stopSendingMessages) {
                    LOG.debug("Stop sending messages......");
                    break;
                }
                final String eventListenerString = writeValueAsString(eventListener);
                LOG.debug("=======>> Writing message to cdap stream no: {} of {}", i, totalMessageCount);
                getContext().write(tcaSubscriberOutputStreamName, eventListenerString);
                i++;

                try {
                    Thread.sleep(subscriberPollingInterval);
                } catch (InterruptedException e) {
                    LOG.error("Error while sleeping");
                    throw new DCAEAnalyticsRuntimeException("Error while sleeping", LOG, e);
                }
            }

            LOG.debug("Finished writing mock messages to CDAP Stream");

        } catch (IOException e) {
            LOG.error("Error while parsing json file");
            throw new DCAEAnalyticsRuntimeException("Error while parsing mock json file", LOG, e);
        }


    }

    @Override
    public void stop() {
        stopSendingMessages = true;
    }
}