aboutsummaryrefslogtreecommitdiffstats
path: root/dcae-analytics-cdap-tca/src/test/java/org/openecomp/dcae/apod/analytics/cdap/tca/BaseAnalyticsCDAPTCAUnitTest.java
blob: 6d84561d16ab34e945c79a42560926009b213c82 (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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * ===============================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;

import co.cask.cdap.api.flow.flowlet.AbstractFlowlet;
import co.cask.cdap.api.flow.flowlet.FlowletContext;
import co.cask.cdap.internal.flow.DefaultFlowletConfigurer;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Suppliers;
import org.junit.Assert;
import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCAPolicyPreferences;
import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCATestAppConfig;
import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCATestAppPreferences;
import org.openecomp.dcae.apod.analytics.model.domain.cef.EventListener;
import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;
import org.openecomp.dcae.apod.analytics.model.util.AnalyticsModelIOUtils;
import org.openecomp.dcae.apod.analytics.model.util.json.AnalyticsModelObjectMapperSupplier;
import org.openecomp.dcae.apod.analytics.test.BaseDCAEAnalyticsUnitTest;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Rajiv Singla . Creation Date: 10/25/2016.
 */
public abstract class BaseAnalyticsCDAPTCAUnitTest extends BaseDCAEAnalyticsUnitTest {

    /**
     * Object mapper to be used for all TCA Json Parsing
     */
    protected static final ObjectMapper ANALYTICS_MODEL_OBJECT_MAPPER =
            Suppliers.memoize(new AnalyticsModelObjectMapperSupplier()).get();

    protected static final String TCA_POLICY_JSON_FILE_LOCATION = "data/json/policy/tca_policy.json";
    protected static final String CEF_MESSAGES_JSON_FILE_LOCATION = "data/json/cef/cef_messages.json";
    protected static final String CEF_MESSAGE_JSON_FILE_LOCATION = "data/json/cef/cef_message.json";
    protected static final String CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION =
            "data/json/cef/cef_message_with_threshold_violation.json";

    protected static final String TCA_CONTROLLER_POLICY_FILE_LOCATION =
            "data/properties/tca_controller_policy.properties";

    protected static final String TCA_CONTROLLER_POLICY_FROM_JSON_FILE_LOCATION =
                        "data/properties/tca_controller_policy_from_json.properties";


    protected static final String TCA_TEST_APP_CONFIG_NAME = "testTCAAppName";
    protected static final String TCA_TEST_APP_CONFIG_DESCRIPTION = "testTCAAppDescription";
    protected static final String TCA_TEST_APP_CONFIG_SUBSCRIBER_OUTPUT_STREAM_NAME =
            "testTcaSubscriberOutputStreamName";
    protected static final String TCA_TEST_APP_CONFIG_VES_ALERT_TABLE_NAME = "testTcaVESAlertsTableName";
    protected static final String TCA_TEST_APP_CONFIG_VES_MESSAGE_STATUS_TABLE_NAME =
            "testTcaVESMessageStatusTableName";


    /**
     * Provides TCA Policy that can be used for testing
     *
     * @return test TCA Policy Object
     */
    protected TCAPolicy getSampleTCAPolicy() {
        return deserializeJsonFileToModel(TCA_POLICY_JSON_FILE_LOCATION, TCAPolicy.class);
    }

    /**
     * Provides TCA Policy that can be used for testing
     *
     * @return test {@link TCAPolicyPreferences}
     */
    protected TCAPolicyPreferences getSampleTCAPolicyPreferences() {
        return deserializeJsonFileToModel(TCA_POLICY_JSON_FILE_LOCATION, TCAPolicyPreferences.class);
    }

    /**
     * Provides list containing 350 CEF messages
     *
     * @return CEF Test Message
     *
     * @throws Exception Exception
     */
    protected List<EventListener> getCEFMessages() throws Exception {
        final String cefMessageAsString = fromStream(CEF_MESSAGES_JSON_FILE_LOCATION);
        final TypeReference<List<EventListener>> eventListenerListTypeReference =
                new TypeReference<List<EventListener>>() {
                };
        return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(cefMessageAsString, eventListenerListTypeReference);
    }

    /**
     * Provides 1 valid CEF messages which does not violate Threshold as String
     *
     * @return CEF Test Message String
     *
     * @throws Exception Exception
     */
    protected String getValidCEFMessage() throws Exception {
        return fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);
    }


    /**
     * Provides single CEF Test Message
     *
     * @return CEF Test Message
     *
     * @throws Exception Exception
     */
    protected EventListener getCEFEventListener() throws Exception {
        final String cefMessageAsString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);
        return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(cefMessageAsString, EventListener.class);
    }

    /**
     * Deserialize given Json file location to given model class and returns it back without any validation check
     *
     * @param jsonFileLocation Classpath location of the json file
     * @param modelClass Model Class type
     * @param <T> Json Model Type
     *
     * @return Json model object
     */
    public static <T> T deserializeJsonFileToModel(String jsonFileLocation, Class<T> modelClass) {
        final InputStream jsonFileInputStream =
                BaseDCAEAnalyticsUnitTest.class.getClassLoader().getResourceAsStream(jsonFileLocation);
        Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);
        try {
            return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(jsonFileInputStream, modelClass);
        } catch (IOException ex) {
            LOG.error("Error while doing assert Json for fileLocation: {}, modelClass: {}, Exception {}",
                    jsonFileLocation, modelClass, ex);
            throw new RuntimeException(ex);
        } finally {
            try {
                jsonFileInputStream.close();
            } catch (IOException e) {
                LOG.error("Error while closing input stream at file location: {}", jsonFileLocation);
                throw new RuntimeException(e);
            }
        }
    }

    protected static TCATestAppConfig getTCATestAppConfig() {
        final TCATestAppConfig tcaAppConfig = new TCATestAppConfig();
        tcaAppConfig.setAppName(TCA_TEST_APP_CONFIG_NAME);
        tcaAppConfig.setAppDescription(TCA_TEST_APP_CONFIG_DESCRIPTION);
        tcaAppConfig.setTcaSubscriberOutputStreamName(TCA_TEST_APP_CONFIG_SUBSCRIBER_OUTPUT_STREAM_NAME);
        tcaAppConfig.setTcaVESAlertsTableName(TCA_TEST_APP_CONFIG_VES_ALERT_TABLE_NAME);
        tcaAppConfig.setTcaVESMessageStatusTableName(TCA_TEST_APP_CONFIG_VES_MESSAGE_STATUS_TABLE_NAME);
        return tcaAppConfig;
    }

    /**
     * Provides a test application preference for unit testing
     *
     * @return tca app preferences
     */
    protected static TCATestAppPreferences getTCATestAppPreferences() {
        final TCATestAppPreferences tcaTestAppPreferences = new TCATestAppPreferences();
        tcaTestAppPreferences.setSubscriberHostName("SUBSCRIBER_HOST_NAME");
        tcaTestAppPreferences.setSubscriberHostPortNumber(10000);
        tcaTestAppPreferences.setSubscriberTopicName("SUBSCRIBER_TOPIC_NAME");
        tcaTestAppPreferences.setSubscriberUserName("SUBSCRIBER_USERNAME");
        tcaTestAppPreferences.setSubscriberUserPassword("SUBSCRIBER_PASSWORD");
        tcaTestAppPreferences.setSubscriberProtocol("https");
        tcaTestAppPreferences.setSubscriberContentType("application/json");
        tcaTestAppPreferences.setSubscriberConsumerId("SUBSCRIBER_CONSUMER_ID");
        tcaTestAppPreferences.setSubscriberConsumerGroup("SUBSCRIBER_CONSUMER_GROUP_NAME");
        tcaTestAppPreferences.setSubscriberTimeoutMS(10);
        tcaTestAppPreferences.setSubscriberMessageLimit(100);
        tcaTestAppPreferences.setSubscriberPollingInterval(1000);

        tcaTestAppPreferences.setPublisherHostName("PUBLISHER_HOST_NAME");
        tcaTestAppPreferences.setPublisherHostPort(1234);
        tcaTestAppPreferences.setPublisherTopicName("PUBLISHER_TOPIC_NAME");
        tcaTestAppPreferences.setPublisherUserName("PUBLISHER_USERNAME");
        tcaTestAppPreferences.setPublisherUserPassword("PUBLISHER_PASSWORD");
        tcaTestAppPreferences.setPublisherProtocol("https");
        tcaTestAppPreferences.setPublisherContentType("application/json");
        tcaTestAppPreferences.setPublisherMaxBatchSize(100);
        tcaTestAppPreferences.setPublisherMaxRecoveryQueueSize(100);
        tcaTestAppPreferences.setPublisherPollingInterval(6000);
        return tcaTestAppPreferences;
    }

    protected static Map<String, String> getPreferenceMap() {
        Map<String, String> preference = new HashMap<>();
        preference.put("subscriberHostName", "mrlocal-mtnjftle01.homer.com");
        preference.put("subscriberHostPort", "3905");
        preference.put("subscriberTopicName", "com.dcae.dmaap.mtnje2.DcaeTestVESPub");
        preference.put("subscriberProtocol", "https");
        preference.put("subscriberUserName", "USER");
        preference.put("subscriberUserPassword", "PASSWORD");
        preference.put("subscriberContentType", "application/json");
        preference.put("subscriberConsumerId", "123");
        preference.put("subscriberConsumerGroup", "testTCAConsumerName-123");
        preference.put("subscriberTimeoutMS", "-1");
        preference.put("subscriberMessageLimit", "-1");
        preference.put("subscriberPollingInterval", "30000");

        preference.put("publisherHostName", "publisherHostName");
        preference.put("publisherHostPort", "3905");
        preference.put("publisherTopicName", "publisherTopicName");
        preference.put("publisherProtocol", "https");
        preference.put("publisherUserName", "publisherUserName");
        preference.put("publisherContentType", "application/json");
        preference.put("publisherMaxBatchSize", "1000");
        preference.put("publisherMaxRecoveryQueueSize", "100");
        preference.put("publisherPollingInterval", "6000");
        return preference;
    }

    protected static <T extends AbstractFlowlet> void assertFlowletNameAndDescription(
            final String expectedName, final String expectedDescription, final T flowlet) {
        final DefaultFlowletConfigurer defaultFlowletConfigurer =
                new DefaultFlowletConfigurer(flowlet);
        flowlet.configure(defaultFlowletConfigurer);

        final String flowletName = getPrivateFiledValue(defaultFlowletConfigurer, "name", String.class);
        final String flowletDescription =
                getPrivateFiledValue(defaultFlowletConfigurer, "description", String.class);

        assertThat("Flowlet name must match with CDAPComponentsConstants",
                flowletName, is(expectedName));

        assertThat("Flowlet description must match with CDAPComponentsConstants",
                flowletDescription, is(expectedDescription));

    }

    protected static FlowletContext getTestFlowletContextWithValidPolicy() {
        final Properties controllerProperties =
                AnalyticsModelIOUtils.loadPropertiesFile(TCA_CONTROLLER_POLICY_FILE_LOCATION, new Properties());

        Map<String, String> runtimeArgs = new LinkedHashMap<>();
        for (Map.Entry<Object, Object> property : controllerProperties.entrySet()) {
            runtimeArgs.put(property.getKey().toString(), property.getValue().toString());
        }

        final FlowletContext flowletContext = mock(FlowletContext.class);
        when(flowletContext.getRuntimeArguments()).thenReturn(runtimeArgs);
        return flowletContext;
    }

    protected static FlowletContext getTestFlowletContextWithValidPolicyFromJSON() {
        final Properties controllerProperties =
                AnalyticsModelIOUtils.loadPropertiesFile(TCA_CONTROLLER_POLICY_FROM_JSON_FILE_LOCATION,
                        new Properties());

        Map<String, String> runtimeArgs = new LinkedHashMap<>();
        for (Map.Entry<Object, Object> property : controllerProperties.entrySet()) {
            runtimeArgs.put(property.getKey().toString(), property.getValue().toString());
        }

        final FlowletContext flowletContext = mock(FlowletContext.class);
        when(flowletContext.getRuntimeArguments()).thenReturn(runtimeArgs);
        return flowletContext;
    }

}