543326ca858e8340274cff351a0071881dc94bd0
[aai/sparky-be.git] / sparkybe-onap-service / src / test / java / org / onap / aai / sparky / viewandinspect / BaseVisualizationContextTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.sparky.viewandinspect;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26
27 import java.io.InputStream;
28 import java.security.SecureRandom;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.concurrent.ExecutorService;
34
35 import javax.inject.Inject;
36
37 import org.eclipse.persistence.jaxb.JAXBContextProperties;
38 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
39 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
40 import org.hamcrest.Matcher;
41 import org.junit.Before;
42 import org.junit.Test;
43 import org.junit.runner.RunWith;
44 import org.mockito.ArgumentMatcher;
45 import org.mockito.Matchers;
46 import org.mockito.Mockito;
47 import org.onap.aai.cl.api.Logger;
48 import org.onap.aai.cl.eelf.LoggerFactory;
49 import org.onap.aai.cl.mdc.MdcContext;
50 import org.onap.aai.restclient.client.OperationResult;
51 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
52 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
53 import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig;
54 import org.onap.aai.sparky.sync.entity.SearchableEntity;
55 import org.onap.aai.sparky.util.NodeUtils;
56 import org.onap.aai.sparky.util.StringCollectionContainsMatcher;
57 import org.onap.aai.sparky.util.TestResourceLoader;
58 import org.onap.aai.sparky.viewandinspect.config.VisualizationConfigs;
59 import org.onap.aai.sparky.viewandinspect.context.BaseVisualizationContext;
60 import org.onap.aai.sparky.viewandinspect.entity.ActiveInventoryNode;
61 import org.onap.aai.sparky.viewandinspect.entity.QueryParams;
62 import org.onap.aai.sparky.viewandinspect.enumeration.NodeProcessingState;
63 import org.springframework.test.context.ContextConfiguration;
64 import org.springframework.test.context.TestPropertySource;
65 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
66
67
68
69 @RunWith(SpringJUnit4ClassRunner.class)
70 @TestPropertySource(properties = {
71 "schemaIngestPropLoc = src/test/resources/oxm-reader/schema-ingest-single-oxm.properties" })
72 @ContextConfiguration(locations = { "classpath:oxm-reader/oxm-reader-bean.xml" })
73
74
75 public class BaseVisualizationContextTest {
76
77   private static SecureRandom secureRandom = new SecureRandom();
78   private static Logger LOG =
79       LoggerFactory.getInstance().getLogger(BaseVisualizationContextTest.class);
80
81   private BaseVisualizationContext baseVisualizationContext;
82   private ExecutorService aaiExecutorService;
83   private VisualizationConfigs visualizationConfig; 
84
85   private ActiveInventoryAdapter aaiAdapter;
86   private RestEndpointConfig aaiRestEndPointConfig; 
87   
88   @Inject
89   private OxmEntityLookup oxmEntityLookup;
90   
91   @Before
92   public void init() throws Exception {
93
94     aaiExecutorService = NodeUtils.createNamedExecutor("SLNC-WORKER", 5, LOG);
95     visualizationConfig = new VisualizationConfigs();
96     
97     ArrayList<String> shallowEntities = new ArrayList<String>();
98     shallowEntities.add("cloud-region");
99     
100     visualizationConfig.setShallowEntities(shallowEntities);
101     visualizationConfig.setMaxSelfLinkTraversalDepth(2); 
102
103
104     aaiAdapter = Mockito.mock(ActiveInventoryAdapter.class);
105
106     aaiRestEndPointConfig = new RestEndpointConfig();
107     aaiRestEndPointConfig.setNumRequestRetries(5);
108     
109     Mockito.when(aaiAdapter.getEndpointConfig()).thenReturn(aaiRestEndPointConfig);
110     
111     MdcContext.initialize("" + secureRandom.nextLong(), "AAI-UI", "", "partner-name",
112         "localhost:4242");
113     
114     // all our resources are prefixed already, so the repairSelfLink shouldn't do anything to the link
115     Mockito.when(aaiAdapter.repairSelfLink(Matchers.contains(""))).thenReturn("");
116
117     
118   }
119
120   private ArgumentMatcher<List<String>> listContainsValue(String expectedValue) {
121     return new StringCollectionContainsMatcher(expectedValue);
122   }
123
124
125   @Test
126   public void validateBasicConstruction() throws Exception {
127
128     long contextId = secureRandom.nextLong();
129
130     baseVisualizationContext = new BaseVisualizationContext(contextId, aaiAdapter,
131         aaiExecutorService, visualizationConfig, oxmEntityLookup);
132
133     assertEquals(contextId, baseVisualizationContext.getContextId());
134
135   }
136
137   @Test
138   public void validateSmallGraphAssembly() throws Exception {
139
140     /**
141      * We have a tiny graph that we will validate assembly of:
142      * 
143      * <li>customer -> tenant
144      * <li>customer -> service-subscription
145      * <li>service-subscription -> service-instance-1
146      * <li>service-subscription -> service-instance-2
147      * 
148      * At the end of this success path, we should have 5 nodes in the node cache. Once we have this
149      * flow we can experiment with error paths involving resource download failures to ensure graph
150      * nodes are in the correct state and that expected nodes are successfully represented in the
151      * cache.
152      */
153
154     long contextId = secureRandom.nextLong();
155
156     baseVisualizationContext = new BaseVisualizationContext(contextId, aaiAdapter,
157         aaiExecutorService, visualizationConfig, oxmEntityLookup);
158
159     SearchableEntity searchableEntity = new SearchableEntity();
160     String customerSelfLink =
161         "https://server.proxy:8443/aai/v11/business/customers/customer/customer-4";
162     String customerNodeId = NodeUtils.generateUniqueShaDigest(customerSelfLink);
163
164     searchableEntity.setId(customerNodeId);
165     searchableEntity.setEntityType("customer");
166     searchableEntity.setEntityPrimaryKeyValue("customer-4");
167     searchableEntity.setLink(customerSelfLink);
168
169     QueryParams queryParams = new QueryParams();
170     queryParams.setSearchTargetNodeId(customerNodeId);
171     queryParams.setSearchTargetPrimaryKeyValues("customer-4");
172
173     // aai customer resource dip
174
175     Mockito
176         .when(aaiAdapter.queryActiveInventoryWithRetries(Matchers.contains("customer-4"),
177             Mockito.anyString(), Mockito.anyInt(),Mockito.anyString()))
178         .thenReturn(new OperationResult(200, TestResourceLoader
179             .getTestResourceDataJson("/sync/aai/aai-resources/customer/customer-4.json")));
180
181     // aai tenant resource dip
182
183     Mockito
184         .when(aaiAdapter.queryActiveInventoryWithRetries(Matchers.contains("tenant/tenant-1"),
185             Mockito.anyString(), Mockito.anyInt(),Mockito.anyString()))
186         .thenReturn(new OperationResult(200, TestResourceLoader
187             .getTestResourceDataJson("/sync/aai/aai-resources/tenant/tenant-1.json")));
188
189     // generic-queries for service-subscription
190
191     Mockito
192         .when(aaiAdapter.getGenericQueryForSelfLink(Matchers.contains("service-subscription"),
193             Matchers.argThat(
194                 listContainsValue("service-subscription.service-type:service-subscription-2"))))
195         .thenReturn(
196             "https://server.proxy:8443/aai/v11/search/generic-query/service-subscription-2");
197
198     Mockito
199         .when(aaiAdapter.queryActiveInventoryWithRetries(
200             Matchers.contains("generic-query/service-subscription-2"), Mockito.anyString(),
201             Mockito.anyInt(),Mockito.anyString()))
202         .thenReturn(new OperationResult(200, TestResourceLoader.getTestResourceDataJson(
203             "/sync/aai/aai-traversal/generic-query/service-subscription/service-subscription-2.json")));
204
205     // generic-queries for service-instance-1
206
207     Mockito
208         .when(aaiAdapter.getGenericQueryForSelfLink(Matchers.contains("service-instance"),
209             Matchers.argThat(listContainsValue("service-instance-id:service-instance-54"))))
210         .thenReturn(
211             "https://server.proxy:8443/aai/v11/search/generic-query/service-instance-id/service-instance-54");
212
213     Mockito
214         .when(aaiAdapter.queryActiveInventoryWithRetries(
215             Matchers.contains("generic-query/service-instance-id/service-instance-54"),
216             Mockito.anyString(), Mockito.anyInt(),Mockito.anyString()))
217         .thenReturn(new OperationResult(200, TestResourceLoader.getTestResourceDataJson(
218             "/sync/aai/aai-traversal/generic-query/service-instance/service-instance-54.json")));
219
220     // generic-queries for service-instance-2
221
222     Mockito
223         .when(aaiAdapter.getGenericQueryForSelfLink(Matchers.contains("service-instance"),
224             Matchers.argThat(listContainsValue("service-instance-id:service-instance-55"))))
225         .thenReturn(
226             "https://server.proxy:8443/aai/v11/search/generic-query/service-instance-id/service-instance-55");
227
228     Mockito
229         .when(aaiAdapter.queryActiveInventoryWithRetries(
230             Matchers.contains("generic-query/service-instance-id/service-instance-55"),
231             Mockito.anyString(), Mockito.anyInt(),Mockito.anyString()))
232         .thenReturn(new OperationResult(200, TestResourceLoader.getTestResourceDataJson(
233             "/sync/aai/aai-traversal/generic-query/service-instance/service-instance-55.json")));
234
235
236
237     // start the test
238
239     baseVisualizationContext.processSelfLinks(searchableEntity, queryParams);
240
241     /*
242      * validation can be in the form of validating nodes + relationships from the node cache
243      * baseVisualizationContext.getNodeCache();
244      */
245
246     Map<String, ActiveInventoryNode> nodeCache = baseVisualizationContext.getNodeCache();
247
248     assertEquals(5, nodeCache.size());
249     assertNotNull(nodeCache.get(customerNodeId));
250     assertEquals("customer", nodeCache.get(customerNodeId).getEntityType());
251
252     // verify node collection nodes
253
254     ActiveInventoryNode customerNode =
255         nodeCache.get("da4101ad19b3c380a1c12ffeda8ab390e1489fb4a22a392c9a1939db63c3dec5");
256     ActiveInventoryNode ssNode =
257         nodeCache.get("f4ceaf19459993c4fc9438a7579dd20d786109f4455e38682c579045b7ae615e");
258     ActiveInventoryNode tenantNode =
259         nodeCache.get("4735439b29e446b339535668238076e4b392eaa3eec218936e12f735179bc55e");
260     ActiveInventoryNode s1 =
261         nodeCache.get("f975ab453b142197af5d0173e0a9cf2aa22d10502f8ad655c8d17de81b066e8f");
262     ActiveInventoryNode s2 =
263         nodeCache.get("de77ef8f76dd6f19662b163527ff839891b9596cac655e3143fdd7ad39e2e4e3");
264
265     assertNotNull(customerNode);
266     assertNotNull(ssNode);
267     assertNotNull(tenantNode);
268     assertNotNull(s1);
269     assertNotNull(s2);
270
271     // verify node depths
272
273     assertEquals(0, customerNode.getNodeDepth());
274     assertEquals(1, ssNode.getNodeDepth());
275
276     /*
277      * I think there is a bug in the way the node depth is represented due to the enforcement of
278      * bidirectional links being disabled. We may have to circle back to this behavior at some point
279      * and re-verify that the behavior works properly.
280      */
281
282     assertEquals(2, tenantNode.getNodeDepth());
283     assertEquals(2, s1.getNodeDepth());
284     assertEquals(2, s2.getNodeDepth());
285
286     // verify node states
287
288     assertEquals(NodeProcessingState.READY, customerNode.getState());
289     assertEquals(NodeProcessingState.READY, ssNode.getState());
290
291     /*
292      * these nodes have a NEIGHBORS_UNPROCESSED state because the max traversal depth was hit before
293      * processing all the nested relationships. I think what we should look at is advancing the
294      * state to READY if in fact there are no relationships to process, which I think could be the
295      * case sometimes.
296      */
297     assertEquals(NodeProcessingState.NEIGHBORS_UNPROCESSED, tenantNode.getState());
298     assertEquals(NodeProcessingState.NEIGHBORS_UNPROCESSED, s1.getState());
299     assertEquals(NodeProcessingState.NEIGHBORS_UNPROCESSED, s2.getState());
300
301   }
302
303   protected DynamicJAXBContext createVersionedOxm() {    
304     Map<String, Object> properties = new HashMap<>(); 
305     ClassLoader classLoader = null;
306     InputStream iStream = classLoader.getResourceAsStream("example/resources/eclipselink/eclipselink-oxm.xml");
307
308     properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
309     try{
310     return DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties);
311     } catch (Exception e) {
312       return null;
313     }
314   } 
315
316
317 }