Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / elk / client / PolicyElasticSearchController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.elk.client;
22
23
24 import java.io.File;
25 import java.io.PrintWriter;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.regex.Pattern;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.json.JSONObject;
37 import org.openecomp.policy.adapter.ClosedLoopPerformanceMetrics;
38 import org.openecomp.policy.adapter.ClosedLoopPolicy;
39 import org.openecomp.policy.dao.PolicyVersionDao;
40 import org.openecomp.policy.elk.client.ElkConnector.PolicyIndexType;
41 import org.openecomp.policy.rest.dao.DescriptiveScopeDao;
42 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
43 import org.openecomp.policy.rest.jpa.Attribute;
44 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
45 import org.openecomp.policy.rest.jpa.ClosedLoopD2Services;
46 import org.openecomp.policy.rest.jpa.ClosedLoopSite;
47 import org.openecomp.policy.rest.jpa.DCAEuuid;
48 import org.openecomp.policy.rest.jpa.DecisionSettings;
49 import org.openecomp.policy.rest.jpa.DescriptiveScope;
50 import org.openecomp.policy.rest.jpa.EcompName;
51 import org.openecomp.policy.rest.jpa.EnforcingType;
52 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
53 import org.openecomp.policy.rest.jpa.MicroServiceLocation;
54 import org.openecomp.policy.rest.jpa.MicroServiceModels;
55 import org.openecomp.policy.rest.jpa.PEPOptions;
56 import org.openecomp.policy.rest.jpa.PolicyVersion;
57 import org.openecomp.policy.rest.jpa.RiskType;
58 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
59 import org.openecomp.policy.rest.jpa.TermList;
60 import org.openecomp.policy.rest.jpa.VNFType;
61 import org.openecomp.policy.rest.jpa.VSCLAction;
62 import org.openecomp.policy.rest.jpa.VarbindDictionary;
63 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.servlet.ModelAndView;
68
69 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
70 import org.openecomp.policy.common.logging.flexlogger.Logger;
71
72 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
73 import com.fasterxml.jackson.databind.DeserializationFeature;
74 import com.fasterxml.jackson.databind.JsonNode;
75 import com.fasterxml.jackson.databind.ObjectMapper;
76
77 @Controller
78 @RequestMapping({"/"})
79 public class PolicyElasticSearchController extends RestrictedBaseController{
80
81         private static final Logger logger = FlexLogger.getLogger(PolicyElasticSearchController.class);
82         private volatile HashMap<Path, String> filteredPolicies = new HashMap<Path, String>();
83         private List<JSONObject> policyNames = null;
84
85         enum Mode{
86                 attribute, ecompName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, enforcer, fwTerm, gocEventAlarm,
87                 gocTraversal, gocRootCause, gocVnfType, gocServerScope, gocHPEventSource, msDCAEUUID, msConfigName, msLocation, msModels,
88                 psGroupPolicy, safeRisk, safePolicyWarning
89         }
90         
91         public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
92                 private static final long serialVersionUID = 1L;
93                 {
94                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_TRINITY, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_TRINITY);
95                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VUSP, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_VUSP);
96                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_MCR, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_MCR);
97                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_GAMMA, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_GAMMA);     
98                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VDNS, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_VDNS);
99
100                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_EMAIL_ADDRESS, ClosedLoopPolicy.CLFAULT_UIJSON_EMAIL_ADDRESS);
101                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_TRIGGER_SIGNATURE, ClosedLoopPolicy.CLFAULT_UIJSON_TRIGGER_SIGNATURE);
102                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_VERIFICATION_SIGNATURE, ClosedLoopPolicy.CLFAULT_UIJSON_VERIFICATION_SIGNATURE);
103                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_CONNECT_ALL_TRAPS, ClosedLoopPolicy.CLFAULT_UIJSON_CONNECT_ALL_TRAPS);     
104                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_CONNECT_ALL_FAULTS, ClosedLoopPolicy.CLFAULT_UIJSON_CONNECT_ALL_FAULTS);
105
106                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE, ClosedLoopPolicy.CLFAULT_UIJSON_POLICY_STATUS_ACTIVE);
107                         put(ClosedLoopPolicy.CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE, ClosedLoopPolicy.CLFAULT_UIJSON_POLICY_STATUS_INACTIVE);
108
109                         put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_ONSET_MESSAGE, ClosedLoopPerformanceMetrics.CLPM_UIJSON_ONSET_MESSAGE);
110                         put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_POLICY_NAME, ClosedLoopPerformanceMetrics.CLPM_UIJSON_POLICY_NAME);
111                         put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_ABATEMENT_MESSAGE, ClosedLoopPerformanceMetrics.CLPM_UIJSON_ABATEMENT_MESSAGE);
112                         put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_GEOLINK, ClosedLoopPerformanceMetrics.CLPM_UIJSON_GEOLINK);       
113                 }};
114
115
116                 //For AND and OR logical connector AND=0 and OR=1
117                 private int connectorSelected;
118
119                 public static DescriptiveScopeDao descriptiveScopeDao;
120                 public static PolicyVersionDao policyVersionDao;
121
122                 @Autowired
123                 public PolicyElasticSearchController(DescriptiveScopeDao descriptiveScopeDao, PolicyVersionDao policyVersionDao) {
124                         PolicyElasticSearchController.descriptiveScopeDao = descriptiveScopeDao;
125                         PolicyElasticSearchController.policyVersionDao = policyVersionDao;
126
127                 }
128
129                 public PolicyElasticSearchController() {
130                 }
131
132                 @RequestMapping(value={"/searchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
133                 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
134                         List<JSONObject> resultList = new ArrayList<JSONObject>();
135                         try {
136                                 ObjectMapper mapper = new ObjectMapper();
137                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
138                                 JsonNode root = mapper.readTree(request.getReader());
139                                 SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class);
140
141                                 String policyType = searchData.getPolicyType();
142                                 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
143
144                                 String searchText = searchData.getQuery();
145                                 if (searchText == null || searchText.isEmpty()) {
146                                         String descriptiveValue = searchData.getDescriptiveScope();
147                                         if(descriptiveValue != null){
148                                                 searchText = "Descriptive-Scope="+descriptiveValue;
149                                         }
150                                         if (policyType == null || policyType.isEmpty() &&
151                                                         !policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) {
152                                                 if (logger.isDebugEnabled()) {
153                                                         logger.debug("Clearing search filters, nothing to search and not closed loop.");
154                                                 }                                       
155                                         }
156                                 } else {
157                                         searchText = searchText.trim();
158                                         //Descriptive Scope. 
159                                         /*
160                                   When a item is selected in the "descriptiveScope" comboBox, the name of the item 
161                                   is added to the Search-Text Box with the prefix "Descriptive-Scope"
162                                   User needs to press the "Search" button to perform the search. 
163                                          */
164                                         if(searchText.contains("Descriptive-Scope=")){ 
165                                                 if (logger.isDebugEnabled()) {
166                                                         logger.debug("Inside the Descriptive Scope");
167                                                 }
168                                                 /*
169                                                 First item is always String "Descriptive-Scope" before the "=",
170                                                 So taking the second item of "split using ="
171                                                  */
172                                                 String[] dsName= searchText.split("=",2);
173                                                 /*
174                                                 Trying to find the search String by traversing different items from the dictionary by Scope-Name
175                                                 Once when the the "scope-name" is found, we get the search string from dictionary. 
176                                                  */
177                                                 if(searchData.getDescriptiveScope() != null){
178                                                         DescriptiveScope dsSearch = descriptiveScopeDao.getDescriptiveScopeById(searchData.getDescriptiveScope());
179                                                         if(dsSearch.getScopeName().equals(dsName[1])){
180                                                                 searchText=dsSearch.getSearch();
181                                                                 if (logger.isDebugEnabled()) {
182                                                                         logger.debug("DescriptiveScope Search String is " +searchText );
183                                                                 }
184                                                         }
185                                                 }
186
187                                         }
188                                         // '&' turned to "AND" to make it inline with Freeform search. 
189                                         if(searchText.contains(":")){
190                                                 String connector="AND";
191                                                 if(searchText.contains("AND")){
192                                                         connector="AND";
193                                                         connectorSelected=0;
194                                                 }else if(searchText.contains("OR")){
195                                                         connector=Pattern.quote("OR");
196                                                         connectorSelected=1;
197                                                 }
198                                                 for (String retval: searchText.split(connector)){
199
200                                                         int index= retval.indexOf(':');
201                                                         String filterKey=null;
202                                                         String filterValue=null;
203
204                                                         filterKey=retval.substring(0,index).trim();
205                                                         filterValue= retval.substring(index+1).trim();
206
207                                                         logger.debug("Key is "+filterKey+" and value is "+filterValue);
208                                                         String clSearchBoxFilter=filterKey;
209
210                                                         ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>();
211
212                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter);
213                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter);
214                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter);
215                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter);
216
217
218                                                         ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
219                                                         clSearchBoxFilterValue_s.add(filterValue);
220
221                                                         filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s));
222                                                 }
223                                         }
224                                 }
225
226                                 if (policyType != null && !policyType.isEmpty() && 
227                                                 policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) {
228
229                                         /* closed loop policy type */
230
231                                         String clPolicyType = searchData.getClosedLooppolicyType();
232                                         if (clPolicyType != null && !clPolicyType.isEmpty()) {                                                  
233                                                 ArrayList<String> clPolicyTypeField_s = new ArrayList<String>();
234                                                 clPolicyTypeField_s.add("Policy.PolicyType");
235
236                                                 ArrayList<String> clPolicyTypeValue_s = new ArrayList<String>();
237                                                 clPolicyTypeValue_s.add(clPolicyType);
238
239                                                 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clPolicyTypeField_s, clPolicyTypeValue_s));
240                                         }
241
242                                         String clEcompName = searchData.getEcompName();
243                                         if (clEcompName != null && !clEcompName.isEmpty()) {
244                                                 clSearchBody(clPolicyType, "ecompname", clEcompName, filter_s);
245                                         }
246
247                                         String clD2Services = searchData.getD2Service();
248                                         if (clD2Services != null && !clD2Services.isEmpty()) {
249                                                 switch (clD2Services) {
250                                                 case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_TRINITY:
251                                                 case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VUSP:                                         
252                                                 case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_MCR:                                          
253                                                 case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_GAMMA:                                                        
254                                                 case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VDNS: 
255                                                         clSearchBody(clPolicyType, name2jsonPath.get(clD2Services), "true", filter_s);
256                                                         break;
257                                                 default:
258                                                         if (logger.isWarnEnabled())
259                                                                 logger.warn("Unexpected D2 Service: " + clD2Services);
260                                                         break;
261                                                 }
262                                         }
263
264                                         String clFaultAction = searchData.getVproAction();
265                                         if (clFaultAction != null && !clFaultAction.isEmpty()) {
266                                                 if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) {
267                                                         clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "actions", clFaultAction, filter_s);
268                                                 }
269                                         }
270
271                                         String clFaultStatus = searchData.getPolicyStatus();
272                                         if (clFaultStatus != null && !clFaultStatus.isEmpty()) {
273                                                 if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) {
274                                                         clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "closedLoopPolicyStatus", clFaultStatus, filter_s);
275                                                 }
276                                         }
277
278                                         String clFaultVnfTypes = searchData.getVnfType();
279                                         if (clFaultVnfTypes != null && !clFaultVnfTypes.isEmpty()) {
280                                                 if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) {
281                                                         clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "vnfType", clFaultVnfTypes, filter_s);
282                                                 }
283                                         }
284
285                                         String clPMServiceType = searchData.getServiceType();
286                                         if (clPMServiceType != null && !clPMServiceType.isEmpty()) {
287                                                 if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_PM.name())) {
288                                                         clSearchFilter(ElkConnector.PolicyType.Config_PM.name(), "serviceTypePolicyName", clPMServiceType, filter_s);
289                                                 }
290                                         }
291
292                                         String clSearchBoxFilter = searchData.getBindTextSearch();
293                                         if (clSearchBoxFilter != null && !clSearchBoxFilter.isEmpty() && 
294                                                         searchText != null && !searchText.isEmpty()) {
295
296                                                 if (name2jsonPath.containsKey(clSearchBoxFilter)) {
297                                                         clSearchBoxFilter = name2jsonPath.get(clSearchBoxFilter);
298                                                 }                                               
299
300                                                 ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>();
301                                                 if (clPolicyType == null || clPolicyType.isEmpty()) {
302                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter);
303                                                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter);
304                                                 } else {
305                                                         clSearchBoxFilterField_s.add("Policy.Body." + clPolicyType + "_Body." + clSearchBoxFilter);
306                                                 }
307
308                                                 ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
309                                                 clSearchBoxFilterValue_s.add(searchText);
310
311                                                 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s));
312
313                                                 // deactivate search all fields in case a searchbox filter is provided
314                                                 searchText = "";
315                                         }
316                                 }
317
318                                 if ((searchText == null || searchText.isEmpty()) && 
319                                                 (filter_s == null || filter_s.size() <=0) ) {
320                                         if (logger.isWarnEnabled()) {
321                                                 logger.warn("Clearing search filters, closed loop but nothing to search nor filters");
322                                         }
323                                 }
324
325                                 ArrayList<PolicyLocator> locators = null;
326                                 try {
327                                         locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), 
328                                                         searchText, filter_s,connectorSelected);        
329                                 } catch (Exception ise) {
330                                         logger.warn("Search is unavailable: " + ise.getMessage());
331                                 }
332
333                                 synchronized(this.filteredPolicies) {
334                                         if (locators.isEmpty()) {
335                                                 if (logger.isInfoEnabled()) {
336                                                         logger.info("No match has been found");
337                                                 }
338                                                 logger.warn("No match has been found");
339                                         }
340
341                                         HashMap<String, Boolean> policyVersion_s = new HashMap<String, Boolean>();
342                                         List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionData();
343                                         for(int i = 0; i < policyVersionList.size(); i++) {
344                                                 PolicyVersion entityVersion = policyVersionList.get(i);
345                                                 String dbPolicy = entityVersion.getPolicyName() + "." + entityVersion.getActiveVersion();
346                                                 policyVersion_s.put(dbPolicy, true);
347                                                 if (logger.isDebugEnabled())
348                                                         logger.debug("Map addition: DB Policy Name: " + dbPolicy);
349                                         }
350
351                                         this.filteredPolicies.clear();
352                                         for (PolicyLocator p: locators) {
353                                                 String dbPolicyName = p.scope + File.separator  + p.policyType + "_" + p.policyName;
354                                                 if (policyVersion_s.containsKey(dbPolicyName)) {
355                                                         String filterPolicyName = dbPolicyName + ".xml";
356                                                         this.filteredPolicies.put(Paths.get(filterPolicyName), filterPolicyName);
357                                                         JSONObject el = new JSONObject();
358                                                         el.put("name", dbPolicyName);   
359                                                         resultList.add(el);
360                                                         if (logger.isInfoEnabled())
361                                                                 logger.info("Active Version Policy found in search: " + dbPolicyName + " -> " + filterPolicyName);
362                                                 } else {
363                                                         if (logger.isInfoEnabled()) 
364                                                                 logger.info("Inactive Version Policy found in search: " + dbPolicyName);                                                
365                                                 }
366                                         }
367
368                                         if (this.filteredPolicies.isEmpty()) {
369                                                 if (logger.isInfoEnabled()) {
370                                                         logger.info("No match has been found for active versions");
371                                                 }
372                                                 JSONObject result = new JSONObject();
373                                                 result.put("success", false);
374                                                 result.put("error", "No match has been found for active versions");
375                                                 resultList.add(result);
376                                                 logger.warn("No match has been found for active versions");
377
378                                         }
379
380                                         System.out.println(this.filteredPolicies);
381                                 }
382
383                                 response.setCharacterEncoding("UTF-8");
384                                 response.setContentType("application / json");
385                                 request.setCharacterEncoding("UTF-8");
386
387                                 PrintWriter out = response.getWriter();
388                                 JSONObject j = new JSONObject("{result: " + resultList + "}");
389                                 out.write(j.toString());
390                                 return null;
391                         }catch(Exception e){
392                                 response.setCharacterEncoding("UTF-8");
393                                 request.setCharacterEncoding("UTF-8");
394                                 PrintWriter out = response.getWriter();
395                                 out.write(e.getMessage());
396                         }
397                         return null;
398                 }
399
400                 protected void clSearchBody(String clPolicyType, String bodyField, String bodyValue,
401                                 ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) {
402                         if (logger.isDebugEnabled())
403                                 logger.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue);
404
405                         final ArrayList<String> clBodyField_s = new ArrayList<String>();
406                         final ArrayList<String> clBodyValue_s = new ArrayList<String>();
407
408                         if (clPolicyType == null || clPolicyType.isEmpty()) {
409                                 clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField);
410                                 clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField);
411                                 clBodyValue_s.add(bodyValue);
412                         } else {
413                                 clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField);
414                                 clBodyValue_s.add(bodyValue);
415                         }
416                         filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s));
417                 }
418
419                 protected void clSearchFilter(String clType, String clField, String clValue, 
420                                 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) {
421                         if (logger.isDebugEnabled())
422                                 logger.debug("ENTER: " + clType + ":" + clField + ":" + clValue);
423
424                         ArrayList<String> clSearchField_s = new ArrayList<String>();
425                         clSearchField_s.add("Policy.Body." + clType + "_Body." + clField);
426
427                         ArrayList<String> clSearchValue_s = new ArrayList<String>();
428                         clSearchValue_s.add(clValue);
429
430                         filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s));
431                 }
432
433                 public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
434                         if (type == null || type.isEmpty())
435                                 return PolicyIndexType.all;
436
437                         return PolicyIndexType.valueOf(type);
438                 }
439
440                 public boolean updateElk(String xacmlFilePath) {
441                         boolean success = true;
442                         try {
443                                 File xacmlPolicy = new File(xacmlFilePath);
444                                 success = ElkConnector.singleton.update(xacmlPolicy);
445                                 if (!success) {
446                                         if (logger.isWarnEnabled()) {
447                                                 logger.warn("FAILURE to create ELK record created for " + xacmlPolicy.getPath());
448                                         }
449                                 } else {
450                                         if (logger.isInfoEnabled()) {
451                                                 logger.warn("SUCCESS creating ELK record created for " + xacmlPolicy.getPath());
452                                         }                                                                       
453                                 }                                                                       
454                         } catch (Exception e) {
455                                 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
456                                 success = false;
457                         }
458                         return success;
459                 }
460
461                 @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
462                 public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
463                         try{
464                                 ObjectMapper mapper = new ObjectMapper();
465                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
466                                 JsonNode root = mapper.readTree(request.getReader());
467                                 String dictionaryType = root.get("type").textValue();
468                                 Mode mode = Mode.valueOf(dictionaryType);
469                                 String value;
470                                 String msg;
471                                 switch (mode){
472                                 case attribute :
473                                         Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
474                                         value = attributedata.getXacmlId();
475                                         msg = searchElkDatabase("pholder",value);
476                                         break;
477                                 case ecompName :
478                                         EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class);
479                                         value = ecompName.getEcompName();
480                                         msg = searchElkDatabase("pholder",value);
481                                         break;
482                                 case actionPolicy :
483                                         ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
484                                         value = actionPolicyDict.getAttributeName();
485                                         msg = searchElkDatabase("pholder",value);
486                                         break;
487                                 case brmsParam :
488                                         BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
489                                         value = bRMSParamTemplate.getRuleName();
490                                         msg = searchElkDatabase("BRMSParamTemplate AND " + value);
491                                         break;
492                                 case pepOptions :
493                                         PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
494                                         value = pEPOptions.getPepName();
495                                         msg = searchElkDatabase("pepName",value);
496                                         break;
497                                 case clSite :
498                                         ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
499                                         value = closedLoopSite.getSiteName();
500                                         msg = searchElkDatabase("siteNames",value);
501                                         break;
502                                 case clService :
503                                         ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
504                                         value = closedLoopD2Services.getServiceName();
505                                         msg = searchElkDatabase("d2Services",value);
506                                         break;
507                                 case clVarbind :
508                                         VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
509                                         value = varbindDictionary.getVarbindName();
510                                         msg = searchElkDatabase("triggerSignaturesUsedForUI.signatures",value);
511                                         break;
512                                 case clVnf :
513                                         VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
514                                         value = vNFType.getVnftype();
515                                         msg = searchElkDatabase("vnfType",value);
516                                         break;
517                                 case clVSCL :
518                                         VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
519                                         value = vsclAction.getVsclaction();
520                                         msg = searchElkDatabase("actions",value);
521                                         break;
522                                 case decision :
523                                         DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
524                                         value = decisionSettings.getXacmlId();
525                                         msg = searchElkDatabase("pholder",value);
526                                         break;
527                                 case enforcer :
528                                         EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class);
529                                         value = enforcingType.getEnforcingType();
530                                         msg = searchElkDatabase("pholder",value);
531                                         break;                  
532                                 case fwTerm :
533                                         TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
534                                         value = term.getTermName();
535                                         msg = searchElkDatabase("firewallRuleList.ruleName",value);
536                                         break;
537                                 case msDCAEUUID :
538                                         DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
539                                         value = dcaeUUID.getName();
540                                         msg = searchElkDatabase("uuid",value);
541                                         break;
542                                 case msLocation :
543                                         MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
544                                         value = mslocation.getName();
545                                         msg = searchElkDatabase("location",value);
546                                         break;
547                                 case msModels :
548                                         MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
549                                         value = msModels.getModelName();
550                                         msg = searchElkDatabase("configName",value);
551                                         break;
552                                 case psGroupPolicy :
553                                         GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
554                                         value = groupPoilicy.getGroupName();
555                                         msg = searchElkDatabase("PolicyScope",value);
556                                         break;
557                                 case safeRisk :
558                                         RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
559                                         value = riskType.getRiskName();
560                                         msg = searchElkDatabase("Risk Type",value);
561                                         break;
562                                 case safePolicyWarning :
563                                         SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
564                                         value = safePolicy.getName();
565                                         msg = searchElkDatabase("Safe Warning",value);
566                                         break;
567                                 default:                
568                                 }
569                                 response.setCharacterEncoding("UTF-8");
570                                 response.setContentType("application / json");
571                                 request.setCharacterEncoding("UTF-8");
572
573                                 PrintWriter out = response.getWriter();
574                                 JSONObject j = new JSONObject("{result: " + policyNames + "}");
575                                 out.write(j.toString());
576                                 return null;
577                         }catch(Exception e){
578                                 response.setCharacterEncoding("UTF-8");
579                                 request.setCharacterEncoding("UTF-8");
580                                 PrintWriter out = response.getWriter();
581                                 out.write(e.getMessage());
582                         }
583                         return null;
584                 }
585                 
586                 //Search Elk database
587                 public String searchElkDatabase(String value){
588                         String policyType = "";
589                         String searchText = value;
590                         ArrayList<PolicyLocator> locators;
591                         ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
592                         try {
593                                 locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0);        
594                         } catch (Exception ise) {
595                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
596                                 value = "$notSuccess%";
597                                 return value;
598                         }
599                         policyNames = new ArrayList<JSONObject>();
600                         for (PolicyLocator p: locators) {
601                                 String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName + "." +p.version + ".xml";
602                                 logger.debug(dbPolicyName);
603                                 JSONObject el = new JSONObject();
604                                 el.put("name", dbPolicyName);   
605                                 policyNames.add(el);
606                         }
607                         if(!locators.isEmpty()){
608                                 value = "$success%";
609                                 return value;
610                         }
611                         return value;
612                 }
613                 
614                 //Search the Elk database
615                 public String searchElkDatabase(String key, String value){
616                         String policyType = "";
617                         String searchText = key+":"+value;
618                         ArrayList<PolicyLocator> locators;
619                         ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
620                         logger.debug("Parameter value is"+value);
621
622                         String clSearchKey=null;
623                         clSearchKey=key;
624
625                         logger.debug("Filter value is"+clSearchKey);
626
627                         ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>();
628
629                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchKey);
630                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey);
631                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchKey);
632                         clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchKey);
633                         //clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey);
634
635                         String clSearchValue=null;
636                         clSearchValue=value;
637
638                         logger.debug("Search value is"+clSearchValue);
639
640                         ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
641                         clSearchBoxFilterValue_s.add(clSearchValue);
642
643                         filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s));
644
645                         try {
646                                 locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0);        
647                                 logger.debug("No Exceptions");
648                                 for (PolicyLocator l: locators) {
649                                         logger.debug(l.policyName);
650                                 }
651                                 logger.debug("After for");
652                         } catch (Exception ise) {
653                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
654                                 //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database ");
655                                 logger.debug("Exceptions");
656                                 value = "$notSuccess%";
657                                 return value;
658                         }
659                         policyNames = new ArrayList<JSONObject>();
660                         for (PolicyLocator p: locators) {
661                                 String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName + ".xml";
662                                 logger.debug(dbPolicyName);
663                                 JSONObject el = new JSONObject();
664                                 el.put("name", dbPolicyName);   
665                                 policyNames.add(el);
666                         }
667                         if(!locators.isEmpty()){
668                                 value = "$success%";
669                                 logger.debug("Success");
670                                 return value;
671                         }
672                         return value;
673                 }
674
675 }
676
677
678 class SearchData{
679         private String query;
680         private String policyType;
681         private String descriptiveScope;
682         private String closedLooppolicyType;
683         private String ecompName;
684         private String d2Service;
685         private String vnfType;
686         private String policyStatus;
687         private String vproAction;
688         private String serviceType;
689         private String bindTextSearch;
690         public String getQuery() {
691                 return query;
692         }
693         public void setQuery(String query) {
694                 this.query = query;
695         }
696         public String getPolicyType() {
697                 return policyType;
698         }
699         public void setPolicyType(String policyType) {
700                 this.policyType = policyType;
701         }
702         public String getDescriptiveScope() {
703                 return descriptiveScope;
704         }
705         public void setDescriptiveScope(String descriptiveScope) {
706                 this.descriptiveScope = descriptiveScope;
707         }
708         public String getClosedLooppolicyType() {
709                 return closedLooppolicyType;
710         }
711         public void setClosedLooppolicyType(String closedLooppolicyType) {
712                 this.closedLooppolicyType = closedLooppolicyType;
713         }
714         public String getEcompName() {
715                 return ecompName;
716         }
717         public void setEcompName(String ecompName) {
718                 this.ecompName = ecompName;
719         }
720         public String getD2Service() {
721                 return d2Service;
722         }
723         public void setD2Service(String d2Service) {
724                 this.d2Service = d2Service;
725         }
726         public String getVnfType() {
727                 return vnfType;
728         }
729         public void setVnfType(String vnfType) {
730                 this.vnfType = vnfType;
731         }
732         public String getPolicyStatus() {
733                 return policyStatus;
734         }
735         public void setPolicyStatus(String policyStatus) {
736                 this.policyStatus = policyStatus;
737         }
738         public String getVproAction() {
739                 return vproAction;
740         }
741         public void setVproAction(String vproAction) {
742                 this.vproAction = vproAction;
743         }
744         public String getServiceType() {
745                 return serviceType;
746         }
747         public void setServiceType(String serviceType) {
748                 this.serviceType = serviceType;
749         }
750         public String getBindTextSearch() {
751                 return bindTextSearch;
752         }
753         public void setBindTextSearch(String bindTextSearch) {
754                 this.bindTextSearch = bindTextSearch;
755         }
756 }