TCA: Support for VES/A&AI enrichment
[dcaegen2/analytics/tca.git] / dcae-analytics-tca / src / test / java / org / openecomp / dcae / apod / analytics / tca / utils / TCAUtilsTest.java
index 458f18c..853ac54 100644 (file)
-/*
- * ===============================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.tca.utils;
-
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Table;
-import org.apache.commons.lang3.tuple.Pair;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.mockito.Mockito;
-import org.openecomp.dcae.apod.analytics.common.AnalyticsConstants;
-import org.openecomp.dcae.apod.analytics.common.exception.MessageProcessingException;
-import org.openecomp.dcae.apod.analytics.model.domain.cef.CommonEventHeader;
-import org.openecomp.dcae.apod.analytics.model.domain.cef.Domain;
-import org.openecomp.dcae.apod.analytics.model.domain.cef.Event;
-import org.openecomp.dcae.apod.analytics.model.domain.cef.EventListener;
-import org.openecomp.dcae.apod.analytics.model.domain.cef.EventSeverity;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.ControlLoopEventStatus;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.ControlLoopSchemaType;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.Direction;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.MetricsPerEventName;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;
-import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.Threshold;
-import org.openecomp.dcae.apod.analytics.model.facade.tca.TCAVESResponse;
-import org.openecomp.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest;
-import org.openecomp.dcae.apod.analytics.tca.processor.TCACEFProcessorContext;
-import org.quartz.Job;
-import org.quartz.JobDataMap;
-import org.quartz.JobDetail;
-import org.quartz.Scheduler;
-import org.quartz.SimpleTrigger;
-import org.quartz.impl.StdSchedulerFactory;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.isA;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-/**
- * @author Rajiv Singla . Creation Date: 11/9/2016.
- */
-public class TCAUtilsTest extends BaseAnalyticsTCAUnitTest {
-
-    @Test
-    public void testGetPolicyEventNames() throws Exception {
-
-        final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy();
-        final List<String> eventNames = TCAUtils.getPolicyEventNames(sampleTCAPolicy);
-
-        assertThat("Policy event names must contain vFirewall and vLoadBalancer", eventNames,
-                containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer"));
-    }
-
-    @Test
-    public void testGetPolicyEventNamesSupplier() throws Exception {
-        final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy();
-        final Supplier<List<String>> policyEventNamesSupplier = TCAUtils.getPolicyEventNamesSupplier
-                (sampleTCAPolicy);
-        final List<String> eventNames = policyEventNamesSupplier.get();
-        assertThat("Policy event names must contain vFirewall and vLoadBalancer", eventNames,
-                containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer"));
-    }
-
-    @Test
-    public void testProcessCEFMessage() throws Exception {
-        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);
-        final TCACEFProcessorContext tcacefProcessorContext = TCAUtils.filterCEFMessage(cefMessageString,
-                getSampleTCAPolicy());
-        assertThat("TCAECEFProcessor Processor Context can continue flag is true", tcacefProcessorContext
-                .canProcessingContinue(), is(true));
-    }
-
-    @Test
-    public void testGetPolicyFRThresholdsTableSupplier() throws Exception {
-        final Table<String, String, List<Threshold>> policyFRThresholdPathTable = TCAUtils
-                .getPolicyEventNameThresholdsTableSupplier(getSampleTCAPolicy()).get();
-
-        final Map<String, List<Threshold>> eNodeBRankpi = policyFRThresholdPathTable.row("Mfvs_eNodeB_RANKPI");
-        final Map<String, List<Threshold>> vLoadBalancer = policyFRThresholdPathTable.row("vLoadBalancer");
-
-        final Set<String> eNodeBRankpiFieldPaths = eNodeBRankpi.keySet();
-        final Set<String> vLoadBalancerPaths = vLoadBalancer.keySet();
-
-        final String receivedBroadcastPacketsFieldPath =
-                "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated";
-        assertThat("eNodeBRankpi threshold field path size must be " +
-                        "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" +
-                        ".receivedBroadcastPacketsAccumulated",
-                eNodeBRankpiFieldPaths.iterator().next(),
-                is(receivedBroadcastPacketsFieldPath));
-
-        assertThat("vLoadBalancer threshold field path size must be " +
-                        "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" +
-                        ".receivedBroadcastPacketsAccumulated",
-                vLoadBalancerPaths.iterator().next(),
-                is(receivedBroadcastPacketsFieldPath));
-
-        final List<Threshold> eNodeBRankpiThresholds = policyFRThresholdPathTable.get("Mfvs_eNodeB_RANKPI",
-                receivedBroadcastPacketsFieldPath);
-        final List<Threshold> vLoadBalancerThresholds = policyFRThresholdPathTable.get("vLoadBalancer",
-                receivedBroadcastPacketsFieldPath);
-
-        assertThat("eNodeBRankpi Threshold size must be 3", eNodeBRankpiThresholds.size(), is(3));
-        assertThat("vLoadBalancer Threshold size must be 2", vLoadBalancerThresholds.size(), is(2));
-    }
-
-    @Test
-    public void testGetJsonPathValueWithValidMessageAndPolicy() throws Exception {
-        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);
-        final String jsonPath =
-                "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated";
-        final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath);
-        final Map<String, List<Long>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths);
-        assertThat("Json Path value must match", jsonPathValueMap.get(jsonPath).get(0), is(5000L));
-
-    }
-
-    @Test
-    public void testGetJsonPathValueWithValidPath() throws Exception {
-        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);
-        final String jsonPath = "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].invalid";
-        final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath);
-        final Map<String, List<Long>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths);
-        assertThat("Json path value must be empty", jsonPathValueMap.size(), is(0));
-
-    }
-
-
-    @Test
-    public void testCreateNewTCAVESResponseWithVFControlLoopSchemaType() throws Exception {
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-
-        MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class);
-        when(metricsPerEventName.getThresholds()).thenReturn(getThresholds());
-        when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope");
-        when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName);
-        when(metricsPerEventName.getEventName()).thenReturn("testEventName");
-        when(metricsPerEventName.getControlLoopSchemaType()).thenReturn(ControlLoopSchemaType.VM);
-
-        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");
-
-        //TODO :  Add proper assertions, as the usage is not clearly understood
-        assertThat(tcaVESResponse.getClosedLoopControlName(),
-                is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"));
-        assertThat(tcaVESResponse.getVersion(), is("Test Version"));
-        assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope"));
-        assertNull(tcaVESResponse.getAai().getGenericVNFId());
-        assertNotNull(tcaVESResponse.getAai().getGenericServerId());
-    }
-
-    @Test
-    public void testCreateNewTCAVESResponseWithFunctionalRolevFirewall() throws Exception {
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-
-        MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class);
-        when(metricsPerEventName.getThresholds()).thenReturn(getThresholds());
-        when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope");
-        when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName);
-        when(metricsPerEventName.getEventName()).thenReturn("vFirewall");
-
-        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");
-
-        //TODO :  Add proper assertions, as the usage is not clearly understood
-        assertThat(tcaVESResponse.getClosedLoopControlName(),
-                is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"));
-        assertThat(tcaVESResponse.getVersion(), is("Test Version"));
-        assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope"));
-        assertNotNull(tcaVESResponse.getAai().getGenericVNFId());
-        assertNull(tcaVESResponse.getAai().getGenericServerId());
-    }
-
-    @Rule
-    public ExpectedException expectedIllegalArgumentException = ExpectedException.none();
-
-    @Test
-    public void testCreateNewTCAVESResponseNullFunctionalRole() throws Exception {
-        expectedIllegalArgumentException.expect(MessageProcessingException.class);
-        expectedIllegalArgumentException.expectCause(isA(IllegalArgumentException.class));
-        expectedIllegalArgumentException.expectMessage("No violations metrics. Unable to create VES Response");
-
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");
-        assertNotNull(tcaVESResponse.getClosedLoopControlName());
-    }
-
-    @Test
-    public void testPrioritizeThresholdViolations() throws Exception {
-
-        Map<String, Threshold> thresholdMap = new HashMap<>();
-        Threshold majorThreshold = mock(Threshold.class);
-        when(majorThreshold.getSeverity()).thenReturn(EventSeverity.MAJOR);
-        thresholdMap.put("MAJOR", majorThreshold);
-
-        Threshold result1 = TCAUtils.prioritizeThresholdViolations(thresholdMap);
-        assertEquals(result1.getSeverity(), EventSeverity.MAJOR);
-
-        Threshold criticalThreshold = mock(Threshold.class);
-        when(criticalThreshold.getSeverity()).thenReturn(EventSeverity.CRITICAL);
-        thresholdMap.put("CRITICAL", criticalThreshold);
-
-        Threshold result2 = TCAUtils.prioritizeThresholdViolations(thresholdMap);
-        assertEquals(result2.getSeverity(), EventSeverity.CRITICAL);
-    }
-
-    @Test
-    public void testCreateViolatedMetrics() throws Exception {
-        TCAPolicy tcaPolicy = getSampleTCAPolicy();
-        Threshold violatedThreshold = getCriticalThreshold();
-        String functionalRole = "Mfvs_eNodeB_RANKPI";
-        MetricsPerEventName result = TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, functionalRole);
-        assertThat(result.getPolicyScope(), is("resource=vFirewall;type=configuration"));
-        assertThat(result.getPolicyName(), is("configuration.dcae.microservice.tca.xml"));
-    }
-
-    @Test
-    public void testCreateViolatedMetricsWrongEventName() throws Exception {
-        expectedIllegalArgumentException.expect(MessageProcessingException.class);
-        expectedIllegalArgumentException.expectCause(isA(IllegalStateException.class));
-        String eventName = "badEventName";
-        expectedIllegalArgumentException.expectMessage("TCA Policy must contain eventName: " + eventName);
-        TCAPolicy tcaPolicy = getSampleTCAPolicy();
-        Threshold violatedThreshold = getCriticalThreshold();
-        TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, eventName);
-    }
-
-    @Test
-    public void testGetDomainAndEventName() {
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-        EventListener eventListener = mock(EventListener.class);
-        Event event = mock(Event.class);
-        CommonEventHeader commonEventHeader = mock(CommonEventHeader.class);
-
-        Pair<String, String> result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);
-        assertNull(result.getLeft());
-        assertNull(result.getRight());
-
-        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(eventListener);
-        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);
-        assertNull(result.getLeft());
-        assertNull(result.getRight());
-
-        when(eventListener.getEvent()).thenReturn(event);
-        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);
-        assertNull(result.getLeft());
-        assertNull(result.getRight());
-
-        when(event.getCommonEventHeader()).thenReturn(commonEventHeader);
-        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);
-        assertNull(result.getLeft());
-        assertNull(result.getRight());
-
-        when(commonEventHeader.getDomain()).thenReturn(Domain.other);
-        when(commonEventHeader.getEventName()).thenReturn("eventName");
-
-        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);
-        assertEquals(result.getLeft(), "other");
-        assertEquals(result.getRight(), "eventName");
-
-    }
-
-    @Test
-    public void testComputeThresholdViolationsNotPresent() throws Exception {
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-        when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true);
-        when(tcacefProcessorContext.getMessage()).thenReturn(getValidCEFMessage());
-
-        when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy());
-        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-
-        TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext);
-        assertNotNull(result);
-        verify(result, times(0)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class));
-        assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy());
-    }
-
-    @Test
-    public void testComputeThresholdViolationsPresent() throws Exception {
-        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);
-        when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true);
-        final String cefMessageString = fromStream(CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION);
-        when(tcacefProcessorContext.getMessage()).thenReturn(cefMessageString);
-
-        when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy());
-        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-
-        TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext);
-        verify(result, times(1)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class));
-
-        assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy());
-    }
-
-
-    @Test
-    public void testCreateTCAPolicyMetricsPerFunctionalRoleList() throws Exception {
-
-        final Map<String, String> tcaPolicyMap = TCAUtils.filterMapByKeyNamePrefix(getControllerRuntimeArguments(),
-                AnalyticsConstants.TCA_POLICY_METRICS_PER_FUNCTIONAL_ROLE_PATH);
-
-        // determine functional Roles
-        final Map<String, Map<String, String>> functionalRolesMap =
-                TCAUtils.extractSubTree(tcaPolicyMap, 2, 3, AnalyticsConstants.TCA_POLICY_DELIMITER);
-
-        final List<MetricsPerEventName> tcaPolicyMetricsPerEventNameList =
-                TCAUtils.createTCAPolicyMetricsPerEventNameList(functionalRolesMap);
-
-        assertThat("There are two Metrics per function role", 2,
-                is(tcaPolicyMetricsPerEventNameList.size()));
-    }
-
-
-    @Test
-    public void testCreateQuartzScheduler() throws Exception {
-        final Scheduler scheduler = Mockito.mock(Scheduler.class);
-        final StdSchedulerFactory stdSchedulerFactory = Mockito.mock(StdSchedulerFactory.class);
-        when(stdSchedulerFactory.getScheduler()).thenReturn(scheduler);
-        final JobDataMap jobDataMap = Mockito.mock(JobDataMap.class);
-        TCAUtils.createQuartzScheduler(1000, stdSchedulerFactory,
-                "data/properties/quartz-test.properties", jobDataMap, Job.class,
-                "testJob", "testTigger");
-        verify(scheduler, times(1))
-                .scheduleJob(Mockito.any(JobDetail.class), Mockito.any(SimpleTrigger.class));
-    }
-
-
-    @Test
-    public void testCreateTCAAlertStringWhenCEFIsEnabled() throws Exception {
-        final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.CRITICAL);
-        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);
-        when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics);
-        when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-        final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", true);
-        assertTrue(alertString.contains("thresholdCrossingAlertFields"));
-    }
-
-    @Test(expected = MessageProcessingException.class)
-    public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsEnabled() throws Exception {
-        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);
-        when(processorContext.getMetricsPerEventName()).thenReturn(null);
-        TCAUtils.createTCAAlertString(processorContext, "testApp", true);
-    }
-
-    @Test
-    public void testCreateTCAAlertStringWhenCEFIsDisabled() throws Exception {
-        final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.MAJOR);
-        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);
-        when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics);
-        when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener());
-        final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", false);
-        assertFalse(alertString.contains("thresholdCrossingAlertFields"));
-    }
-
-    @Test(expected = MessageProcessingException.class)
-    public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsDisabled() throws Exception {
-        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);
-        when(processorContext.getMetricsPerEventName()).thenReturn(null);
-        TCAUtils.createTCAAlertString(processorContext, "testApp", false);
-    }
-
-    private static MetricsPerEventName createViolatedMetricsPerEventName(EventSeverity severity) {
-        final Threshold violatedThreshold = new Threshold();
-        violatedThreshold.setSeverity(severity);
-        violatedThreshold.setDirection(Direction.GREATER);
-        violatedThreshold.setClosedLoopControlName("violatedThresholdClosedLoopName");
-        violatedThreshold.setActualFieldValue(100L);
-        violatedThreshold.setFieldPath("violatedThresholdFieldPath");
-        violatedThreshold.setVersion("violatedThresholdVersion");
-        violatedThreshold.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
-        violatedThreshold.setThresholdValue(50L);
-
-        final MetricsPerEventName violatedMetrics = new MetricsPerEventName();
-        violatedMetrics.setPolicyName("violatePolicyName");
-        violatedMetrics.setPolicyVersion("violatedPolicyVersion");
-        violatedMetrics.setPolicyScope("violatedPolicyScope");
-        violatedMetrics.setEventName("violatedEventName");
-        violatedMetrics.setThresholds(Arrays.asList(violatedThreshold));
-        return violatedMetrics;
-    }
-}
+/*\r
+ * ===============================LICENSE_START======================================\r
+ *  dcae-analytics\r
+ * ================================================================================\r
+ *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ *  Licensed under the Apache License, Version 2.0 (the "License");\r
+ *  you may not use this file except in compliance with the License.\r
+ *   You may obtain a copy of the License at\r
+ *\r
+ *          http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ *  Unless required by applicable law or agreed to in writing, software\r
+ *  distributed under the License is distributed on an "AS IS" BASIS,\r
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ *  See the License for the specific language governing permissions and\r
+ *  limitations under the License.\r
+ *  ============================LICENSE_END===========================================\r
+ */\r
+\r
+package org.openecomp.dcae.apod.analytics.tca.utils;\r
+\r
+import com.fasterxml.jackson.databind.JsonNode;\r
+import com.google.common.base.Supplier;\r
+import com.google.common.collect.ImmutableSet;\r
+import com.google.common.collect.Table;\r
+import org.apache.commons.lang3.tuple.Pair;\r
+import org.junit.Rule;\r
+import org.junit.Test;\r
+import org.junit.rules.ExpectedException;\r
+import org.mockito.Mockito;\r
+import org.openecomp.dcae.apod.analytics.common.AnalyticsConstants;\r
+import org.openecomp.dcae.apod.analytics.common.exception.MessageProcessingException;\r
+import org.openecomp.dcae.apod.analytics.model.domain.cef.CommonEventHeader;\r
+import org.openecomp.dcae.apod.analytics.model.domain.cef.Domain;\r
+import org.openecomp.dcae.apod.analytics.model.domain.cef.Event;\r
+import org.openecomp.dcae.apod.analytics.model.domain.cef.EventListener;\r
+import org.openecomp.dcae.apod.analytics.model.domain.cef.EventSeverity;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.ClosedLoopEventStatus;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.ControlLoopSchemaType;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.Direction;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.MetricsPerEventName;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;\r
+import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.Threshold;\r
+import org.openecomp.dcae.apod.analytics.model.facade.tca.AAI;\r
+import org.openecomp.dcae.apod.analytics.model.facade.tca.TCAVESResponse;\r
+import org.openecomp.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest;\r
+import org.openecomp.dcae.apod.analytics.tca.processor.TCACEFProcessorContext;\r
+import org.quartz.Job;\r
+import org.quartz.JobDataMap;\r
+import org.quartz.JobDetail;\r
+import org.quartz.Scheduler;\r
+import org.quartz.SimpleTrigger;\r
+import org.quartz.impl.StdSchedulerFactory;\r
+\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import static org.hamcrest.CoreMatchers.is;\r
+import static org.hamcrest.CoreMatchers.isA;\r
+import static org.hamcrest.Matchers.containsInAnyOrder;\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertFalse;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
+import static org.junit.Assert.assertThat;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.mockito.Mockito.mock;\r
+import static org.mockito.Mockito.times;\r
+import static org.mockito.Mockito.verify;\r
+import static org.mockito.Mockito.when;\r
+\r
+/**\r
+ * @author Rajiv Singla . Creation Date: 11/9/2016.\r
+ */\r
+public class TCAUtilsTest extends BaseAnalyticsTCAUnitTest {\r
+\r
+    @Test\r
+    public void testGetPolicyEventNames() throws Exception {\r
+\r
+        final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy();\r
+        final List<String> eventNames = TCAUtils.getPolicyEventNames(sampleTCAPolicy);\r
+\r
+        assertThat("Policy event names must contain vFirewall, vLoadBalancer, virtualVMEventName", eventNames,\r
+                containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer", "virtualVMEventName"));\r
+    }\r
+\r
+    @Test\r
+    public void testGetPolicyEventNamesSupplier() throws Exception {\r
+        final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy();\r
+        final Supplier<List<String>> policyEventNamesSupplier = TCAUtils.getPolicyEventNamesSupplier\r
+                (sampleTCAPolicy);\r
+        final List<String> eventNames = policyEventNamesSupplier.get();\r
+        assertThat("Policy event names must contain vFirewall and vLoadBalancer", eventNames,\r
+                containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer", "virtualVMEventName"));\r
+    }\r
+\r
+    @Test\r
+    public void testProcessCEFMessage() throws Exception {\r
+        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);\r
+        final TCACEFProcessorContext tcacefProcessorContext = TCAUtils.filterCEFMessage(cefMessageString,\r
+                getSampleTCAPolicy());\r
+        assertThat("TCAECEFProcessor Processor Context can continue flag is true", tcacefProcessorContext\r
+                .canProcessingContinue(), is(true));\r
+    }\r
+\r
+    @Test\r
+    public void testGetPolicyFRThresholdsTableSupplier() throws Exception {\r
+        final Table<String, String, List<Threshold>> policyFRThresholdPathTable = TCAUtils\r
+                .getPolicyEventNameThresholdsTableSupplier(getSampleTCAPolicy()).get();\r
+\r
+        final Map<String, List<Threshold>> eNodeBRankpi = policyFRThresholdPathTable.row("Mfvs_eNodeB_RANKPI");\r
+        final Map<String, List<Threshold>> vLoadBalancer = policyFRThresholdPathTable.row("vLoadBalancer");\r
+\r
+        final Set<String> eNodeBRankpiFieldPaths = eNodeBRankpi.keySet();\r
+        final Set<String> vLoadBalancerPaths = vLoadBalancer.keySet();\r
+\r
+        final String receivedBroadcastPacketsFieldPath =\r
+                "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated";\r
+        assertThat("eNodeBRankpi threshold field path size must be " +\r
+                        "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" +\r
+                        ".receivedBroadcastPacketsAccumulated",\r
+                eNodeBRankpiFieldPaths.iterator().next(),\r
+                is(receivedBroadcastPacketsFieldPath));\r
+\r
+        assertThat("vLoadBalancer threshold field path size must be " +\r
+                        "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" +\r
+                        ".receivedBroadcastPacketsAccumulated",\r
+                vLoadBalancerPaths.iterator().next(),\r
+                is(receivedBroadcastPacketsFieldPath));\r
+\r
+        final List<Threshold> eNodeBRankpiThresholds = policyFRThresholdPathTable.get("Mfvs_eNodeB_RANKPI",\r
+                receivedBroadcastPacketsFieldPath);\r
+        final List<Threshold> vLoadBalancerThresholds = policyFRThresholdPathTable.get("vLoadBalancer",\r
+                receivedBroadcastPacketsFieldPath);\r
+\r
+        assertThat("eNodeBRankpi Threshold size must be 3", eNodeBRankpiThresholds.size(), is(3));\r
+        assertThat("vLoadBalancer Threshold size must be 2", vLoadBalancerThresholds.size(), is(2));\r
+    }\r
+\r
+    @Test\r
+    public void testGetJsonPathValueWithValidMessageAndPolicy() throws Exception {\r
+        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);\r
+        final String jsonPath =\r
+                "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated";\r
+        final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath);\r
+        final Map<String, List<Long>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths);\r
+        assertThat("Json Path value must match", jsonPathValueMap.get(jsonPath).get(0), is(5000L));\r
+\r
+    }\r
+\r
+    @Test\r
+    public void testGetJsonPathValueWithValidPath() throws Exception {\r
+        final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION);\r
+        final String jsonPath = "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].invalid";\r
+        final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath);\r
+        final Map<String, List<Long>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths);\r
+        assertThat("Json path value must be empty", jsonPathValueMap.size(), is(0));\r
+\r
+    }\r
+\r
+\r
+    @Test\r
+    public void testCreateNewTCAVESResponseWithVFControlLoopSchemaType() throws Exception {\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+\r
+        MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class);\r
+        when(metricsPerEventName.getThresholds()).thenReturn(getThresholds());\r
+        when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope");\r
+        when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName);\r
+        when(metricsPerEventName.getEventName()).thenReturn("testEventName");\r
+        when(metricsPerEventName.getControlLoopSchemaType()).thenReturn(ControlLoopSchemaType.VM);\r
+\r
+        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");\r
+\r
+        //TODO :  Add proper assertions, as the usage is not clearly understood\r
+        assertThat(tcaVESResponse.getClosedLoopControlName(),\r
+                is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"));\r
+        assertThat(tcaVESResponse.getVersion(), is("Test Version"));\r
+        assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope"));\r
+        assertNull(tcaVESResponse.getAai().getGenericVNFId());\r
+        assertNotNull(tcaVESResponse.getAai().getGenericServerId());\r
+    }\r
+\r
+    @Test\r
+    public void testCreateNewTCAVESResponseWithFunctionalRolevFirewall() throws Exception {\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+\r
+        MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class);\r
+        when(metricsPerEventName.getThresholds()).thenReturn(getThresholds());\r
+        when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope");\r
+        when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName);\r
+        when(metricsPerEventName.getEventName()).thenReturn("vFirewall");\r
+\r
+        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");\r
+\r
+        //TODO :  Add proper assertions, as the usage is not clearly understood\r
+        assertThat(tcaVESResponse.getClosedLoopControlName(),\r
+                is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"));\r
+        assertThat(tcaVESResponse.getVersion(), is("Test Version"));\r
+        assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope"));\r
+        assertNotNull(tcaVESResponse.getAai().getGenericVNFId());\r
+        assertNull(tcaVESResponse.getAai().getGenericServerId());\r
+    }\r
+\r
+    @Rule\r
+    public ExpectedException expectedIllegalArgumentException = ExpectedException.none();\r
+\r
+    @Test\r
+    public void testCreateNewTCAVESResponseNullFunctionalRole() throws Exception {\r
+        expectedIllegalArgumentException.expect(MessageProcessingException.class);\r
+        expectedIllegalArgumentException.expectCause(isA(IllegalArgumentException.class));\r
+        expectedIllegalArgumentException.expectMessage("No violations metrics. Unable to create VES Response");\r
+\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+        TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME");\r
+        assertNotNull(tcaVESResponse.getClosedLoopControlName());\r
+    }\r
+\r
+    @Test\r
+    public void testPrioritizeThresholdViolations() throws Exception {\r
+\r
+        Map<String, Threshold> thresholdMap = new HashMap<>();\r
+        Threshold majorThreshold = mock(Threshold.class);\r
+        when(majorThreshold.getSeverity()).thenReturn(EventSeverity.MAJOR);\r
+        thresholdMap.put("MAJOR", majorThreshold);\r
+\r
+        Threshold result1 = TCAUtils.prioritizeThresholdViolations(thresholdMap);\r
+        assertEquals(result1.getSeverity(), EventSeverity.MAJOR);\r
+\r
+        Threshold criticalThreshold = mock(Threshold.class);\r
+        when(criticalThreshold.getSeverity()).thenReturn(EventSeverity.CRITICAL);\r
+        thresholdMap.put("CRITICAL", criticalThreshold);\r
+\r
+        Threshold result2 = TCAUtils.prioritizeThresholdViolations(thresholdMap);\r
+        assertEquals(result2.getSeverity(), EventSeverity.CRITICAL);\r
+    }\r
+\r
+    @Test\r
+    public void testCreateViolatedMetrics() throws Exception {\r
+        TCAPolicy tcaPolicy = getSampleTCAPolicy();\r
+        Threshold violatedThreshold = getCriticalThreshold();\r
+        String functionalRole = "Mfvs_eNodeB_RANKPI";\r
+        MetricsPerEventName result = TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, functionalRole);\r
+        assertThat(result.getPolicyScope(), is("resource=vFirewall;type=configuration"));\r
+        assertThat(result.getPolicyName(), is("configuration.dcae.microservice.tca.xml"));\r
+    }\r
+\r
+    @Test\r
+    public void testCreateViolatedMetricsWrongEventName() throws Exception {\r
+        expectedIllegalArgumentException.expect(MessageProcessingException.class);\r
+        expectedIllegalArgumentException.expectCause(isA(IllegalStateException.class));\r
+        String eventName = "badEventName";\r
+        expectedIllegalArgumentException.expectMessage("TCA Policy must contain eventName: " + eventName);\r
+        TCAPolicy tcaPolicy = getSampleTCAPolicy();\r
+        Threshold violatedThreshold = getCriticalThreshold();\r
+        TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, eventName);\r
+    }\r
+\r
+    @Test\r
+    public void testGetDomainAndEventName() {\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+        EventListener eventListener = mock(EventListener.class);\r
+        Event event = mock(Event.class);\r
+        CommonEventHeader commonEventHeader = mock(CommonEventHeader.class);\r
+\r
+        Pair<String, String> result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);\r
+        assertNull(result.getLeft());\r
+        assertNull(result.getRight());\r
+\r
+        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(eventListener);\r
+        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);\r
+        assertNull(result.getLeft());\r
+        assertNull(result.getRight());\r
+\r
+        when(eventListener.getEvent()).thenReturn(event);\r
+        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);\r
+        assertNull(result.getLeft());\r
+        assertNull(result.getRight());\r
+\r
+        when(event.getCommonEventHeader()).thenReturn(commonEventHeader);\r
+        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);\r
+        assertNull(result.getLeft());\r
+        assertNull(result.getRight());\r
+\r
+        when(commonEventHeader.getDomain()).thenReturn(Domain.other);\r
+        when(commonEventHeader.getEventName()).thenReturn("eventName");\r
+\r
+        result = TCAUtils.getDomainAndEventName(tcacefProcessorContext);\r
+        assertEquals(result.getLeft(), "other");\r
+        assertEquals(result.getRight(), "eventName");\r
+\r
+    }\r
+\r
+    @Test\r
+    public void testComputeThresholdViolationsNotPresent() throws Exception {\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+        when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true);\r
+        when(tcacefProcessorContext.getMessage()).thenReturn(getValidCEFMessage());\r
+\r
+        when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy());\r
+        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+\r
+        TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext);\r
+        assertNotNull(result);\r
+        verify(result, times(0)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class));\r
+        assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy());\r
+    }\r
+\r
+    @Test\r
+    public void testComputeThresholdViolationsPresent() throws Exception {\r
+        TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class);\r
+        when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true);\r
+        final String cefMessageString = fromStream(CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION);\r
+        when(tcacefProcessorContext.getMessage()).thenReturn(cefMessageString);\r
+\r
+        when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy());\r
+        when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+\r
+        TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext);\r
+        verify(result, times(1)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class));\r
+\r
+        assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy());\r
+    }\r
+\r
+\r
+    @Test\r
+    public void testCreateTCAPolicyMetricsPerKeyName() throws Exception {\r
+\r
+        final Map<String, String> tcaPolicyMap = TCAUtils.filterMapByKeyNamePrefix(getControllerRuntimeArguments(),\r
+                AnalyticsConstants.TCA_POLICY_METRICS_PER_FUNCTIONAL_ROLE_PATH);\r
+\r
+        // determine functional Roles\r
+        final Map<String, Map<String, String>> functionalRolesMap =\r
+                TCAUtils.extractSubTree(tcaPolicyMap, 2, 3, AnalyticsConstants.TCA_POLICY_DELIMITER);\r
+\r
+        final List<MetricsPerEventName> tcaPolicyMetricsPerEventNameList =\r
+                TCAUtils.createTCAPolicyMetricsPerEventNameList(functionalRolesMap);\r
+\r
+        assertThat("There are two Metrics per function role", 2,\r
+                is(tcaPolicyMetricsPerEventNameList.size()));\r
+    }\r
+\r
+\r
+    @Test\r
+    public void testCreateQuartzScheduler() throws Exception {\r
+        final Scheduler scheduler = Mockito.mock(Scheduler.class);\r
+        final StdSchedulerFactory stdSchedulerFactory = Mockito.mock(StdSchedulerFactory.class);\r
+        when(stdSchedulerFactory.getScheduler()).thenReturn(scheduler);\r
+        final JobDataMap jobDataMap = Mockito.mock(JobDataMap.class);\r
+        TCAUtils.createQuartzScheduler(1000, stdSchedulerFactory,\r
+                "data/properties/quartz-test.properties", jobDataMap, Job.class,\r
+                "testJob", "testTigger");\r
+        verify(scheduler, times(1))\r
+                .scheduleJob(Mockito.any(JobDetail.class), Mockito.any(SimpleTrigger.class));\r
+    }\r
+\r
+\r
+    @Test\r
+    public void testCreateTCAAlertStringWhenCEFIsEnabled() throws Exception {\r
+        final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.CRITICAL);\r
+        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);\r
+        when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics);\r
+        when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+        final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", true);\r
+        assertTrue(alertString.contains("thresholdCrossingAlertFields"));\r
+    }\r
+\r
+    @Test(expected = MessageProcessingException.class)\r
+    public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsEnabled() throws Exception {\r
+        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);\r
+        when(processorContext.getMetricsPerEventName()).thenReturn(null);\r
+        TCAUtils.createTCAAlertString(processorContext, "testApp", true);\r
+    }\r
+\r
+    @Test\r
+    public void testCreateTCAAlertStringWhenCEFIsDisabled() throws Exception {\r
+        final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.MAJOR);\r
+        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);\r
+        when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics);\r
+        when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener());\r
+        final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", false);\r
+        assertFalse(alertString.contains("thresholdCrossingAlertFields"));\r
+    }\r
+\r
+    @Test(expected = MessageProcessingException.class)\r
+    public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsDisabled() throws Exception {\r
+        TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class);\r
+        when(processorContext.getMetricsPerEventName()).thenReturn(null);\r
+        TCAUtils.createTCAAlertString(processorContext, "testApp", false);\r
+    }\r
+\r
+    private static MetricsPerEventName createViolatedMetricsPerEventName(EventSeverity severity) {\r
+        final Threshold violatedThreshold = new Threshold();\r
+        violatedThreshold.setSeverity(severity);\r
+        violatedThreshold.setDirection(Direction.GREATER);\r
+        violatedThreshold.setClosedLoopControlName("violatedThresholdClosedLoopName");\r
+        violatedThreshold.setActualFieldValue(100L);\r
+        violatedThreshold.setFieldPath("violatedThresholdFieldPath");\r
+        violatedThreshold.setVersion("violatedThresholdVersion");\r
+        violatedThreshold.setClosedLoopEventStatus(ClosedLoopEventStatus.ONSET);\r
+        violatedThreshold.setThresholdValue(50L);\r
+\r
+        final MetricsPerEventName violatedMetrics = new MetricsPerEventName();\r
+        violatedMetrics.setPolicyName("violatePolicyName");\r
+        violatedMetrics.setPolicyVersion("violatedPolicyVersion");\r
+        violatedMetrics.setPolicyScope("violatedPolicyScope");\r
+        violatedMetrics.setEventName("violatedEventName");\r
+        violatedMetrics.setThresholds(Arrays.asList(violatedThreshold));\r
+        return violatedMetrics;\r
+    }\r
+}\r