Adding back-end support for UI filters
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / viewandinspect / services / VisualizationService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.viewandinspect.services;
24
25 import java.io.IOException;
26 import java.security.SecureRandom;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ExecutorService;
30
31 import javax.servlet.ServletException;
32
33 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
34 import org.onap.aai.sparky.dal.aai.ActiveInventoryAdapter;
35 import org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider;
36 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
37 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryRestConfig;
38 import org.onap.aai.sparky.dal.cache.EntityCache;
39 import org.onap.aai.sparky.dal.cache.PersistentEntityCache;
40 import org.onap.aai.sparky.dal.elasticsearch.ElasticSearchAdapter;
41 import org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider;
42 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
43 import org.onap.aai.sparky.dal.rest.OperationResult;
44 import org.onap.aai.sparky.dal.rest.RestClientBuilder;
45 import org.onap.aai.sparky.dal.rest.RestfulDataAccessor;
46 import org.onap.aai.sparky.logging.AaiUiMsgs;
47 import org.onap.aai.sparky.synchronizer.entity.SearchableEntity;
48 import org.onap.aai.sparky.util.NodeUtils;
49 import org.onap.aai.sparky.viewandinspect.config.VisualizationConfig;
50 import org.onap.aai.sparky.viewandinspect.entity.ActiveInventoryNode;
51 import org.onap.aai.sparky.viewandinspect.entity.D3VisualizationOutput;
52 import org.onap.aai.sparky.viewandinspect.entity.GraphMeta;
53 import org.onap.aai.sparky.viewandinspect.entity.QueryParams;
54 import org.onap.aai.sparky.viewandinspect.entity.QueryRequest;
55 import org.onap.aai.cl.api.Logger;
56 import org.onap.aai.cl.eelf.LoggerFactory;
57
58 import com.fasterxml.jackson.annotation.JsonInclude.Include;
59 import com.fasterxml.jackson.core.JsonProcessingException;
60 import com.fasterxml.jackson.databind.DeserializationFeature;
61 import com.fasterxml.jackson.databind.JsonNode;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63
64 public class VisualizationService {
65
66   private static final Logger LOG =
67       LoggerFactory.getInstance().getLogger(VisualizationService.class);
68
69   private OxmModelLoader loader;
70   private ObjectMapper mapper = new ObjectMapper();
71
72   private final ActiveInventoryDataProvider aaiProvider;
73   private final ActiveInventoryRestConfig aaiRestConfig;
74   private final ElasticSearchDataProvider esProvider;
75   private final ElasticSearchConfig esConfig;
76   private final ExecutorService aaiExecutorService;
77
78   private ConcurrentHashMap<Long, VisualizationContext> contextMap;
79   private final SecureRandom secureRandom;
80
81   private ActiveInventoryConfig aaiConfig;
82   private VisualizationConfig visualizationConfig;
83
84   public VisualizationService(OxmModelLoader loader) throws Exception {
85     this.loader = loader;
86
87     aaiRestConfig = ActiveInventoryConfig.getConfig().getAaiRestConfig();
88
89     EntityCache cache = null;
90     secureRandom = new SecureRandom();
91
92     ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder());
93
94     if (aaiRestConfig.isCacheEnabled()) {
95       cache = new PersistentEntityCache(aaiRestConfig.getStorageFolderOverride(),
96           aaiRestConfig.getNumCacheWorkers());
97
98       aaiAdapter.setCacheEnabled(true);
99       aaiAdapter.setEntityCache(cache);
100     }
101
102     this.aaiProvider = aaiAdapter;
103
104     RestClientBuilder esClientBuilder = new RestClientBuilder();
105     esClientBuilder.setUseHttps(false);
106     RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(esClientBuilder);
107     this.esConfig = ElasticSearchConfig.getConfig();
108     this.esProvider = new ElasticSearchAdapter(nonCachingRestProvider, this.esConfig);
109
110     this.mapper = new ObjectMapper();
111     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
112
113     this.contextMap = new ConcurrentHashMap<Long, VisualizationContext>();
114     this.visualizationConfig = VisualizationConfig.getConfig();
115     this.aaiConfig = ActiveInventoryConfig.getConfig();
116     this.aaiExecutorService = NodeUtils.createNamedExecutor("SLNC-WORKER",
117         aaiConfig.getAaiRestConfig().getNumResolverWorkers(), LOG);
118   }
119
120   public OxmModelLoader getLoader() {
121     return loader;
122   }
123
124   public void setLoader(OxmModelLoader loader) {
125     this.loader = loader;
126   }
127
128   /**
129    * Analyze query request body.
130    *
131    * @param queryRequestJson the query request json
132    * @return the query request
133    */
134
135   public QueryRequest analyzeQueryRequestBody(String queryRequestJson) {
136
137
138     LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
139         "analyzeQueryRequestBody()," + " queryRequestJson = " + queryRequestJson);
140
141     ObjectMapper nonEmptyMapper = new ObjectMapper();
142     nonEmptyMapper.setSerializationInclusion(Include.NON_EMPTY);
143
144     QueryRequest queryBody = null;
145
146     try {
147       queryBody = nonEmptyMapper.readValue(queryRequestJson, QueryRequest.class);
148     } catch (Exception exc) {
149       LOG.error(AaiUiMsgs.EXCEPTION_CAUGHT, "Analyzing query request body.",
150           exc.getLocalizedMessage());
151     }
152
153     return queryBody;
154
155   }
156
157   /**
158    * Log optime.
159    *
160    * @param method the method
161    * @param opStartTimeInMs the op start time in ms
162    */
163   private void logOptime(String method, long opStartTimeInMs) {
164     LOG.info(AaiUiMsgs.OPERATION_TIME, method,
165         String.valueOf(System.currentTimeMillis() - opStartTimeInMs));
166   }
167
168   private SearchableEntity extractSearchableEntityFromElasticEntity(
169       OperationResult operationResult) {
170     if (operationResult == null || !operationResult.wasSuccessful()) {
171       // error, return empty collection
172       return null;
173     }
174
175     SearchableEntity sourceEntity = null;
176     if (operationResult.wasSuccessful()) {
177
178       try {
179         JsonNode elasticValue = mapper.readValue(operationResult.getResult(), JsonNode.class);
180
181         if (elasticValue != null) {
182           JsonNode sourceField = elasticValue.get("_source");
183
184           if (sourceField != null) {
185             sourceEntity = new SearchableEntity();
186
187             String entityType = NodeUtils.extractFieldValueFromObject(sourceField, "entityType");
188             sourceEntity.setEntityType(entityType);
189             String entityPrimaryKeyValue =
190                 NodeUtils.extractFieldValueFromObject(sourceField, "entityPrimaryKeyValue");
191             sourceEntity.setEntityPrimaryKeyValue(entityPrimaryKeyValue);
192             String link = NodeUtils.extractFieldValueFromObject(sourceField, "link");
193             sourceEntity.setLink(link);
194             String lastmodTimestamp =
195                 NodeUtils.extractFieldValueFromObject(sourceField, "lastmodTimestamp");
196             sourceEntity.setEntityTimeStamp(lastmodTimestamp);
197           }
198         }
199       } catch (IOException ioe) {
200         LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, "a json node ", ioe.getLocalizedMessage());
201       }
202     }
203     return sourceEntity;
204   }
205
206   /**
207    * Builds the visualization using generic query.
208    *
209    * @param queryRequest the query request
210    * @return the operation result
211    */
212   public OperationResult buildVisualizationUsingGenericQuery(QueryRequest queryRequest) {
213
214     OperationResult returnValue = new OperationResult();
215     OperationResult dataCollectionResult = null;
216     QueryParams queryParams = null;
217     SearchableEntity sourceEntity = null;
218
219     try {
220
221       /*
222        * Here is where we need to make a dip to elastic-search for the self-link by entity-id (link
223        * hash).
224        */
225       dataCollectionResult = esProvider.retrieveEntityById(queryRequest.getHashId());
226       sourceEntity = extractSearchableEntityFromElasticEntity(dataCollectionResult);
227
228       if (sourceEntity != null) {
229         sourceEntity.generateId();
230       }
231
232       queryParams = new QueryParams();
233       queryParams.setSearchTargetNodeId(queryRequest.getHashId());
234
235     } catch (Exception e1) {
236       LOG.error(AaiUiMsgs.FAILED_TO_GET_NODES_QUERY_RESULT, e1.getLocalizedMessage());
237       dataCollectionResult = new OperationResult(500, "Failed to get nodes-query result from AAI");
238     }
239
240     if (dataCollectionResult.getResultCode() == 200) {
241
242       String d3OutputJsonOutput = null;
243
244       try {
245
246         d3OutputJsonOutput = getVisualizationOutputBasedonGenericQuery(sourceEntity, queryParams);
247
248         if (LOG.isDebugEnabled()) {
249           LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
250               "Generated D3" + " output as json = " + d3OutputJsonOutput);
251         }
252
253         if (d3OutputJsonOutput != null) {
254           returnValue.setResultCode(200);
255           returnValue.setResult(d3OutputJsonOutput);
256         } else {
257           returnValue.setResult(500, "Failed to generate D3 graph visualization");
258         }
259
260       } catch (Exception exc) {
261         returnValue.setResult(500,
262             "Failed to generate D3 graph visualization, due to a servlet exception.");
263         LOG.error(AaiUiMsgs.ERROR_D3_GRAPH_VISUALIZATION, exc.getLocalizedMessage());
264       }
265     } else {
266       returnValue.setResult(dataCollectionResult.getResultCode(), dataCollectionResult.getResult());
267     }
268
269     return returnValue;
270
271   }
272
273   /**
274    * Gets the visualization output basedon generic query.
275    *
276    * @param searchtargetEntity entity that will be used to start visualization flow
277    * @param queryParams the query params
278    * @return the visualization output basedon generic query
279    * @throws ServletException the servlet exception
280    */
281   private String getVisualizationOutputBasedonGenericQuery(SearchableEntity searchtargetEntity,
282       QueryParams queryParams) throws ServletException {
283
284     long opStartTimeInMs = System.currentTimeMillis();
285
286     VisualizationTransformer transformer = null;
287     try {
288       transformer = new VisualizationTransformer();
289     } catch (Exception exc) {
290       throw new ServletException(
291           "Failed to create VisualizationTransformer instance because of execption", exc);
292     }
293
294     VisualizationContext visContext = null;
295     long contextId = secureRandom.nextLong();
296     try {
297       visContext = new VisualizationContext(contextId, aaiProvider, aaiExecutorService, loader);
298       contextMap.putIfAbsent(contextId, visContext);
299     } catch (Exception e1) {
300       LOG.error(AaiUiMsgs.EXCEPTION_CAUGHT,
301           "While building Visualization Context, " + e1.getLocalizedMessage());
302       throw new ServletException(e1);
303     }
304
305     String jsonResponse = null;
306
307     long startTimeInMs = System.currentTimeMillis();
308
309     visContext.processSelfLinks(searchtargetEntity, queryParams);
310     contextMap.remove(contextId);
311
312     logOptime("collectSelfLinkNodes()", startTimeInMs);
313
314     /*
315      * Flatten the graphs into a set of Graph and Link nodes. In this method I want the node graph
316      * resulting from the edge-tag-query to be represented first, and then we'll layer in
317      * relationship data.
318      */
319     long overlayDataStartTimeInMs = System.currentTimeMillis();
320
321     Map<String, ActiveInventoryNode> cachedNodeMap = visContext.getNodeCache();
322
323     if (LOG.isDebugEnabled()) {
324
325       StringBuilder sb = new StringBuilder(128);
326
327       sb.append("\nCached Node Map:\n");
328       for (String k : cachedNodeMap.keySet()) {
329         sb.append("\n----");
330         sb.append("\n").append(cachedNodeMap.get(k).dumpNodeTree(true));
331       }
332
333       LOG.debug(AaiUiMsgs.DEBUG_GENERIC, sb.toString());
334     }
335
336     transformer.buildFlatNodeArrayFromGraphCollection(cachedNodeMap);
337     transformer.buildLinksFromGraphCollection(cachedNodeMap);
338
339     /*
340      * - Apply configuration-driven styling - Build the final transformation response object - Use
341      * information we have to populate the GraphMeta object
342      */
343
344     transformer.addSearchTargetAttributesToRootNode();
345
346     GraphMeta graphMeta = new GraphMeta();
347
348     D3VisualizationOutput output = null;
349     try {
350       output = transformer
351           .generateVisualizationOutput((System.currentTimeMillis() - opStartTimeInMs), graphMeta);
352     } catch (Exception exc) {
353       LOG.error(AaiUiMsgs.FAILURE_TO_PROCESS_REQUEST, exc.getLocalizedMessage());
354       throw new ServletException("Caught an exception while generation visualization output", exc);
355     }
356
357     output.setInlineMessage(visContext.getInlineMessage());
358     output.getGraphMeta().setNumLinkResolveFailed(visContext.getNumFailedLinkResolve());
359     output.getGraphMeta().setNumLinksResolvedSuccessfullyFromCache(
360         visContext.getNumSuccessfulLinkResolveFromCache());
361     output.getGraphMeta().setNumLinksResolvedSuccessfullyFromServer(
362         visContext.getNumSuccessfulLinkResolveFromFromServer());
363
364     try {
365       jsonResponse = transformer.convertVisualizationOutputToJson(output);
366     } catch (JsonProcessingException jpe) {
367       throw new ServletException(
368           "Caught an exception while converting visualization output to json", jpe);
369     }
370
371     logOptime("[build flat node array, add relationship data, search target,"
372         + " color scheme, and generate visualization output]", overlayDataStartTimeInMs);
373
374     logOptime("doFilter()", opStartTimeInMs);
375
376     return jsonResponse;
377
378   }
379
380   public void shutdown() {
381     aaiProvider.shutdown();
382     aaiExecutorService.shutdown();
383     esProvider.shutdown();
384   }
385 }